text:
using System;
using System.Collections.Generic;
using System.Linq;
using Cake.Core.Tests.Fixtures;
using Xunit;

namespace Cake.Core.Tests.Unit
{
    public sealed class CakeEngineTests
    {
        public sealed class TheConstructor
        {
            [Fact]
            public void Should_Throw_If_Log_Is_Null()
            {
                // Given
                var fixture = new CakeEngineFixture { Log = null };

                // When
                var result = Record.Exception(() => fixture.CreateEngine());

                // Then
                Assert.IsArgumentNullException(result, "log");
            }
        }

        public sealed class TheRegisterTaskMethod
        {
            [Fact]
            public void Should_Return_A_New_Task()
            {
                // Given
                var engine = new CakeEngineFixture().CreateEngine();

                // When
                var result = engine.RegisterTask("task");

                // Then
                Assert.NotNull(result);
                Assert.Equal("task", result.Task.Name);
            }

            [Fact]
            public void Should_Register_Created_Task()
            {
                // Given
                var engine = new CakeEngineFixture().CreateEngine();

                // When
                var result = engine.RegisterTask("task");

                // Then
                Assert.True(engine.Tasks.Contains(result.Task));
            }

            [Fact]
            public void Should_Throw_If_Another_Task_With_The_Same_Name_Already_Been_Added()
            {
                // Given
                var engine = new CakeEngineFixture().CreateEngine();
                engine.RegisterTask("task");

                // When
                var result = Record.Exception(() => engine.RegisterTask("task"));

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("Another task with the name 'task' has already been added.", result.Message);
            }

            [Fact]
            public void Should_Throw_If_Another_Task_With_The_Same_Name_Already_Been_Added_Regardless_Of_Casing()
            {
                // Given
                var engine = new CakeEngineFixture().CreateEngine();
                engine.RegisterTask("task");

                // When
                var result = Record.Exception(() => engine.RegisterTask("TASK"));

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("Another task with the name 'TASK' has already been added.", result.Message);
            }
        }

        public sealed class TheRunTargetMethod
        {
            public sealed class WithTarget
            {
                [Fact]
                public void Should_Throw_If_Target_Is_Null()
                {
                    // Given
                    var fixture = new CakeEngineFixture();
                    var engine = fixture.CreateEngine();

                    // When
                    var result = Record.Exception(() =>
                        engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, null));

                    // Then
                    Assert.IsArgumentNullException(result, "target");
                }
            }

            public sealed class WithExecutionStrategy
            {
                [Fact]
                public void Should_Throw_If_Target_Is_Null()
                {
                    // Given
                    var fixture = new CakeEngineFixture();
                    var engine = fixture.CreateEngine();

                    // When
                    var result = Record.Exception(() =>
                        engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, null));

                    // Then
                    Assert.IsArgumentNullException(result, "target");
                }

                [Fact]
                public void Should_Throw_If_Execution_Strategy_Is_Null()
                {
                    // Given
                    var fixture = new CakeEngineFixture();
                    var engine = fixture.CreateEngine();

                    // When
                    var result = Record.Exception(() => engine.RunTarget(fixture.Context, null, "A"));

                    // Then
                    Assert.IsArgumentNullException(result, "strategy");
                }
            }

            [Fact]
            public void Should_Execute_Tasks_In_Order()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A").Does(() => result.Add("A"));
                engine.RegisterTask("B").IsDependentOn("A").Does(() => result.Add("B"));
                engine.RegisterTask("C").IsDependentOn("B").Does(() => result.Add("C"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "C");

                // Then
                Assert.Equal(3, result.Count);
                Assert.Equal("A", result[0]);
                Assert.Equal("B", result[1]);
                Assert.Equal("C", result[2]);
            }

            [Fact]
            public void Should_Skip_Tasks_Where_Criterias_Are_Not_Fulfilled()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A").Does(() => result.Add("A"));
                engine.RegisterTask("B").IsDependentOn("A").WithCriteria(() => false).Does(() => result.Add("B"));
                engine.RegisterTask("C").IsDependentOn("B").Does(() => result.Add("C"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "C");

                // Then
                Assert.Equal(2, result.Count);
                Assert.Equal("A", result[0]);
                Assert.Equal("C", result[1]);
            }

            [Fact]
            public void Should_Not_Skip_Tasks_Where_Criterias_Are_Fulfilled()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A").Does(() => result.Add("A"));
                engine.RegisterTask("B").IsDependentOn("A").WithCriteria(() => true).Does(() => result.Add("B"));
                engine.RegisterTask("C").IsDependentOn("B").Does(() => result.Add("C"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "C");

                // Then
                Assert.Equal(3, result.Count);
                Assert.Equal("A", result[0]);
                Assert.Equal("B", result[1]);
                Assert.Equal("C", result[2]);
            }

            [Fact]
            public void Should_Throw_If_Target_Was_Not_Found()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "Run-Some-Tests"));

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("The target 'Run-Some-Tests' was not found.", result.Message);
            }

            [Fact]
            public void Should_Not_Catch_Exceptions_From_Task_If_ContinueOnError_Is_Not_Set()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A").Does(() => { throw new InvalidOperationException("Whoopsie"); });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Whoopsie", result.Message);
            }

            [Fact]
            public void Should_Swallow_Exceptions_If_ContinueOnError_Is_Set()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A").ContinueOnError().Does(() => { throw new InvalidOperationException(); });

                // When, Then
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");
            }

            [Fact]
            public void Should_Invoke_Task_Error_Handler_If_Exception_Is_Thrown()
            {
                // Given
                var invoked = false;
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Whoopsie"); })
                    .OnError(exception => { invoked = true; });

                // When
                Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.True(invoked);
            }

            [Fact]
            public void Should_Propagate_Exception_From_Error_Handler()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Whoopsie"); })
                    .OnError(exception => { throw new InvalidOperationException("Totally my fault"); });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Totally my fault", result.Message);
            }

            [Fact]
            public void Should_Log_Exception_Handled_By_Error_Handler()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Whoopsie"); })
                    .OnError(exception => { throw new InvalidOperationException("Totally my fault"); });

                // When
                Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.True(fixture.Log.Messages.Contains("Error: Whoopsie"));
            }

            [Fact]
            public void Should_Throw_If_Target_Cannot_Be_Reached_Due_To_Constraint()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A");
                engine.RegisterTask("B").IsDependentOn("A").WithCriteria(false);

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "B"));

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("Could not reach target 'B' since it was skipped due to a criteria.", result.Message);
            }

            [Fact]
            public void Should_Run_Setup_Before_First_Task()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterSetupAction(() => result.Add("Setup"));
                engine.RegisterTask("A").Does(() => result.Add("A"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");

                // Then
                Assert.Equal(2, result.Count);
                Assert.Equal("Setup", result[0]);
            }

            [Fact]
            public void Should_Not_Run_Tasks_If_Setup_Failed()
            {
                // Given
                var runTask = false;
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterSetupAction(() => { throw new InvalidOperationException("Fail"); });
                engine.RegisterTask("A").Does(() => runTask = true);

                // When
                Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.False(runTask, "Task A was executed although it shouldn't have been.");
                Assert.True(fixture.Log.Messages.Contains("Executing custom setup action..."));
            }

            [Fact]
            public void Should_Run_Teardown_After_Last_Running_Task()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterSetupAction(() => result.Add("Setup"));
                engine.RegisterTeardownAction(() => result.Add("Teardown"));
                engine.RegisterTask("A").Does(() => result.Add("A"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");

                // Then
                Assert.Equal(3, result.Count);
                Assert.Equal("Teardown", result[2]);
            }

            [Fact]
            public void Should_Run_Teardown_After_Last_Running_Task_Even_If_Task_Failed()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterSetupAction(() => { });
                engine.RegisterTeardownAction(() => { });
                engine.RegisterTask("A").Does(() => { throw new InvalidOperationException("Fail"); });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.NotNull(result);
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Fail", result.Message);
                Assert.True(fixture.Log.Messages.Contains("Executing custom teardown action..."));
            }

            [Fact]
            public void Should_Run_Teardown_If_Setup_Failed()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterSetupAction(() => { throw new InvalidOperationException("Fail"); });
                engine.RegisterTeardownAction(() => { });
                engine.RegisterTask("A").Does(() => { });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.NotNull(result);
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Fail", result.Message);
                Assert.True(fixture.Log.Messages.Contains("Executing custom teardown action..."));
            }

            [Fact]
            public void Should_Throw_Exception_Thrown_From_Setup_Action_If_Both_Setup_And_Teardown_Actions_Throw()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterSetupAction(() => { throw new InvalidOperationException("Setup"); });
                engine.RegisterTeardownAction(() => { throw new InvalidOperationException("Teardown"); });
                engine.RegisterTask("A").Does(() => { });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.NotNull(result);
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Setup", result.Message);
            }

            [Fact]
            public void Should_Throw_Exception_Occuring_In_Teardown_If_No_Previous_Exception_Was_Thrown()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                var expected = new InvalidOperationException("Teardown");

                engine.RegisterTeardownAction(() => { throw expected; });
                engine.RegisterTask("A").Does(() => { });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.Equal(expected, result);
            }

            [Fact]
            public void Should_Log_Teardown_Exception_If_Both_Setup_And_Teardown_Actions_Throw()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterSetupAction(() => { throw new InvalidOperationException("Setup"); });
                engine.RegisterTeardownAction(() => { throw new InvalidOperationException("Teardown"); });
                engine.RegisterTask("A").Does(() => { });

                // When
                Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.True(fixture.Log.Messages.Any(x => x.StartsWith("Teardown error:")));
            }

            [Fact]
            public void Should_Exception_Thrown_From_Task_If_Both_Task_And_Teardown_Actions_Throw()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterTeardownAction(() => { throw new InvalidOperationException("Teardown"); });
                engine.RegisterTask("A").Does(() => { throw new InvalidOperationException("Task"); });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.NotNull(result);
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Task", result.Message);
            }

            [Fact]
            public void Should_Log_Teardown_Exception_If_Both_Task_And_Teardown_Actions_Throw()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterTeardownAction(() => { throw new InvalidOperationException("Teardown"); });
                engine.RegisterTask("A").Does(() => { throw new InvalidOperationException("Task"); });

                // When
                Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.True(fixture.Log.Messages.Any(x => x.StartsWith("Teardown error:")));
            }

            [Fact]
            public void Should_Execute_Finally_Handler_If_Task_Succeeds()
            {
                // Given
                var invoked = false;
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Finally(() => invoked = true);

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");

                // Then
                Assert.True(invoked);
            }

            [Fact]
            public void Should_Execute_Finally_Handler_If_Task_Throws()
            {
                // Given
                var invoked = false;
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();

                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Whoopsie"); })
                    .ContinueOnError()
                    .Finally(() => invoked = true);

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");

                // Then
                Assert.True(invoked);
            }

            [Fact]
            public void Should_Execute_Finally_Handler_After_Error_Handler_If_Task_Succeeds()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Whoopsie"); })
                    .OnError(() => result.Add("Error"))
                    .Finally(() => result.Add("Finally"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");

                // Then
                Assert.Equal(2, result.Count);
                Assert.Equal("Error", result[0]);
            }

            [Fact]
            public void Should_Execute_Error_Reporter_Before_Error_Handler_If_Task_Succeeds()
            {
                // Given
                var result = new List<string>();
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Whoopsie"); })
                    .OnError(ex => result.Add("Error"))
                    .ReportError(ex => result.Add("Report"));

                // When
                engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A");

                // Then
                Assert.Equal(2, result.Count);
                Assert.Equal("Report", result[0]);
            }

            [Fact]
            public void Should_Swallow_Exceptions_Thrown_In_Error_Reporter()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Task"); })
                    .ReportError(ex => { throw new InvalidOperationException("Report"); });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.Equal("Task", result.Message);
            }

            [Fact]
            public void Should_Execute_Error_Handler_Even_If_Exception_Was_Thrown_In_Error_Reporter()
            {
                // Given
                var fixture = new CakeEngineFixture();
                var engine = fixture.CreateEngine();
                engine.RegisterTask("A")
                    .Does(() => { throw new InvalidOperationException("Task"); })
                    .OnError(() => { throw new InvalidOperationException("Error"); })
                    .ReportError(ex => { throw new InvalidOperationException("Report"); });

                // When
                var result = Record.Exception(() =>
                    engine.RunTarget(fixture.Context, fixture.ExecutionStrategy, "A"));

                // Then
                Assert.Equal("Error", result.Message);
            }
        }
    }
}


text:
#include <string>
using std::string;
#include "googleapis/client/data/data_reader.h"
#include "googleapis/client/data/jsoncpp_data.h"
#include "googleapis/client/util/status.h"
#include <glog/logging.h>
#include <json/reader.h>
#include <json/writer.h>

namespace googleapis {

namespace client {

JsonCppData::JsonCppData(const Json::Value& value)
  : is_mutable_(false), value_(const_cast<Json::Value*>(&value)) {
}
JsonCppData::JsonCppData(Json::Value* value)
  : is_mutable_(true), value_(value) {
}
JsonCppData::~JsonCppData() {
}

void JsonCppData::CheckIsMutable() const {
  CHECK(is_mutable_);
}

DataReader* JsonCppData::MakeJsonReader() const {
  Json::FastWriter writer;
  const string& json = writer.write(Storage());
  return NewManagedInMemoryDataReader(json);  // copy the data
}

util::Status JsonCppData::LoadFromJsonReader(DataReader* data_reader) {
  string storage = data_reader->RemainderToString();
  if (!data_reader->ok()) {
    return data_reader->status();
  }

  const char* data = storage.data();
  int64 size = storage.size();
  Json::Reader json_reader;
  bool result = json_reader.parse(data, data + size, *MutableStorage(), false);
  if (!result) {
	  return StatusInvalidArgument("");//json_reader.getFormattedErrorMessages());
  }
  return StatusOk();
}

util::Status JsonCppData::LoadFromJsonStream(std::istream* stream) {
  Json::Reader reader;
  bool result = reader.parse(*stream, *MutableStorage());
  if (!result) {
return StatusInvalidArgument(reader.getFormatedErrorMessages());
  }
  return StatusOk();
}

util::Status JsonCppData::StoreToJsonStream(std::ostream* stream) const {
  Json::StyledStreamWriter writer;
  writer.write(*stream, Storage());
  if (stream->fail()) {
    return StatusUnknown("Error storing JSON");
  }
  return StatusOk();
}

void JsonCppData::Clear() {
  MutableStorage()->clear();
}

JsonCppDictionary::JsonCppDictionary(const Json::Value& value)
  : JsonCppData(value) {
}

JsonCppDictionary::JsonCppDictionary(Json::Value* value)
  : JsonCppData(value) {
}

}  // namespace client

}  // namespace googleapis

redpajama_set_name: RedPajamaGithub


text:
package com.yahoo.ycsb.measurements;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;

import com.yahoo.ycsb.measurements.exporter.MeasurementsExporter;

class SeriesUnit
{
	/**
	 * @param time
	 * @param average
	 */
	public SeriesUnit(long time, double average) {
		this.time = time;
		this.average = average;
	}
	public long time;
	public double average;
}

/**
 * A time series measurement of a metric, such as READ LATENCY.
 */
public class OneMeasurementTimeSeries extends OneMeasurement
{
	/**
	 * Granularity for time series; measurements will be averaged in chunks of this granularity. Units are milliseconds.
	 */
	public static final String GRANULARITY="timeseries.granularity";

	public static final String GRANULARITY_DEFAULT="1000";

	int _granularity;
	Vector<SeriesUnit> _measurements;

	long start=-1;
	long currentunit=-1;
	int count=0;
	int sum=0;
	int operations=0;
	long totallatency=0;

	//keep a windowed version of these stats for printing status
	int windowoperations=0;
	long windowtotallatency=0;

	int min=-1;
	int max=-1;

	private HashMap<Integer, int[]> returncodes;

	public OneMeasurementTimeSeries(String name, Properties props)
	{
		super(name);
		_granularity=Integer.parseInt(props.getProperty(GRANULARITY,GRANULARITY_DEFAULT));
		_measurements=new Vector<SeriesUnit>();
		returncodes=new HashMap<Integer,int[]>();
	}

	void checkEndOfUnit(boolean forceend)
	{
		long now=System.currentTimeMillis();

		if (start<0)
		{
			currentunit=0;
			start=now;
		}

		long unit=((now-start)/_granularity)*_granularity;

		if ( (unit>currentunit) || (forceend) )
		{
			double avg=((double)sum)/((double)count);
			_measurements.add(new SeriesUnit(currentunit,avg));

			currentunit=unit;

			count=0;
			sum=0;
		}
	}

	@Override
	public void measure(int latency)
	{
		checkEndOfUnit(false);

		count++;
		sum+=latency;
		totallatency+=latency;
		operations++;
		windowoperations++;
		windowtotallatency+=latency;

		if (latency>max)
		{
			max=latency;
		}

		if ( (latency<min) || (min<0) )
		{
			min=latency;
		}
	}

  @Override
  public void exportMeasurements(MeasurementsExporter exporter) throws IOException
  {
    checkEndOfUnit(true);

    exporter.write(getName(), "Operations", operations);
    exporter.write(getName(), "AverageLatency(us)", (((double)totallatency)/((double)operations)));
    exporter.write(getName(), "MinLatency(us)", min);
    exporter.write(getName(), "MaxLatency(us)", max);

    //TODO: 95th and 99th percentile latency

    for (Integer I : returncodes.keySet())
    {
      int[] val=returncodes.get(I);
      exporter.write(getName(), "Return="+I, val[0]);
    }

    for (SeriesUnit unit : _measurements)
    {
      exporter.write(getName(), Long.toString(unit.time), unit.average);
    }
  }

	@Override
	public void reportReturnCode(int code) {
		Integer Icode=code;
		if (!returncodes.containsKey(Icode))
		{
			int[] val=new int[1];
			val[0]=0;
			returncodes.put(Icode,val);
		}
		returncodes.get(Icode)[0]++;

	}

	@Override
	public String getSummary() {
		if (windowoperations==0)
		{
			return "";
		}
		DecimalFormat d = new DecimalFormat("#.##");
		double report=((double)windowtotallatency)/((double)windowoperations);
		windowtotallatency=0;
		windowoperations=0;
		return "["+getName()+" AverageLatency(us)="+d.format(report)+"]";
	}

}


text:
package master

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"testing"
	"time"

	"github.com/go-openapi/spec"

	v1 "k8s.io/api/core/v1"
	networkingv1 "k8s.io/api/networking/v1"
	apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/test/integration/etcd"
	"k8s.io/kubernetes/test/integration/framework"
	utilpointer "k8s.io/utils/pointer"
)

func TestCRDShadowGroup(t *testing.T) {
	result := kubeapiservertesting.StartTestServerOrDie(t, nil, nil, framework.SharedEtcd())
	defer result.TearDownFn()

	testNamespace := "test-crd-shadow-group"
	kubeclient, err := kubernetes.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if _, err := kubeclient.CoreV1().Namespaces().Create(context.TODO(), (&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}), metav1.CreateOptions{}); err != nil {
		t.Fatal(err)
	}

	apiextensionsclient, err := apiextensionsclientset.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	t.Logf("Creating a NetworkPolicy")
	nwPolicy, err := kubeclient.NetworkingV1().NetworkPolicies(testNamespace).Create(context.TODO(), &networkingv1.NetworkPolicy{
		ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: testNamespace},
		Spec: networkingv1.NetworkPolicySpec{
			PodSelector: metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}},
			Ingress:     []networkingv1.NetworkPolicyIngressRule{},
		},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatalf("Failed to create NetworkPolicy: %v", err)
	}

	t.Logf("Trying to shadow networking group")
	crd := &apiextensionsv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{
			Name: "foos." + networkingv1.GroupName,
		},
		Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
			Group:   networkingv1.GroupName,
			Version: networkingv1.SchemeGroupVersion.Version,
			Scope:   apiextensionsv1beta1.ClusterScoped,
			Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
				Plural: "foos",
				Kind:   "Foo",
			},
		},
	}
	etcd.CreateTestCRDs(t, apiextensionsclient, true, crd)

	// wait to give aggregator time to update
	time.Sleep(2 * time.Second)

	t.Logf("Checking that we still see the NetworkPolicy")
	_, err = kubeclient.NetworkingV1().NetworkPolicies(nwPolicy.Namespace).Get(context.TODO(), nwPolicy.Name, metav1.GetOptions{})
	if err != nil {
		t.Errorf("Failed to get NetworkPolocy: %v", err)
	}

	t.Logf("Checking that crd resource does not show up in networking group")
	if etcd.CrdExistsInDiscovery(apiextensionsclient, crd) {
		t.Errorf("CRD resource shows up in discovery, but shouldn't.")
	}
}

func TestCRD(t *testing.T) {
	result := kubeapiservertesting.StartTestServerOrDie(t, nil, nil, framework.SharedEtcd())
	defer result.TearDownFn()

	testNamespace := "test-crd"
	kubeclient, err := kubernetes.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if _, err := kubeclient.CoreV1().Namespaces().Create(context.TODO(), (&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}), metav1.CreateOptions{}); err != nil {
		t.Fatal(err)
	}

	apiextensionsclient, err := apiextensionsclientset.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	t.Logf("Trying to create a custom resource without conflict")
	crd := &apiextensionsv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{
			Name: "foos.cr.bar.com",
		},
		Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
			Group:   "cr.bar.com",
			Version: "v1",
			Scope:   apiextensionsv1beta1.NamespaceScoped,
			Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
				Plural: "foos",
				Kind:   "Foo",
			},
		},
	}
	etcd.CreateTestCRDs(t, apiextensionsclient, false, crd)

	t.Logf("Trying to access foos.cr.bar.com with dynamic client")
	dynamicClient, err := dynamic.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	fooResource := schema.GroupVersionResource{Group: "cr.bar.com", Version: "v1", Resource: "foos"}
	_, err = dynamicClient.Resource(fooResource).Namespace(testNamespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		t.Errorf("Failed to list foos.cr.bar.com instances: %v", err)
	}
}

func TestCRDOpenAPI(t *testing.T) {
	result := kubeapiservertesting.StartTestServerOrDie(t, nil, nil, framework.SharedEtcd())
	defer result.TearDownFn()
	kubeclient, err := kubernetes.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	apiextensionsclient, err := apiextensionsclientset.NewForConfig(result.ClientConfig)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	t.Logf("Trying to create a CustomResourceDefinitions")
	nonStructuralCRD := &apiextensionsv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{
			Name: "foos.nonstructural.cr.bar.com",
		},
		Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
			Group:   "nonstructural.cr.bar.com",
			Version: "v1",
			Scope:   apiextensionsv1beta1.NamespaceScoped,
			Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
				Plural: "foos",
				Kind:   "Foo",
			},
			Validation: &apiextensionsv1beta1.CustomResourceValidation{
				OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{
					Type: "object",
					Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
						"foo": {},
					},
				},
			},
		},
	}
	structuralCRD := &apiextensionsv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{
			Name: "foos.structural.cr.bar.com",
		},
		Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
			Group:   "structural.cr.bar.com",
			Version: "v1",
			Scope:   apiextensionsv1beta1.NamespaceScoped,
			Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
				Plural: "foos",
				Kind:   "Foo",
			},
			PreserveUnknownFields: utilpointer.BoolPtr(false),
			Validation: &apiextensionsv1beta1.CustomResourceValidation{
				OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{
					Type: "object",
					Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
						"foo": {Type: "string"},
					},
				},
			},
		},
	}
	etcd.CreateTestCRDs(t, apiextensionsclient, false, nonStructuralCRD)
	etcd.CreateTestCRDs(t, apiextensionsclient, false, structuralCRD)

	getPublishedSchema := func(defName string) (*spec.Schema, error) {
		bs, err := kubeclient.RESTClient().Get().AbsPath("openapi", "v2").DoRaw(context.TODO())
		if err != nil {
			return nil, err
		}
		spec := spec.Swagger{}
		if err := json.Unmarshal(bs, &spec); err != nil {
			return nil, err
		}
		if spec.SwaggerProps.Paths == nil {
			return nil, nil
		}
		d, ok := spec.SwaggerProps.Definitions[defName]
		if !ok {
			return nil, nil
		}
		return &d, nil
	}

	waitForSpec := func(crd *apiextensionsv1beta1.CustomResourceDefinition, expectedType string) {
		t.Logf(`Waiting for {properties: {"foo": {"type":"%s"}}} to show up in schema`, expectedType)
		lastMsg := ""
		if err := wait.PollImmediate(500*time.Millisecond, 10*time.Second, func() (bool, error) {
			lastMsg = ""
			defName := crdDefinitionName(crd)
			schema, err := getPublishedSchema(defName)
			if err != nil {
				lastMsg = err.Error()
				return false, nil
			}
			if schema == nil {
				lastMsg = fmt.Sprintf("spec.SwaggerProps.Definitions[%q] not found", defName)
				return false, nil
			}
			p, ok := schema.Properties["foo"]
			if !ok {
				lastMsg = fmt.Sprintf(`spec.SwaggerProps.Definitions[%q].Properties["foo"] not found`, defName)
				return false, nil
			}
			if !p.Type.Contains(expectedType) {
				lastMsg = fmt.Sprintf(`spec.SwaggerProps.Definitions[%q].Properties["foo"].Type should be %q, but got: %q`, defName, expectedType, p.Type)
				return false, nil
			}
			return true, nil
		}); err != nil {
			t.Fatalf("Failed to see %s OpenAPI spec in discovery: %v, last message: %s", structuralCRD.Name, err, lastMsg)
		}
	}

	t.Logf("Check that structural schema is published")
	waitForSpec(structuralCRD, "string")
	structuralCRD, err = apiextensionsclient.ApiextensionsV1beta1().CustomResourceDefinitions().Get(context.TODO(), structuralCRD.Name, metav1.GetOptions{})
	if err != nil {
		t.Fatal(err)
	}
	prop := structuralCRD.Spec.Validation.OpenAPIV3Schema.Properties["foo"]
	prop.Type = "boolean"
	structuralCRD.Spec.Validation.OpenAPIV3Schema.Properties["foo"] = prop
	if _, err = apiextensionsclient.ApiextensionsV1beta1().CustomResourceDefinitions().Update(context.TODO(), structuralCRD, metav1.UpdateOptions{}); err != nil {
		t.Fatal(err)
	}
	waitForSpec(structuralCRD, "boolean")

	t.Logf("Check that non-structural schema is not published")
	schema, err := getPublishedSchema(crdDefinitionName(nonStructuralCRD))
	if err != nil {
		t.Fatal(err)
	}
	if schema == nil {
		t.Fatal("expected a non-nil schema")
	}
	if foo, ok := schema.Properties["foo"]; ok {
		t.Fatalf("unexpected published 'foo' property: %#v", foo)
	}
}

func crdDefinitionName(crd *apiextensionsv1beta1.CustomResourceDefinition) string {
	sgmts := strings.Split(crd.Spec.Group, ".")
	reverse(sgmts)
	return strings.Join(append(sgmts, crd.Spec.Version, crd.Spec.Names.Kind), ".")
}

func reverse(s []string) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}


text:
package org.ovirt.engine.api.restapi.types.externalhostproviders;

import static org.ovirt.engine.api.restapi.utils.HexUtils.string2hex;

import org.ovirt.engine.api.model.ExternalDiscoveredHost;
import org.ovirt.engine.api.restapi.types.AbstractInvertibleMappingTest;

public class ExternalDiscoveredHostMapperTest
        extends AbstractInvertibleMappingTest<
            ExternalDiscoveredHost,
            org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost,
            org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost
        > {
    public ExternalDiscoveredHostMapperTest() {
        super(
            ExternalDiscoveredHost.class,
            org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost.class,
            org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost.class
        );
    }

    @Override
    protected ExternalDiscoveredHost postPopulate(ExternalDiscoveredHost model) {
        // The id is expected to be the name encoded in hex:
        model.setId(string2hex(model.getName()));
        return model;
    }

    @Override
    protected void verify(ExternalDiscoveredHost model, ExternalDiscoveredHost transform) {
        assertNotNull(transform);
        assertEquals(model.getId(), transform.getId());
        assertEquals(model.getName(), transform.getName());
        assertEquals(model.getIp(), transform.getIp());
        assertEquals(model.getMac(), transform.getMac());
        assertEquals(model.getSubnetName(), transform.getSubnetName());
        assertEquals(model.getLastReport(), transform.getLastReport());
    }
}


text:
<?php
/**
 * This is the base class for all AR models that needs to handle events
 * fired by the simpleWorkflow behavior.
 * Handling simpleWorkflow events can also be achieved by creating a behavior that
 * inherits from SWActiveRecordBehavior and overload default event handlers
 */
class SWActiveRecord extends CActiveRecord
{
	public function onEnterWorkflow($event)
	{
	}
	public function enterWorkflow($event)
	{
	}
	public function onBeforeTransition($event)
	{
	}
	public function beforeTransition($event)
	{
	}
	public function onProcessTransition($event)
	{
	}
	public function processTransition($event)
	{
	}
	public function onAfterTransition($event)
	{
	}
	public function afterTransition($event)
	{
	}
	public function onFinalStatus($event)
	{
	}
	public function finalStatus($event)
	{
	}
	public function onLeaveWorkflow($event)
	{
	}
	public function leaveWorkflow($event)
	{
	}
}
?>


text:
@interface SongTableViewController : UIViewController<UITableViewDataSource, UITableViewDelegate, PlayerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end


text:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)


text:
static inline unsigned numberOfCPUs()
{
	int result = sysconf( _SC_NPROCESSORS_ONLN );
	if ( result < 0 )
		THROW_BOOST_ERRNO_EXCEPTION( errno, "Unable to fetch number of processors" );
	return result;
}

#endif // __COMMON_NUMBER_OF_CPUS_H__


text:
<?php defined('BASEPATH') or exit('No direct script access allowed');

class inventario_update extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->output->set_header('Content-Type: text/html; charset=ISO-8859-1');
        date_default_timezone_set('America/Lima');
        $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
        $this->output->set_header('Cache-Control: post-check=0, pre-check=0', false);
        $this->output->set_header('Pragma: no-cache');
        $this->output->set_header('Content-Type: text/html; charset=ISO-8859-1');
        $this->load->library('lib_utils');
        $this->load->library('table');
        $this->load->model('m_usuario');
        $this->load->model('m_permisos');
        $this->load->model('m_rol');
        $this->load->model('m_producto');
    }

    public function index()
    {
        $idUsuario = $this->session->userdata('idUsuario');
        $idProductoUpdate = $this->session->userdata('idProductoUpdate');

        if ($idUsuario != null) {
            $nombreUsuario = $this->session->userdata('nombreUsuario');
            $permisos = $this->m_permisos->getPermisosByUsuario($idUsuario);
            $perm = $this->lib_utils->createPermisosVista($permisos);
            $data['nombreUsuario'] = $nombreUsuario;
            $data['permisos'] = $perm;

            $data += $this->m_producto->getDatosProducto($idProductoUpdate);

            // MENU Y CABECERA
            $cabecera = $this->load->view('v_cabecera', $data, true);
            $menu = $this->load->view('v_menu', $data, true);
            $data['cabecera'] = $cabecera;
            $data['menu'] = $menu;

            $data['optTipoUnidad'] = $this->buildOptTipoUnidad($data['idTipoUnidadMedida']);
            $data['optTipoProduct'] = $this->buildOptTipoProducto($data['idTipoProducto']);

            $this->load->view('v_inventario/v_producto_update', $data);
        } else {
            redirect('', 'refresh');
        }
    }

    function buildOptTipoUnidad($idTipoUnidadMedida)
    {
        $listaTipoUnidad = $this->m_producto->getAllTipoUnidad();
        $opt = null;
        foreach ($listaTipoUnidad as $tipoUnidad) {
            $idTipoUnidadCrypt = $this->encrypt->encode($tipoUnidad->idTipoUnidadMedida);
            $selected = ($tipoUnidad->idTipoUnidadMedida == $tipoUnidad) ? 'selected' : null;
            $opt .= '<option value="' . $idTipoUnidadCrypt . '">' . $tipoUnidad->tipoUnidad . '</option>';
        }
        return $opt;
    }

    function buildOptTipoProducto($idTipoProducto)
    {
        $listaTipoProducts = $this->m_producto->getAllTipoProduct();
        $opt = null;
        foreach ($listaTipoProducts as $tipoProduct) {
            $idTipoProductCrypt = $this->encrypt->encode($tipoProduct->idTipoProducto);
            $selected = ($tipoProduct->idTipoProducto == $tipoProduct) ? 'selected' : null;
            $opt .= '<option value="' . $idTipoProductCrypt . '">' . $tipoProduct->nombre . '</option>';
        }
        return $opt;
    }

    function actualizarProducto(){
        $data['error'] = EXIT_ERROR;
        $data['msj']   = null;
        try{
            $idProductoUpdate = $this->session->userdata('idProductoUpdate');
            $nameProducto = $this->input->post('nameProducto');
            $tipoUnidad = $this->encrypt->decode($this->input->post('tipoUnidad'));
            $tipoProducto = $this->encrypt->decode($this->input->post('tipoProducto'));
            $descripcion = $this->input->post('descripcion');
            $arrayUpdate = array(
                'idTipoProducto' => $tipoProducto,
                'idTipoUnidadMedida' => $tipoUnidad,
                'nombre' => $nameProducto,
                'descripcion' => $descripcion
            );
            $data = $this->m_producto->updateProducto($arrayUpdate,$idProductoUpdate);
        } catch(Exception $e){
            $data['msj'] = $e->getMessage();
        }
        echo json_encode(array_map('utf8_encode', $data));
    }
}


text:
{% extends "base.html" %}

{% block page_title %}Feedback on {{ PROJECT_TITLE }}{% end %}

{% block extra_js %}
{% module ScriptTags('feedback.js') %}
{% end %}

{% block extra_head %}

{% end %}

{% block main %}

Feedback

    {% if posted %}

        <button type="button" class="close" data-dismiss="alert">×</button>
        Thank you! Your feedback has been posted. Thanks for helping out!

    {% end %}

    <form action="." method="post">
    {% module xsrf_form_html() %}
    Your name
    <input type="text" class="input-xlarge" name="name" spellcorrect="false" value="{% if name %}{{ name }}{% end %}">
    Your email
    <input type="email" class="input-xlarge" name="email" value="{% if user %}{{ user }}{% end %}">
    What's up?
    <select name="type">
      <option value="feedback">General feedback</option>
      <option value="bug">Bug report</option>
      <option value="feature">Feature request or idea</option>
      <option value="question">Question</option>
      <option value="other">Other</option>
    </select>
    Comment
    <textarea name="comment" rows="5" style="width:500px"></textarea>
    {% if not user %}
    Prove that you're human
    :
    <input type="hidden" class="hp-question" name="hp-question">
    <input name="hp">
    {% end %}

      <button type="submit" class="btn btn-primary">Submit feedback</button>
      <button type="button" class="btn" onclick="location.href='/'">Cancel</button>

    </form>

{% end %}


text:
import {Action} from './analytics';
import {Actions} from './actions';
import {LocalSubscriptionPlatformRenderer} from './local-subscription-platform-renderer';
import {UrlBuilder} from './url-builder';
import {closestAncestorElementBySelector} from '../../../src/dom';
import {dev, userAssert} from '../../../src/log';

/**
 * Surrogate property added to click events marking them as handled by the
 * amp-subscriptions extension.
 */
const CLICK_HANDLED_EVENT_PROPERTY = '_AMP_SUBSCRIPTIONS_CLICK_HANDLED';

/**
 * This implements the methods to interact with various subscription platforms.
 *
 * @implements {./subscription-platform.SubscriptionPlatform}
 */
export class LocalSubscriptionBasePlatform {
  /**
   * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
   * @param {!JsonObject} platformConfig
   * @param {!./service-adapter.ServiceAdapter} serviceAdapter
   */
  constructor(ampdoc, platformConfig, serviceAdapter) {
    /** @protected @const */
    this.ampdoc_ = ampdoc;

    /** @private @const */
    this.rootNode_ = ampdoc.getRootNode();

    /** @protected {!JsonObject} */
    this.serviceConfig_ = platformConfig;

    /** @private @const {boolean} */
    this.pingbackAllEntitlements_ = !!this.serviceConfig_[
      'pingbackAllEntitlements'
    ];

    /** @protected @const {!./service-adapter.ServiceAdapter} */
    this.serviceAdapter_ = serviceAdapter;

    /** @protected @const {!UrlBuilder} */
    this.urlBuilder_ = new UrlBuilder(
      this.ampdoc_,
      this.serviceAdapter_.getReaderId('local')
    );

    /** @protected @const {!./analytics.SubscriptionAnalytics} */
    this.subscriptionAnalytics_ = serviceAdapter.getAnalytics();

    userAssert(
      this.serviceConfig_['actions'],
      'Actions have not been defined in the service config'
    );

    /** @private @const {!Actions} */
    this.actions_ = new Actions(
      this.ampdoc_,
      this.urlBuilder_,
      this.subscriptionAnalytics_,
      this.validateActionMap(this.serviceConfig_['actions'])
    );

    /** @private @const {!LocalSubscriptionPlatformRenderer}*/
    this.renderer_ = new LocalSubscriptionPlatformRenderer(
      this.ampdoc_,
      serviceAdapter.getDialog(),
      this.serviceAdapter_
    );
  }

  /**
   * @override
   */
  getServiceId() {
    return 'local';
  }

  /**
   * Validates the action map
   * @param {!JsonObject<string, string>} actionMap
   * @return {!JsonObject<string, string>}
   */
  validateActionMap(actionMap) {
    userAssert(
      actionMap[Action.LOGIN],
      'Action "login" is not present in action map'
    );
    userAssert(
      actionMap[Action.SUBSCRIBE],
      'Action "subscribe" is not present in action map'
    );
    return actionMap;
  }

  /**
   * Add event listener for the subscriptions action
   * @protected
   */
  initializeListeners_() {
    const handleClickOncePerEvent = (e) => {
      if (e[CLICK_HANDLED_EVENT_PROPERTY]) {
        return;
      }
      e[CLICK_HANDLED_EVENT_PROPERTY] = true;

      const element = closestAncestorElementBySelector(
        dev().assertElement(e.target),
        '[subscriptions-action]'
      );
      this.handleClick_(element);
    };
    this.rootNode_.addEventListener('click', handleClickOncePerEvent);

    // If the root node has a `body` property, listen to events on that too,
    // to fix an iOS shadow DOM bug (https://github.com/ampproject/amphtml/issues/25754).
    if (this.rootNode_.body) {
      this.rootNode_.body.addEventListener('click', handleClickOncePerEvent);
    }
  }

  /**
   * Handle click on subscription-action
   * @private
   * @param {Node} element
   */
  handleClick_(element) {
    if (element) {
      const action = element.getAttribute('subscriptions-action');
      const serviceAttr = element.getAttribute('subscriptions-service');
      if (serviceAttr == 'local') {
        this.executeAction(action);
      } else if ((serviceAttr || 'auto') == 'auto') {
        if (action == Action.LOGIN) {
          // The "login" action is somewhat special b/c viewers can
          // enhance this action, e.g. to provide save/link feature.
          const platform = this.serviceAdapter_.selectPlatformForLogin();
          this.serviceAdapter_.delegateActionToService(
            action,
            platform.getServiceId()
          );
        } else {
          this.executeAction(action);
        }
      } else if (serviceAttr) {
        this.serviceAdapter_.delegateActionToService(action, serviceAttr);
      }
    }
  }

  /** @override */
  activate(entitlement) {
    // Note all platforms are resolved at this stage
    // Get the factor states of each platform and
    // add them to the renderState object
    this.createRenderState_(entitlement).then((renderState) => {
      this.renderer_.render(renderState);
    });
  }

  /**
   * Factored out for testability
   * @param {./entitlement.Entitlement} entitlement
   * @return {!Promise<!JsonObject>}
   * @private
   */
  createRenderState_(entitlement) {
    const renderState = entitlement.json();
    return this.serviceAdapter_
      .getScoreFactorStates()
      .then((scoresValues) => {
        renderState['factors'] = scoresValues;
        return this.urlBuilder_.setAuthResponse(renderState);
      })
      .then(() => {
        return this.actions_.build();
      })
      .then(() => renderState);
  }

  /** @override */
  reset() {
    this.renderer_.reset();
  }

  /** @override */
  executeAction(action) {
    const actionExecution = this.actions_.execute(action);
    return actionExecution.then((result) => {
      if (result) {
        this.serviceAdapter_.resetPlatforms();
      }
      return !!result;
    });
  }

  /** @override */
  isPrerenderSafe() {
    // Local platform can never be allowed to prerender in a viewer
    return false;
  }

  /** @override */
  getSupportedScoreFactor(unusedFactor) {
    return 0;
  }

  /** @override */
  getBaseScore() {
    return this.serviceConfig_['baseScore'] || 0;
  }

  /**
   * @override
   * @return {!Promise<?./entitlement.Entitlement>}
   */
  getEntitlements() {}

  /**
   * @override
   * @param {?./entitlement.Entitlement} unusedEntitlement
   * @return {!Promise|undefined}
   */
  pingback(unusedEntitlement) {}

  /**
   * @override
   * @return {boolean}
   */
  pingbackReturnsAllEntitlements() {
    return this.pingbackAllEntitlements_;
  }

  /** @override */
  isPingbackEnabled() {
    return false;
  }

  /** @override */
  decorateUI(unusedNode, unusedAction, unusedOptions) {}
}


text:
#include "../../inc/MarlinConfig.h"

#if HAS_LEVELING

#include "../gcode.h"
#include "../../feature/bedlevel/bedlevel.h"
#include "../../module/planner.h"
#include "../../module/probe.h"

#if ENABLED(EEPROM_SETTINGS)
  #include "../../module/settings.h"
#endif

#if ENABLED(EXTENSIBLE_UI)
  #include "../../lcd/extui/ui_api.h"
#endif

//#define M420_C_USE_MEAN

/**
 * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
 *
 *   S[bool]   Turns leveling on or off
 *   Z[height] Sets the Z fade height (0 or none to disable)
 *   V[bool]   Verbose - Print the leveling grid
 *
 * With AUTO_BED_LEVELING_UBL only:
 *
 *   L[index]  Load UBL mesh from index (0 is default)
 *   T[map]    0:Human-readable 1:CSV 2:"LCD" 4:Compact
 *
 * With mesh-based leveling only:
 *
 *   C         Center mesh on the mean of the lowest and highest
 *
 * With MARLIN_DEV_MODE:
 *   S2        Create a simple random mesh and enable
 */
void GcodeSuite::M420() {
  const bool seen_S = parser.seen('S'),
             to_enable = seen_S ? parser.value_bool() : planner.leveling_active;

  #if ENABLED(MARLIN_DEV_MODE)
    if (parser.intval('S') == 2) {
      const float x_min = probe.min_x(), x_max = probe.max_x(),
                  y_min = probe.min_y(), y_max = probe.max_y();
      #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
        bilinear_start.set(x_min, y_min);
        bilinear_grid_spacing.set((x_max - x_min) / (GRID_MAX_CELLS_X),
                                  (y_max - y_min) / (GRID_MAX_CELLS_Y));
      #endif
      GRID_LOOP(x, y) {
        Z_VALUES(x, y) = 0.001 * random(-200, 200);
        TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, Z_VALUES(x, y)));
      }
      SERIAL_ECHOPGM("Simulated " STRINGIFY(GRID_MAX_POINTS_X) "x" STRINGIFY(GRID_MAX_POINTS_Y) " mesh ");
      SERIAL_ECHOPAIR(" (", x_min);
      SERIAL_CHAR(','); SERIAL_ECHO(y_min);
      SERIAL_ECHOPAIR(")-(", x_max);
      SERIAL_CHAR(','); SERIAL_ECHO(y_max);
      SERIAL_ECHOLNPGM(")");
    }
  #endif

  xyz_pos_t oldpos = current_position;

  // If disabling leveling do it right away
  // (Don't disable for just M420 or M420 V)
  if (seen_S && !to_enable) set_bed_leveling_enabled(false);

  #if ENABLED(AUTO_BED_LEVELING_UBL)

    // L to load a mesh from the EEPROM
    if (parser.seen('L')) {

      set_bed_leveling_enabled(false);

      #if ENABLED(EEPROM_SETTINGS)
        const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.storage_slot;
        const int16_t a = settings.calc_num_meshes();

        if (!a) {
          SERIAL_ECHOLNPGM("?EEPROM storage not available.");
          return;
        }

        if (!WITHIN(storage_slot, 0, a - 1)) {
          SERIAL_ECHOLNPGM("?Invalid storage slot.");
          SERIAL_ECHOLNPAIR("?Use 0 to ", a - 1);
          return;
        }

        settings.load_mesh(storage_slot);
        ubl.storage_slot = storage_slot;

      #else

        SERIAL_ECHOLNPGM("?EEPROM storage not available.");
        return;

      #endif
    }

    // L or V display the map info
    if (parser.seen("LV")) {
      ubl.display_map(parser.byteval('T'));
      SERIAL_ECHOPGM("Mesh is ");
      if (!ubl.mesh_is_valid()) SERIAL_ECHOPGM("in");
      SERIAL_ECHOLNPAIR("valid\nStorage slot: ", ubl.storage_slot);
    }

  #endif // AUTO_BED_LEVELING_UBL

  const bool seenV = parser.seen_test('V');

  #if HAS_MESH

    if (leveling_is_valid()) {

      // Subtract the given value or the mean from all mesh values
      if (parser.seen('C')) {
        const float cval = parser.value_float();
        #if ENABLED(AUTO_BED_LEVELING_UBL)

          set_bed_leveling_enabled(false);
          ubl.adjust_mesh_to_mean(true, cval);

        #else

          #if ENABLED(M420_C_USE_MEAN)

            // Get the sum and average of all mesh values
            float mesh_sum = 0;
            GRID_LOOP(x, y) mesh_sum += Z_VALUES(x, y);
            const float zmean = mesh_sum / float(GRID_MAX_POINTS);

          #else // midrange

            // Find the low and high mesh values.
            float lo_val = 100, hi_val = -100;
            GRID_LOOP(x, y) {
              const float z = Z_VALUES(x, y);
              NOMORE(lo_val, z);
              NOLESS(hi_val, z);
            }
            // Get the midrange plus C value. (The median may be better.)
            const float zmean = (lo_val + hi_val) / 2.0 + cval;

          #endif

          // If not very close to 0, adjust the mesh
          if (!NEAR_ZERO(zmean)) {
            set_bed_leveling_enabled(false);
            // Subtract the mean from all values
            GRID_LOOP(x, y) {
              Z_VALUES(x, y) -= zmean;
              TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, Z_VALUES(x, y)));
            }
            TERN_(ABL_BILINEAR_SUBDIVISION, bed_level_virt_interpolate());
          }

        #endif
      }

    }
    else if (to_enable || seenV) {
      SERIAL_ECHO_MSG("Invalid mesh.");
      goto EXIT_M420;
    }

  #endif // HAS_MESH

  // V to print the matrix or mesh
  if (seenV) {
    #if ABL_PLANAR
      planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
    #else
      if (leveling_is_valid()) {
        #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
          print_bilinear_leveling_grid();
          TERN_(ABL_BILINEAR_SUBDIVISION, print_bilinear_leveling_grid_virt());
        #elif ENABLED(MESH_BED_LEVELING)
          SERIAL_ECHOLNPGM("Mesh Bed Level data:");
          mbl.report_mesh();
        #endif
      }
    #endif
  }

  #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
    if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units(), false);
  #endif

  // Enable leveling if specified, or if previously active
  set_bed_leveling_enabled(to_enable);

  #if HAS_MESH
    EXIT_M420:
  #endif

  // Error if leveling failed to enable or reenable
  if (to_enable && !planner.leveling_active)
    SERIAL_ERROR_MSG(STR_ERR_M420_FAILED);

  SERIAL_ECHO_START();
  SERIAL_ECHOPGM("Bed Leveling ");
  serialprintln_onoff(planner.leveling_active);

  #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
    SERIAL_ECHO_START();
    SERIAL_ECHOPGM("Fade Height ");
    if (planner.z_fade_height > 0.0)
      SERIAL_ECHOLN(planner.z_fade_height);
    else
      SERIAL_ECHOLNPGM(STR_OFF);
  #endif

  // Report change in position
  if (oldpos != current_position)
    report_current_position();
}

#endif // HAS_LEVELING


text:
{-# LANGUAGE ForeignFunctionInterface #-}

-- |
--
-- We wish to find a solution that satisifes the following logical condition.
--
-- > (A v ¬B v C) ∧ (B v D v E) ∧ (D v F)
--
-- We can specify this as a zero-terminated lists of integers, with integers mapping onto the variable as ordered
-- in the condition and with integer negation corresponding to logical negation of the specific clause.
--
-- > 1 -2 3 0
-- > 2 4 5 0
-- > 4 6 0
--
-- We feed this list of clauses to the SAT solver using the 'solve' function.
--
-- @
-- import Picosat
--
-- main :: IO [Int]
-- main = do
--   solve [[1, -2, 3], [2,4,5], [4,6]]
--   -- Solution [1,-2,3,4,5,6]
-- @
--
-- The solution given we can interpret as:
--
-- >  1  A
-- > -2 ~B
-- >  3  C
-- >  4  D
-- >  5  E
-- >  6  F
--
-- To generate all satisfiable solutions, use 'solveAll' function.:
--
-- @
-- import Picosat
--
-- main :: IO [Int]
-- main = solveAll [[1,2]]
--   -- [Solution [1,2],Solution [-1,2],Solution [1,-2]]
-- @
--
-- For a higher level interface see: <http://hackage.haskell.org/package/picologic>
--
--
-- If you intend to solve a set of similar CNFs think about using
-- Picosat's incremental interface. It allows to push and pop
-- sets of clauses, as well as solving under assumptions.
--
-- @
-- import Picosat (evalScopedPicosat, addBaseClauses,
--                 withScopedClauses, scopedAllSolutions,
--                 scopedSolutionWithAssumptions)
--
-- main :: IO [Int]
-- main =
--   evalScopedPicosat $ do
--     addBaseClauses [[1, 2, 3]]
--     -- == [Solution [1,2,3],
--     --     Solution [1,2,-3],
--     --     Solution [1,-2,3],
--     --     Solution [1,-2,-3],
--     --     Solution [-1,-2,3],
--     --     Solution [-1,2,-3],
--     --     Solution [-1,2,3]]
--
--     withScopedClauses [[-2,-3]] $ do
--       sol <- scopedAllSolutions
--       -- ==   [Solution [-1,2,-3],
--       --       Solution [-1,-2,3],
--       --       Solution [1,-2,-3],
--       --       Solution [1,-2,3],
--       --       Solution [1,2,-3]]
--
--     addBaseClauses [[-1,-3]]
--
--     withScopedClauses [[-1,-2], [1,-3]] $ do
--       sol <- scopedSolutionWithAssumptions [1]
-- @
module Picosat
  ( solve,
    solveAll,
    unsafeSolve,
    unsafeSolveAll,
    Picosat,
    Solution (..),
    evalScopedPicosat,
    addBaseClauses,
    withScopedClauses,
    scopedAllSolutions,
    scopedSolutionWithAssumptions,
  )
where

import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.State.Strict
import qualified Data.Set as S
import Foreign.C.Types
import Foreign.Ptr
import System.IO.Unsafe (unsafePerformIO)

foreign import ccall unsafe "picosat_init"
  picosat_init ::
    IO (Picosat)

foreign import ccall unsafe "picosat_reset"
  picosat_reset ::
    Picosat -> IO ()

foreign import ccall unsafe "picosat_add"
  picosat_add ::
    Picosat -> CInt -> IO CInt

foreign import ccall unsafe "picosat_variables"
  picosat_variables ::
    Picosat -> IO CInt

foreign import ccall unsafe "picosat_sat"
  picosat_sat ::
    Picosat -> CInt -> IO CInt

foreign import ccall unsafe "picosat_deref"
  picosat_deref ::
    Picosat -> CInt -> IO CInt

foreign import ccall unsafe "picosat_push"
  picosat_push ::
    Picosat -> IO CInt

foreign import ccall unsafe "picosat_pop"
  picosat_pop ::
    Picosat -> IO CInt

-- foreign import ccall unsafe "picosat_context" picosat_context
--     :: Picosat -> IO CInt

foreign import ccall unsafe "picosat_assume"
  picosat_assume ::
    Picosat -> CInt -> IO ()

type Picosat = Ptr ()

-- | Call a monadic action with a freshly created Picosat that
-- is destroyed afterwards.
withPicosat :: (Picosat -> IO a) -> IO a
withPicosat f = do
  pico <- picosat_init
  res <- f pico
  picosat_reset pico
  return res

unknown, satisfiable, unsatisfiable :: CInt
unknown = 0
satisfiable = 10
unsatisfiable = 20

data Solution
  = Solution [Int]
  | Unsatisfiable
  | Unknown
  deriving (Show, Eq, Ord)

addClause :: Picosat -> [Int] -> IO ()
addClause pico cl = do
  _ <- mapM_ (picosat_add pico . fromIntegral) cl
  _ <- picosat_add pico 0
  return ()

addClauses :: Picosat -> [[Int]] -> IO ()
addClauses pico = mapM_ $ addClause pico

getSolution :: Picosat -> IO Solution
getSolution pico = do
  vars <- picosat_variables pico
  sol <- forM [1 .. vars] $ \i -> do
    s <- picosat_deref pico i
    return $ i * s
  return $ Solution $ map fromIntegral sol

solution :: Picosat -> IO Solution
solution pico = do
  res <- picosat_sat pico (-1)
  case res of
    a
      | a == unknown -> return Unknown
      | a == unsatisfiable -> return Unsatisfiable
      | a == satisfiable -> getSolution pico
      | otherwise -> error "Picosat error."

-- | Solve a list of CNF constraints yielding the first solution.
solve :: [[Int]] -> IO Solution
solve cnf = do
  withPicosat $ \pico -> do
    _ <- addClauses pico cnf
    sol <- solution pico
    return sol

-- | Solve a list of CNF constraints yielding all possible solutions.
solveAll :: [[Int]] -> IO [Solution]
solveAll cnf = do
  evalScopedPicosat $ do
    addBaseClauses cnf
    scopedAllSolutions

data PicosatScoped = PicosatScoped
  { psPicosat :: Picosat,
    psContextVars :: S.Set Int
  }

type PS a = StateT PicosatScoped IO a

evalScopedPicosat :: PS a -> IO a
evalScopedPicosat action =
  withPicosat $ \picosat -> do
    evalStateT action $ PicosatScoped picosat S.empty

addBaseClauses :: [[Int]] -> PS ()
addBaseClauses clauses = do
  pico <- gets psPicosat
  liftIO $ addClauses pico clauses

withScopedClauses :: [[Int]] -> PS a -> PS a
withScopedClauses clauses action = do
  pico <- gets psPicosat
  withScope $ do
    liftIO $ addClauses pico clauses
    action

withScope :: PS a -> PS a
withScope action = do
  pico <- gets psPicosat
  ctx <- liftIO $ picosat_push pico
  addContextVariable $ fromIntegral ctx
  res <- action
  _ <- liftIO $ picosat_pop pico
  return res

addContextVariable :: Int -> PS ()
addContextVariable var = modify add
  where
    add s = s {psContextVars = S.insert var $ psContextVars s}

-- | Get one solution in scoped context. Pay attention to not
-- return any "context variable" which are Picosat internals.
scopedSolution :: PS Solution
scopedSolution = do
  pico <- gets psPicosat
  sol <- liftIO $ solution pico
  case sol of
    Solution ys -> do
      ctxvars <- gets psContextVars
      return $ Solution
        $ filter (\l -> S.notMember (abs l) ctxvars)
        $ ys
    x ->
      return x

scopedAllSolutions :: PS [Solution]
scopedAllSolutions = do
  let recur solutions = do
        pico <- gets psPicosat
        sol <- scopedSolution
        case sol of
          Solution ys -> do
            let negsol = map negate ys
            liftIO $ addClause pico negsol
            recur (sol : solutions)
          _ ->
            return $ reverse solutions
  withScope $ recur []

scopedSolutionWithAssumptions :: [Int] -> PS Solution
scopedSolutionWithAssumptions assumptions = do
  pico <- gets psPicosat
  liftIO $ mapM_ (picosat_assume pico . fromIntegral) assumptions
  scopedSolution

-- Unsafe solver functions are not guaranteed to be memory safe if the solver fails internally.

{-# NOINLINE unsafeSolve #-}
unsafeSolve :: [[Int]] -> Solution
unsafeSolve = unsafePerformIO . solve

{-# NOINLINE unsafeSolveAll #-}
unsafeSolveAll :: [[Int]] -> [Solution]
unsafeSolveAll = unsafePerformIO . solveAll


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package com.mxgraph.util.png (mxGraph 3.7.0.1 API Specification)</title>
<meta name="date" content="2017-01-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

mxGraph 3.7.0.1

Prev

Next

Frames

No Frames

All Classes

Uses of Package
com.mxgraph.util.png

Packages that use com.mxgraph.util.png

Package
Description

com.mxgraph.util.png

Classes in com.mxgraph.util.png used by com.mxgraph.util.png

Class and Description

mxPngEncodeParam

An instance of ImageEncodeParam for encoding images in
 the PNG format.

mxPngSuggestedPaletteEntry

A class representing the fields of a PNG suggested palette entry.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

mxGraph 3.7.0.1

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2010 Gaudenz Alder, David Benson. All rights reserved.


text:
import {IdPair} from '../types'
import {Observable} from 'rxjs'
import {Pair} from './checkoutPair'
export declare const memoizedPair: (arg1: IdPair) => Observable<Pair>


text:
import {shallow} from 'enzyme';
import React from 'react';

import Advice from './../Advice';

describe('<Advice/>', () => {
  it('renders string title and child content', () => {
    const wrapper = shallow(<Advice>This is a dummy advice text.</Advice>);
    expect(
      wrapper.contains(
This is a dummy advice text.
),
    ).toBe(true);
  });
});


text:
% Computes the average degree of neighboring nodes for every vertex
% Note: Works for weighted degrees also
% INPUTs: adjacency matrix
% OUTPUTs: average neighbor degree vector nx1
% Other routines used: degrees.m, kneighbors.m
% GB, Last updated: May 21, 2010

function ave_n_deg=ave_neighbor_deg(adj)

ave_n_deg=zeros(1,length(adj));   % initialize output vector
[deg,~,~]=degrees(adj);

for i=1:length(adj)  % across all nodes

  neigh=kneighbors(adj,i,1);  % neighbors of i, one link away
  if isempty(neigh); ave_n_deg(i)=0; continue; end
  ave_n_deg(i)=sum(deg(neigh))/deg(i);

end


text:
<?php

/**
 * PluginAlbumImage form.
 *
 * @package    form
 * @subpackage AlbumImage
 * @author     Kousuke Ebihara <ebihara@tejimaya.com>
 */
class AlbumPhotoForm extends sfForm
{
  protected $albumInstance = null;

  public function setup()
  {
    $photoCount = $this->getOption('photo_count', 5);
    $this->albumInstance = $this->getOption('album');
    if (!($this->albumInstance instanceof Album))
    {
      throw new InvalidArgumentException('The "album" option is required and it must be an instance of the Album class.');
    }

    $widget = new opWidgetFormInputAlbumImage(array(), array('size' => 40));
    $validator = new sfValidatorCallback(array('callback' => array($this, 'validatePhoto')));

    for ($i = 1; $i <= $photoCount; $i++)
    {
      $this->setWidget('photo_'.$i, clone $widget);
      $this->setValidator('photo_'.$i, clone $validator);
    }

    $this->getValidatorSchema()->setPostValidator(new sfValidatorCallback(
      array('callback' => array($this, 'requiredCheck')),
      array('required' => 'You need to post at least one photo.')
    ));

    $this->widgetSchema->setNameFormat('album_photo[%s]');
  }

  public function save()
  {
    foreach ($this->getValues() as $k => $v)
    {
      if (0 !== strpos($k, 'photo_'))
      {
        continue;
      }

      if (empty($v['file']))
      {
        continue;
      }

      $file = new File();
      $file->setFromValidatedFile($v['file']);

      if (empty($v['description']))
      {
        $description = $file->getName();
      }
      else
      {
        $description = $v['description'];
      }

      $albumImage = new AlbumImage();
      $albumImage->setAlbum($this->albumInstance);
      $albumImage->setFile($file);
      $albumImage->setDescription($description);
      $albumImage->save();
    }
  }

  public function requiredCheck($validator, $value, $arguments)
  {
    foreach ($value as $k => $v)
    {
      if (0 !== strpos($k, 'photo_'))
      {
        continue;
      }

      if (!empty($v['file']))
      {
        return $value;
      }
    }

    throw new sfValidatorError($validator, 'required');
  }

  public function validatePhoto($validator, $value, $arguments)
  {
    $validatorFile   = new opValidatorImageFile();
    $validatorString = new opValidatorString(array('trim' => true, 'max_length' => 140, 'required' => false));

    try
    {
      $value['file']        = $validatorFile->clean($value['file']);
      $value['description'] = $validatorString->clean($value['description']);
    }
    catch (sfValidatorError $e)
    {
      if ('required' !== $e->getCode())
      {
        throw $e;
      }

      $value['description'] = '';
      $value['file'] = null;
    }

    return $value;
  }
}


text:
<?xml version="1.0"?>
<Runs Version="1" Minor="0">
	<Run Id="impl_1" LaunchDir="/home/virtual/noc_dev/noc_dev/noc_dev.runs/impl_1" FlowId="Vivado_Implementation" FromStepId="write_bitstream" ToStepId="write_bitstream"/>
</Runs>


text:
package org.keycloak.testsuite.arquillian;

import java.io.IOException;
import java.io.NotSerializableException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXServiceURL;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.ContainerRegistry;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.Validate;
import org.jboss.arquillian.test.spi.TestEnricher;
import org.jboss.logging.Logger;
import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
import org.keycloak.common.util.Retry;
import org.keycloak.testsuite.arquillian.annotation.JmxInfinispanCacheStatistics;
import org.keycloak.testsuite.arquillian.annotation.JmxInfinispanChannelStatistics;
import org.keycloak.testsuite.arquillian.jmx.JmxConnectorRegistry;
import org.keycloak.testsuite.arquillian.undertow.KeycloakOnUndertow;
import org.keycloak.testsuite.crossdc.DC;

/**
 *
 * @author hmlnarik
 */
public class CacheStatisticsControllerEnricher implements TestEnricher {

    private static final Logger LOG = Logger.getLogger(CacheStatisticsControllerEnricher.class);

    @Inject
    private Instance<ContainerRegistry> registry;

    @Inject
    private Instance<JmxConnectorRegistry> jmxConnectorRegistry;

    @Inject
    private Instance<SuiteContext> suiteContext;

    @Override
    public void enrich(Object testCase) {
        Validate.notNull(registry.get(), "registry should not be null");
        Validate.notNull(jmxConnectorRegistry.get(), "jmxConnectorRegistry should not be null");
        Validate.notNull(suiteContext.get(), "suiteContext should not be null");

        for (Field field : FieldUtils.getAllFields(testCase.getClass())) {
            JmxInfinispanCacheStatistics annotation = field.getAnnotation(JmxInfinispanCacheStatistics.class);

            if (annotation == null) {
                continue;
            }

            try {
                FieldUtils.writeField(field, testCase, getInfinispanCacheStatistics(annotation), true);
            } catch (IOException | IllegalAccessException | MalformedObjectNameException e) {
                throw new RuntimeException("Could not set value on field " + field);
            }
        }
    }

    private InfinispanStatistics getInfinispanCacheStatistics(JmxInfinispanCacheStatistics annotation) throws MalformedObjectNameException, IOException, MalformedURLException {
        List<ObjectName> mbeanNameTemplates = new LinkedList<>();
        mbeanNameTemplates.add(new ObjectName(String.format(
          "%s:type=%s,name=\"%s(%s)\",manager=\"%s\",component=%s",
          annotation.domain().isEmpty() ? getDefaultDomain(annotation.dc().getDcIndex(), annotation.dcNodeIndex()) : InfinispanConnectionProvider.JMX_DOMAIN,
          annotation.type(),
          annotation.cacheName(),
          annotation.cacheMode(),
          annotation.cacheManagerName(),
          annotation.component()
        )));

        // For the Keycloak on Wildfly 20 and bigger, the typical objectName for the cache statistics looks similar to: jboss.as:subsystem=infinispan,cache-container=keycloak,cache=actionTokens
        if (annotation.dc().getDcIndex() != -1 && annotation.dcNodeIndex() != -1) {
            mbeanNameTemplates.add(new ObjectName(String.format(
                    "jboss.as:subsystem=infinispan,cache-container=keycloak,cache=%s",
                    annotation.cacheName()
            )));
        }

        InfinispanStatistics value = new InfinispanCacheStatisticsImpl(getJmxServerConnection(annotation), mbeanNameTemplates);

        if (annotation.domain().isEmpty()) {
            try {
                LOG.debug("Going to try reset InfinispanCacheStatistics (2 attempts, 150 ms interval)");
                int execute = Retry.execute(() -> value.reset(), 2, 150);
                LOG.debug("reset in " + execute + " attempts");
            } catch (RuntimeException ex) {
                if (annotation.dc() != DC.UNDEFINED && annotation.dcNodeIndex() != -1
                   && suiteContext.get().getAuthServerBackendsInfo(annotation.dc().getDcIndex()).get(annotation.dcNodeIndex()).isStarted()) {
                    LOG.warn("Could not reset statistics for any of the mbean name templates " + mbeanNameTemplates + ". The reason is: \"" + ex.getMessage() + "\"");
                }
            }
        }

        return value;
    }

    private InfinispanStatistics getJGroupsChannelStatistics(JmxInfinispanChannelStatistics annotation) throws MalformedObjectNameException, IOException, MalformedURLException {
        ObjectName mbeanName = new ObjectName(String.format(
          "%s:type=%s,cluster=\"%s\"",
          annotation.domain().isEmpty() ? getDefaultDomain(annotation.dc().getDcIndex(), annotation.dcNodeIndex()) : InfinispanConnectionProvider.JMX_DOMAIN,
          annotation.type(),
          annotation.cluster()
        ));

        InfinispanStatistics value = new InfinispanChannelStatisticsImpl(getJmxServerConnection(annotation), mbeanName);

        if (annotation.domain().isEmpty()) {
            try {
                Retry.execute(() -> value.reset(), 2, 150);
            } catch (RuntimeException ex) {
                if (annotation.dc() != DC.UNDEFINED && annotation.dcNodeIndex() != -1
                   && suiteContext.get().getAuthServerBackendsInfo(annotation.dc().getDcIndex()).get(annotation.dcNodeIndex()).isStarted()) {
                    LOG.warn("Could not reset statistics for " + mbeanName + ". The reason is: \"" + ex.getMessage() + "\"");
                }
            }
        }

        return value;
    }

    @Override
    public Object[] resolve(Method method) {
        Object[] values = new Object[method.getParameterCount()];

        for (int i = 0; i < method.getParameterCount(); i ++) {
            Parameter param = method.getParameters()[i];

            JmxInfinispanCacheStatistics annotation = param.getAnnotation(JmxInfinispanCacheStatistics.class);
            if (annotation != null) try {
                values[i] = getInfinispanCacheStatistics(annotation);
            } catch (IOException | MalformedObjectNameException e) {
                throw new RuntimeException("Could not set value on field " + param);
            }

            JmxInfinispanChannelStatistics channelAnnotation = param.getAnnotation(JmxInfinispanChannelStatistics.class);
            if (channelAnnotation != null) try {
                values[i] = getJGroupsChannelStatistics(channelAnnotation);
            } catch (IOException | MalformedObjectNameException e) {
                throw new RuntimeException("Could not set value on field " + param);
            }
        }

        return values;
    }

    private String getDefaultDomain(int dcIndex, int dcNodeIndex) {
        if (dcIndex != -1 && dcNodeIndex != -1) {
            if (Boolean.parseBoolean(System.getProperty("auth.server.jboss.crossdc"))) {
                //backend-jboss-server
                return "org.wildfly.clustering.infinispan";
            }

            //backend-undertow-server
            return InfinispanConnectionProvider.JMX_DOMAIN + "-" + suiteContext.get().getAuthServerBackendsInfo(dcIndex).get(dcNodeIndex).getQualifier();
        }

        //cache-server
        return InfinispanConnectionProvider.JMX_DOMAIN;
    }

    private Supplier<MBeanServerConnection> getJmxServerConnection(JmxInfinispanCacheStatistics annotation) throws MalformedURLException {
        final String host;
        final int port;

        if (annotation.dc() != DC.UNDEFINED && annotation.dcNodeIndex() != -1) {
            ContainerInfo node = suiteContext.get().getAuthServerBackendsInfo(annotation.dc().getDcIndex()).get(annotation.dcNodeIndex());
            Container container = node.getArquillianContainer();
            if (container.getDeployableContainer() instanceof KeycloakOnUndertow) {
                return () -> ManagementFactory.getPlatformMBeanServer();
            }
            host = "localhost";
            port = container.getContainerConfiguration().getContainerProperties().containsKey("managementPort")
              ? Integer.valueOf(container.getContainerConfiguration().getContainerProperties().get("managementPort"))
              : 9990;
        } else {
            host = annotation.host().isEmpty()
              ? System.getProperty((annotation.hostProperty().isEmpty()
                ? "keycloak.connectionsInfinispan.remoteStoreServer"
                : annotation.hostProperty()))
              : annotation.host();

            port = annotation.managementPort() == -1
              ? Integer.valueOf(System.getProperty((annotation.managementPortProperty().isEmpty()
                ? "cache.server.management.port"
                : annotation.managementPortProperty())))
              : annotation.managementPort();
        }

        JMXServiceURL url = new JMXServiceURL("service:jmx:remote+http://" + host + ":" + port);
        return () -> {
            try {
                return jmxConnectorRegistry.get().getConnection(url).getMBeanServerConnection();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        };
    }

    private Supplier<MBeanServerConnection> getJmxServerConnection(JmxInfinispanChannelStatistics annotation) throws MalformedURLException {
        final String host;
        final int port;

        if (annotation.dc() != DC.UNDEFINED && annotation.dcNodeIndex() != -1) {
            ContainerInfo node = suiteContext.get().getAuthServerBackendsInfo(annotation.dc().getDcIndex()).get(annotation.dcNodeIndex());
            Container container = node.getArquillianContainer();
            if (container.getDeployableContainer() instanceof KeycloakOnUndertow) {
                return () -> ManagementFactory.getPlatformMBeanServer();
            }
            host = "localhost";
            port = container.getContainerConfiguration().getContainerProperties().containsKey("managementPort")
              ? Integer.valueOf(container.getContainerConfiguration().getContainerProperties().get("managementPort"))
              : 9990;
        } else {
            host = annotation.host().isEmpty()
              ? System.getProperty((annotation.hostProperty().isEmpty()
                ? "keycloak.connectionsInfinispan.remoteStoreServer"
                : annotation.hostProperty()))
              : annotation.host();

            port = annotation.managementPort() == -1
              ? Integer.valueOf(System.getProperty((annotation.managementPortProperty().isEmpty()
                ? "cache.server.management.port"
                : annotation.managementPortProperty())))
              : annotation.managementPort();
        }

        JMXServiceURL url = new JMXServiceURL("service:jmx:remote+http://" + host + ":" + port);
        return () -> {
            try {
                return jmxConnectorRegistry.get().getConnection(url).getMBeanServerConnection();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        };
    }

    private static abstract class CacheStatisticsImpl implements InfinispanStatistics {

        private final Supplier<MBeanServerConnection> mbscCreateor;
        private final List<ObjectName> mbeanNameTemplates;
        private ObjectName mbeanName;

        public CacheStatisticsImpl(Supplier<MBeanServerConnection> mbscCreateor, ObjectName mbeanNameTemplate) {
            this(mbscCreateor, Collections.singletonList(mbeanNameTemplate));
        }

        public CacheStatisticsImpl(Supplier<MBeanServerConnection> mbscCreateor, List<ObjectName> mbeanNameTemplates) {
            this.mbscCreateor = mbscCreateor;
            this.mbeanNameTemplates = mbeanNameTemplates;
        }

        protected MBeanServerConnection getConnection() {
            return mbscCreateor.get();
        }

        @Override
        public boolean exists() {
            try {
                getMbeanName();
                return true;
            } catch (IOException | RuntimeException ex) {
                return false;
            }
        }

        @Override
        public Map<String, Object> getStatistics() {
            try {
                MBeanInfo mBeanInfo = getConnection().getMBeanInfo(getMbeanName());
                String[] statAttrs = Arrays.asList(mBeanInfo.getAttributes()).stream()
                  .filter(MBeanAttributeInfo::isReadable)
                  .map(MBeanAttributeInfo::getName)
                  .collect(Collectors.toList())
                  .toArray(new String[] {});
                return getConnection().getAttributes(getMbeanName(), statAttrs)
                  .asList()
                  .stream()
                  .collect(Collectors.toMap(Attribute::getName, Attribute::getValue));
            } catch (IOException | InstanceNotFoundException | ReflectionException | IntrospectionException ex) {
                throw new RuntimeException(ex);
            }
        }

        protected ObjectName getMbeanName() throws IOException, RuntimeException {
            if (this.mbeanName == null) {
                // Try all the mbeanName templates
                for (ObjectName mbeanNameTemplate : this.mbeanNameTemplates) {
                    Set<ObjectName> queryNames = getConnection().queryNames(mbeanNameTemplate, null);
                    if (queryNames.isEmpty()) {
                        LOG.infof("No MBean available for the template %s .", mbeanNameTemplate);
                        continue;
                    }
                    this.mbeanName = queryNames.iterator().next();
                    return this.mbeanName;
                }

                throw new RuntimeException("No MBean for any of the templates " + this.mbeanNameTemplates + " found at JMX server");
            }

            return this.mbeanName;
        }

        @Override
        public Comparable getSingleStatistics(String statisticsName) {
            try {
                return (Comparable) getConnection().getAttribute(getMbeanName(), statisticsName);
            } catch (IOException | InstanceNotFoundException | MBeanException | ReflectionException | AttributeNotFoundException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        public void waitToBecomeAvailable(int time, TimeUnit unit) {
            long timeInMillis = TimeUnit.MILLISECONDS.convert(time, unit);
            Retry.execute(() -> {
                try {
                    getMbeanName();
                    if (! isAvailable()) throw new RuntimeException("Not available");
                } catch (IOException | RuntimeException ex) {
                    throw new RuntimeException("Timed out while waiting for any of the mbean name templates " + this.mbeanNameTemplates + " to become available", ex);
                }
            }, 1 + (int) timeInMillis / 100, 100);
        }

        protected abstract boolean isAvailable();
    }

    private static class InfinispanCacheStatisticsImpl extends CacheStatisticsImpl {

        public InfinispanCacheStatisticsImpl(Supplier<MBeanServerConnection> mbscCreator, List<ObjectName> mbeanNames) {
            super(mbscCreator, mbeanNames);
        }

        @Override
        public void reset() {
            try {
                getConnection().invoke(getMbeanName(), "resetStatistics", new Object[] {}, new String[] {});
            } catch (IOException | InstanceNotFoundException | MBeanException | ReflectionException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        protected boolean isAvailable() {
            return getSingleStatistics(Constants.STAT_CACHE_HITS) != null;
        }
    }

    private static class InfinispanChannelStatisticsImpl extends CacheStatisticsImpl {

        public InfinispanChannelStatisticsImpl(Supplier<MBeanServerConnection> mbscCreator, ObjectName mbeanName) {
            super(mbscCreator, mbeanName);
        }

        @Override
        public void reset() {
            try {
                getConnection().invoke(getMbeanName(), "resetStats", new Object[] {}, new String[] {});
            } catch (NotSerializableException ex) {
                // Ignore return value not serializable, the invocation has already done its job
            } catch (IOException | InstanceNotFoundException | MBeanException | ReflectionException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        protected boolean isAvailable() {
            return Objects.equals(getSingleStatistics(Constants.STAT_CHANNEL_CONNECTED), Boolean.TRUE);
       }
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/container/v1beta1/cluster_service.proto

package com.google.container.v1beta1;

public interface SetMasterAuthRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.container.v1beta1.SetMasterAuthRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Deprecated. The Google Developers Console [project ID or project
   * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
   * This field has been deprecated and replaced by the name field.
   *

   *
   * string project_id = 1 [deprecated = true, (.google.api.field_behavior) = REQUIRED];
   *
   *
   * @deprecated google.container.v1beta1.SetMasterAuthRequest.project_id is deprecated. See
   *     google/container/v1beta1/cluster_service.proto;l=2796
   * @return The projectId.
   */
  @java.lang.Deprecated
  java.lang.String getProjectId();
  /**
   *
   *
   *

   * Required. Deprecated. The Google Developers Console [project ID or project
   * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
   * This field has been deprecated and replaced by the name field.
   *

   *
   * string project_id = 1 [deprecated = true, (.google.api.field_behavior) = REQUIRED];
   *
   *
   * @deprecated google.container.v1beta1.SetMasterAuthRequest.project_id is deprecated. See
   *     google/container/v1beta1/cluster_service.proto;l=2796
   * @return The bytes for projectId.
   */
  @java.lang.Deprecated
  com.google.protobuf.ByteString getProjectIdBytes();

  /**
   *
   *
   *

   * Required. Deprecated. The name of the Google Compute Engine
   * [zone](https://cloud.google.com/compute/docs/zones#available) in which the
   * cluster resides. This field has been deprecated and replaced by the name
   * field.
   *

   *
   * string zone = 2 [deprecated = true, (.google.api.field_behavior) = REQUIRED];
   *
   * @deprecated google.container.v1beta1.SetMasterAuthRequest.zone is deprecated. See
   *     google/container/v1beta1/cluster_service.proto;l=2805
   * @return The zone.
   */
  @java.lang.Deprecated
  java.lang.String getZone();
  /**
   *
   *
   *

   * Required. Deprecated. The name of the Google Compute Engine
   * [zone](https://cloud.google.com/compute/docs/zones#available) in which the
   * cluster resides. This field has been deprecated and replaced by the name
   * field.
   *

   *
   * string zone = 2 [deprecated = true, (.google.api.field_behavior) = REQUIRED];
   *
   * @deprecated google.container.v1beta1.SetMasterAuthRequest.zone is deprecated. See
   *     google/container/v1beta1/cluster_service.proto;l=2805
   * @return The bytes for zone.
   */
  @java.lang.Deprecated
  com.google.protobuf.ByteString getZoneBytes();

  /**
   *
   *
   *

   * Required. Deprecated. The name of the cluster to upgrade.
   * This field has been deprecated and replaced by the name field.
   *

   *
   * string cluster_id = 3 [deprecated = true, (.google.api.field_behavior) = REQUIRED];
   *
   *
   * @deprecated google.container.v1beta1.SetMasterAuthRequest.cluster_id is deprecated. See
   *     google/container/v1beta1/cluster_service.proto;l=2812
   * @return The clusterId.
   */
  @java.lang.Deprecated
  java.lang.String getClusterId();
  /**
   *
   *
   *

   * Required. Deprecated. The name of the cluster to upgrade.
   * This field has been deprecated and replaced by the name field.
   *

   *
   * string cluster_id = 3 [deprecated = true, (.google.api.field_behavior) = REQUIRED];
   *
   *
   * @deprecated google.container.v1beta1.SetMasterAuthRequest.cluster_id is deprecated. See
   *     google/container/v1beta1/cluster_service.proto;l=2812
   * @return The bytes for clusterId.
   */
  @java.lang.Deprecated
  com.google.protobuf.ByteString getClusterIdBytes();

  /**
   *
   *
   *

   * Required. The exact form of action to be taken on the master auth.
   *

   *
   *
   * .google.container.v1beta1.SetMasterAuthRequest.Action action = 4 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The enum numeric value on the wire for action.
   */
  int getActionValue();
  /**
   *
   *
   *

   * Required. The exact form of action to be taken on the master auth.
   *

   *
   *
   * .google.container.v1beta1.SetMasterAuthRequest.Action action = 4 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The action.
   */
  com.google.container.v1beta1.SetMasterAuthRequest.Action getAction();

  /**
   *
   *
   *

   * Required. A description of the update.
   *

   *
   *
   * .google.container.v1beta1.MasterAuth update = 5 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the update field is set.
   */
  boolean hasUpdate();
  /**
   *
   *
   *

   * Required. A description of the update.
   *

   *
   *
   * .google.container.v1beta1.MasterAuth update = 5 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The update.
   */
  com.google.container.v1beta1.MasterAuth getUpdate();
  /**
   *
   *
   *

   * Required. A description of the update.
   *

   *
   *
   * .google.container.v1beta1.MasterAuth update = 5 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.container.v1beta1.MasterAuthOrBuilder getUpdateOrBuilder();

  /**
   *
   *
   *

   * The name (project, location, cluster) of the cluster to set auth.
   * Specified in the format `projects/*/locations/*/clusters/*`.
   *

   *
   * string name = 7;
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * The name (project, location, cluster) of the cluster to set auth.
   * Specified in the format `projects/*/locations/*/clusters/*`.
   *

   *
   * string name = 7;
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();
}