text:
namespace Google.Cloud.VMMigration.V1.Snippets
{
    // [START vmmigration_v1_generated_VmMigration_UpdateTargetProject_sync_flattened]
    using Google.Cloud.VMMigration.V1;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedVmMigrationClientSnippets
    {
        /// <summary>Snippet for UpdateTargetProject</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void UpdateTargetProject()
        {
            // Create client
            VmMigrationClient vmMigrationClient = VmMigrationClient.Create();
            // Initialize request argument(s)
            TargetProject targetProject = new TargetProject();
            FieldMask updateMask = new FieldMask();
            // Make the request
            Operation<TargetProject, OperationMetadata> response = vmMigrationClient.UpdateTargetProject(targetProject, updateMask);

            // Poll until the returned long-running operation is complete
            Operation<TargetProject, OperationMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            TargetProject result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<TargetProject, OperationMetadata> retrievedResponse = vmMigrationClient.PollOnceUpdateTargetProject(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                TargetProject retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END vmmigration_v1_generated_VmMigration_UpdateTargetProject_sync_flattened]
}


text:
<Alloy>
	<TableViewRow id="historialRow" selectedBackgroundColor="#238f4b" onClick="getReport">
		<ImageView id="icon"></ImageView>
		<View id="container">
			<Label id="title">
			</Label>
			<Label class="estatus">
				Estatus:
			</Label>
			<Label id="estatus">
			</Label>
		</View>
		<Label id="fecha">
		</Label>
		<ImageView class="arrow">
		</ImageView>
	</TableViewRow>
</Alloy>

redpajama_set_name: RedPajamaGithub


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.trace.database.memory;

import org.junit.Before;
import org.junit.Test;

import ghidra.dbg.target.schema.SchemaContext;
import ghidra.dbg.target.schema.TargetObjectSchema.SchemaName;
import ghidra.dbg.target.schema.XmlSchemaContext;
import ghidra.program.model.lang.LanguageID;
import ghidra.trace.model.Lifespan;
import ghidra.trace.model.target.TraceObject;
import ghidra.trace.model.target.TraceObject.ConflictResolution;
import ghidra.trace.model.thread.TraceObjectThread;
import ghidra.trace.model.thread.TraceThread;
import ghidra.trace.util.LanguageTestWatcher.TestLanguage;
import ghidra.util.database.UndoableTransaction;

public class DBTraceMemoryManagerObjectRegistersPerThreadLETest
		extends AbstractDBTraceMemoryManagerRegistersTest {

	protected SchemaContext ctx;

	@Before
	public void setUpObjectsMode() throws Exception {
		ctx = XmlSchemaContext.deserialize("""
				<context>
				    <schema name='Session' elementResync='NEVER' attributeResync='ONCE'>
				        <attribute name='Regions' schema='RegionContainer' />
				        <attribute name='Threads' schema='ThreadContainer' />
				    </schema>
				    <schema name='RegionContainer' canonical='yes' elementResync='NEVER'
				            attributeResync='ONCE'>
				        <element schema='Region' />
				    </schema>
				    <schema name='Region' elementResync='NEVER' attributeResync='NEVER'>
				        <interface name='MemoryRegion' />
				    </schema>
				    <schema name='ThreadContainer' canonical='yes' elementResync='NEVER'
				            attributeResync='ONCE'>
				        <element schema='Thread' />
				    </schema>
				    <schema name='Thread' elementResync='NEVER' attributeResync='NEVER'>
				        <interface name='Aggregate' />
				        <interface name='Thread' />
				        <attribute name='Registers' schema='RegisterContainer' />
				        <attribute name='Stack' schema='Stack' />
				    </schema>
				    <schema name='RegisterContainer' canonical='yes' elementResync='NEVER'
				            attributeResync='ONCE'>
				        <interface name='RegisterContainer' />
				        <element schema='Register' />
				    </schema>
				    <schema name='Register' elementResync='NEVER' attributeResync='NEVER'>
				        <interface name='Register' />
				    </schema>
				    <schema name='Stack' canonical='yes' elementResync='NEVER'
				            attributeResync='ONCE'>
				        <interface name='Stack' />
				        <element schema='Frame' />
				    </schema>
				    <schema name='Frame' elementResync='NEVER' attributeResync='ONCE'>
				        <interface name='StackFrame' />
				    </schema>
				</context>
				""");

		try (UndoableTransaction tid = b.startTransaction()) {
			b.trace.getObjectManager().createRootObject(ctx.getSchema(new SchemaName("Session")));
		}
	}

	@Override
	protected TraceThread getOrAddThread(String name, long creationSnap) {
		TraceThread thread = super.getOrAddThread(name, creationSnap);
		TraceObject obj = ((TraceObjectThread) thread).getObject();
		TraceObject objRegs = b.trace.getObjectManager()
				.createObject(obj.getCanonicalPath().key("Registers"));
		objRegs.insert(Lifespan.ALL, ConflictResolution.DENY);
		return thread;
	}

	@Override
	protected LanguageID getLanguageID() {
		return new LanguageID("Toy:LE:64:default");
	}

	@Override
	protected boolean isRegistersPerFrame() {
		return false;
	}

	@Test
	@TestLanguage("Toy:LE:32:builder")
	public void testRegisterBits() throws Exception {
		runTestRegisterBits(b.host);
	}
}


text:
#include <aws/datasync/model/DescribeTaskResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::DataSync::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DescribeTaskResult::DescribeTaskResult() :
    m_status(TaskStatus::NOT_SET)
{
}

DescribeTaskResult::DescribeTaskResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
    m_status(TaskStatus::NOT_SET)
{
  *this = result;
}

DescribeTaskResult& DescribeTaskResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("TaskArn"))
  {
    m_taskArn = jsonValue.GetString("TaskArn");

  }

  if(jsonValue.ValueExists("Status"))
  {
    m_status = TaskStatusMapper::GetTaskStatusForName(jsonValue.GetString("Status"));

  }

  if(jsonValue.ValueExists("Name"))
  {
    m_name = jsonValue.GetString("Name");

  }

  if(jsonValue.ValueExists("CurrentTaskExecutionArn"))
  {
    m_currentTaskExecutionArn = jsonValue.GetString("CurrentTaskExecutionArn");

  }

  if(jsonValue.ValueExists("SourceLocationArn"))
  {
    m_sourceLocationArn = jsonValue.GetString("SourceLocationArn");

  }

  if(jsonValue.ValueExists("DestinationLocationArn"))
  {
    m_destinationLocationArn = jsonValue.GetString("DestinationLocationArn");

  }

  if(jsonValue.ValueExists("CloudWatchLogGroupArn"))
  {
    m_cloudWatchLogGroupArn = jsonValue.GetString("CloudWatchLogGroupArn");

  }

  if(jsonValue.ValueExists("SourceNetworkInterfaceArns"))
  {
    Aws::Utils::Array<JsonView> sourceNetworkInterfaceArnsJsonList = jsonValue.GetArray("SourceNetworkInterfaceArns");
    for(unsigned sourceNetworkInterfaceArnsIndex = 0; sourceNetworkInterfaceArnsIndex < sourceNetworkInterfaceArnsJsonList.GetLength(); ++sourceNetworkInterfaceArnsIndex)
    {
      m_sourceNetworkInterfaceArns.push_back(sourceNetworkInterfaceArnsJsonList[sourceNetworkInterfaceArnsIndex].AsString());
    }
  }

  if(jsonValue.ValueExists("DestinationNetworkInterfaceArns"))
  {
    Aws::Utils::Array<JsonView> destinationNetworkInterfaceArnsJsonList = jsonValue.GetArray("DestinationNetworkInterfaceArns");
    for(unsigned destinationNetworkInterfaceArnsIndex = 0; destinationNetworkInterfaceArnsIndex < destinationNetworkInterfaceArnsJsonList.GetLength(); ++destinationNetworkInterfaceArnsIndex)
    {
      m_destinationNetworkInterfaceArns.push_back(destinationNetworkInterfaceArnsJsonList[destinationNetworkInterfaceArnsIndex].AsString());
    }
  }

  if(jsonValue.ValueExists("Options"))
  {
    m_options = jsonValue.GetObject("Options");

  }

  if(jsonValue.ValueExists("Excludes"))
  {
    Aws::Utils::Array<JsonView> excludesJsonList = jsonValue.GetArray("Excludes");
    for(unsigned excludesIndex = 0; excludesIndex < excludesJsonList.GetLength(); ++excludesIndex)
    {
      m_excludes.push_back(excludesJsonList[excludesIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("Schedule"))
  {
    m_schedule = jsonValue.GetObject("Schedule");

  }

  if(jsonValue.ValueExists("ErrorCode"))
  {
    m_errorCode = jsonValue.GetString("ErrorCode");

  }

  if(jsonValue.ValueExists("ErrorDetail"))
  {
    m_errorDetail = jsonValue.GetString("ErrorDetail");

  }

  if(jsonValue.ValueExists("CreationTime"))
  {
    m_creationTime = jsonValue.GetDouble("CreationTime");

  }

  if(jsonValue.ValueExists("Includes"))
  {
    Aws::Utils::Array<JsonView> includesJsonList = jsonValue.GetArray("Includes");
    for(unsigned includesIndex = 0; includesIndex < includesJsonList.GetLength(); ++includesIndex)
    {
      m_includes.push_back(includesJsonList[includesIndex].AsObject());
    }
  }

  return *this;
}


text:
require "install_gem/version"

module InstallGem
  # Your code goes here...
end


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

from bluebottle.utils.operations import AlterBaseOperation

class Migration(migrations.Migration):

    dependencies = [
        ('assignments', '0022_auto_20201013_1217'),
    ]

    operations = [
        migrations.AlterField(
            model_name='applicant',
            name='contribution_ptr',
            field=models.OneToOneField(
                auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True,
                primary_key=True, serialize=False, to='activities.Contributor')
        )
    ]


text:
this.b3editor = this.b3editor || {};

(function() {
  "use strict";

  var Action = b3.Class(b3.BaseNode);

  var p = Action.prototype;

  p.type = "action";

  p.__BaseNode_initialize = p.initialize;
  p.initialize = function() {
    this.__BaseNode_initialize();
  }

  b3editor.Action = Action;

})();


text:
package org.axonframework.serialization.converters;

import org.axonframework.serialization.AbstractContentTypeConverter;
import org.axonframework.serialization.CannotConvertBetweenTypesException;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;

/**
 * @author Allard Buijze
 */
public class BlobToInputStreamConverter extends AbstractContentTypeConverter<Blob, InputStream> {

    @Override
    public Class<Blob> expectedSourceType() {
        return Blob.class;
    }

    @Override
    public Class<InputStream> targetType() {
        return InputStream.class;
    }

    @Override
    public InputStream convert(Blob original) {
        try {
            return original.getBinaryStream();
        } catch (SQLException e) {
            throw new CannotConvertBetweenTypesException("Error while attempting to read data from Blob", e);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Candollea 7: 376 (1938)

#### Original name
Lactarius pandani R. Heim

### Remarks
null


text:
'use strict';

var should   = require('should');
var api      = require('hippie');
var routes   = this.routes;
var server   = this.server;

server.start(null, 3000);


text:
class Chef
  module Validation
    class << self
      def cookbook_version(node)
        node.run_context.cookbook_collection["validation"].metadata.version
      end
    end
  end
end


text:
<!--Create build.properties with a line like java4home =/usr/local/litle-home/"your home directory"/j2sdk1.4.2_19-->
<project name="litle-integration-magento" default="build" basedir="..">
	<description>
        Builds litle-integration-magento package
    </description>

	<property environment="env" />

	<!-- set global properties for this build -->
	<property name="version" value="8.15.4"/>
	<property name="pathToLitleMagentoIntegrationFolder" value="${env.WORKSPACE}/"/>
	<property name="pathToFolderToSaveIn" value="${env.WORKSPACE}/output/"/>

	<taskdef name="builder" classname="com.litle.magento.builder.LitleMagentoXMLWriter">
		<classpath>
			<pathelement location="${basedir}/build/magento-xml-builder.jar" />
		</classpath>
	</taskdef>

	<target name="build">
		<delete dir="${pathToFolderToSaveIn}"/>
		<mkdir dir="${pathToFolderToSaveIn}"/>
		<echo message="${basedir}"/>
		<echo message="${pathToFolderToSaveIn}"/>
		<echo message="${pathToLitleMagentoIntegrationFolder}"/>
		<!-- create the package.xml -->
		<builder
			packageVersion="${version}"
			pathToLitleMagentoIntegrationFolder="${pathToLitleMagentoIntegrationFolder}"
			pathToFolderToSaveIn="${pathToFolderToSaveIn}"
		/>

		<!-- copy the source files -->
		<copy todir="${pathToFolderToSaveIn}/app">
			<fileset dir="${pathToLitleMagentoIntegrationFolder}/app"/>
		</copy>

		<!-- Tar gz it up -->
		<mkdir dir="${basedir}/kit"/>
		<tar
			destfile="${basedir}/kit/Litle_Payments-${version}.tgz"
			basedir="${pathToFolderToSaveIn}"
			compression="gzip"/>
	</target>

	<path id="classpath.ref">
        <pathelement location="${basedir}/build/junit-4.8.2.jar" />
        <pathelement location="${basedir}/build/mysql.jar" />
        <pathelement location="${basedir}/build/selenium-2.46.0/selenium-java-2.46.0.jar"/>
        <pathelement location="${basedir}/build/selenium-2.46.0/libs/commons-exec-1.3.jar"/>
        <pathelement location="${basedir}/build/selenium-2.46.0/libs/commons-io-2.4.jar"/>
	    <pathelement location="${basedir}/build/selenium-2.46.0/libs/commons-logging-1.1.3.jar"/>
		<pathelement location="${basedir}/build/selenium-2.46.0/libs/gson-2.3.1.jar"/>
		<pathelement location="${basedir}/build/selenium-2.46.0/libs/guava-18.0.jar"/>
		<pathelement location="${basedir}/build/selenium-2.46.0/libs/httpclient-4.4.1.jar"/>
		<pathelement location="${basedir}/build/selenium-2.46.0/libs/httpcore-4.4.1.jar"/>
	</path>

	<target name="selenium">
		<mkdir dir="${basedir}/test/output"/>
		<javac destdir="${basedir}/test/output" includeantruntime="false" source="1.5" target="1.5" classpathref="classpath.ref" debug="true" debuglevel="lines,vars,source">
			<compilerarg value="-Xbootclasspath/p:${toString:lib.path.ref}" />
			<src path="test/selenium" />
		</javac>
		<mkdir dir="${basedir}/reports/selenium"/>

		<junit haltonfailure="true" printsummary="true" fork="yes">
			<classpath>
				<path refid="classpath.ref" />
				<pathelement location="${basedir}/test/output"/>
			</classpath>

			<formatter type="plain" usefile="false" />
			<formatter type="xml" />

			<batchtest todir="reports/selenium">
				<fileset dir="test/output">
					<include name="**/*Tests.class" />
				</fileset>
			</batchtest>
		</junit>
	</target>

</project>


text:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>

	</configSections>
	<Installer>
		<ShortName>V1ServiceHost</ShortName>
		<LongName>VersionOne Service Host</LongName>
	</Installer>
	<Services>

    <LogService class="VersionOne.ServiceHost.Core.Logging.LogService, VersionOne.ServiceHost.Core">

      <Console enabled="1">
        <LogLevel>Debug</LogLevel>
      </Console>

      <File enabled="1">
        <LogLevel>Info</LogLevel>

        <Filename>.\ServiceHost.log</Filename>

        <MaximumFileSize>10MB</MaximumFileSize>
      </File>
    </LogService>

		<ProfileFlushTimer class="VersionOne.ServiceHost.Core.Services.TimePublisherService,VersionOne.ServiceHost.Core">
			<Interval>15000</Interval>
			<PublishClass>VersionOne.ServiceHost.CommonMode+FlushProfile,VersionOne.ServiceHost.Core</PublishClass>
		</ProfileFlushTimer>
	</Services>
</configuration>


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('organisation', '0006_auto_20161104_1011'),
        ('tracking', '0002_auto_20161110_1518'),
    ]

    operations = [
        migrations.AddField(
            model_name='computer',
            name='location',
            field=models.ForeignKey(blank=True, help_text='Physical location', null=True, on_delete=django.db.models.deletion.PROTECT, to='organisation.Location'),
        ),
    ]


text:
//---------------------------------------------------------------------
// <copyright file="odata_format.h" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

#pragma once

namespace odata { namespace core
{

enum odata_format_type
{
    json_minimal_metadata,
    json_full_metadata,
    json_none_metadata,
};

class odata_format
{
public:
    odata_format(odata_format_type format_type) : m_format_type(format_type)
	{
	}

    odata_format_type get_format_type()
    {
        return m_format_type;
    }

private:
    odata_format_type m_format_type;
};

}}


text:
package org.apache.calcite.adapter.enumerable;

import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.convert.ConverterRule;
import org.apache.calcite.rel.logical.LogicalUnion;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * Rule to convert an {@link org.apache.calcite.rel.logical.LogicalUnion} to an
 * {@link EnumerableUnion}.
 */
class EnumerableUnionRule extends ConverterRule {
  EnumerableUnionRule() {
    super(LogicalUnion.class, Convention.NONE, EnumerableConvention.INSTANCE,
        "EnumerableUnionRule");
  }

  public RelNode convert(RelNode rel) {
    final LogicalUnion union = (LogicalUnion) rel;
    final EnumerableConvention out = EnumerableConvention.INSTANCE;
    final RelTraitSet traitSet = rel.getCluster().traitSet().replace(out);
    final List<RelNode> newInputs = Lists.transform(
        union.getInputs(), n -> convert(n, traitSet));
    return new EnumerableUnion(rel.getCluster(), traitSet,
        newInputs, union.all);
  }
}


text:
/*==============================================================================================================================
| Author        Jeremy Caney (Jeremy@Caney.net)
| Client        Skepti-Forum Project
| Project       Forum Archive
\=============================================================================================================================*/
using System;
using System.Web;
using System.Web.Mvc;
using IO = System.IO;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using SkeptiForum.Archive;
using SkeptiForum.Archive.Reporting;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace SkeptiForum.Archive.Web.Controllers {

  /*============================================================================================================================
  | CLASS: ADMIN CONTROLLER
  \---------------------------------------------------------------------------------------------------------------------------*/
  /// <summary>
  ///   Provides external access to administrative requests.
  /// </summary>
  [RoutePrefix("Admin")]
  public class AdminController : Controller {

    /*==========================================================================================================================
    | GET: /ADMIN/
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Provides access to a list of administrative options available.
    /// </summary>
    /// <remarks>
    ///   The controller provides the view with a list of all groups configured for the application. This includes the last
    ///   archive date and the last index date, which the view may use to determine which groups are in need of rearchiving
    ///   or reindexing, and provide access to the appropriate methods via the WebAPI.
    /// </remarks>
    /// <returns>The index view for available administrative tasks.</returns>
    [Route()]
    public ActionResult Index() {
      return View(ArchiveManager.Groups);
    }

  } //Class
} //Namespace


text:
package org.apache.ojb.otm.core;

/**
 *
 * TransactionListener interface is used by devices associated with a transaction to
 * respond to the events on a transaction.
 *
 * @author Raghu Rajah
 *
 */
public interface TransactionListener
{

    public void transactionBegan (Transaction target);

    public void transactionCommitting (Transaction target);

    public void transactionRollingBack (Transaction target);

}


text:
#include <dart/dart.hpp>
#include <dart/gui/osg/osg.hpp>
#include <osgShadow/ShadowMap>
#include <osgShadow/ShadowTechnique>
#include <pybind11/pybind11.h>

namespace py = pybind11;

namespace dart {
namespace python {

void InteractiveFrame(py::module& m)
{
  auto it
      = ::py::class_<
            dart::gui::osg::InteractiveTool,
            dart::dynamics::SimpleFrame,
            std::shared_ptr<dart::gui::osg::InteractiveTool>>(
            m, "InteractiveTool")
            .def(
                ::py::init<
                    dart::gui::osg::InteractiveFrame*,
                    double,
                    const std::string&>(),
                ::py::arg("frame"),
                ::py::arg("defaultAlpha"),
                ::py::arg("name"))
            .def(
                "setEnabled",
                +[](dart::gui::osg::InteractiveTool* self, bool enabled) {
                  self->setEnabled(enabled);
                },
                ::py::arg("enabled"))
            .def(
                "getEnabled",
                +[](const dart::gui::osg::InteractiveTool* self) -> bool {
                  return self->getEnabled();
                })
            .def(
                "setAlpha",
                +[](dart::gui::osg::InteractiveTool* self, double alpha) {
                  self->setAlpha(alpha);
                },
                ::py::arg("alpha"))
            .def(
                "resetAlpha",
                +[](dart::gui::osg::InteractiveTool* self) {
                  self->resetAlpha();
                })
            .def(
                "setDefaultAlpha",
                +[](dart::gui::osg::InteractiveTool* self, double alpha) {
                  self->setDefaultAlpha(alpha);
                },
                ::py::arg("alpha"))
            .def(
                "setDefaultAlpha",
                +[](dart::gui::osg::InteractiveTool* self,
                    double alpha,
                    bool reset) { self->setDefaultAlpha(alpha, reset); },
                ::py::arg("alpha"),
                ::py::arg("reset"))
            .def(
                "getDefaultAlpha",
                +[](const dart::gui::osg::InteractiveTool* self) -> double {
                  return self->getDefaultAlpha();
                })
            .def(
                "getShapeFrames",
                +[](dart::gui::osg::InteractiveTool* self)
                    -> const std::vector<dart::dynamics::SimpleFrame*> {
                  return self->getShapeFrames();
                })
            .def(
                "getShapeFrames",
                +[](const dart::gui::osg::InteractiveTool* self)
                    -> const std::vector<const dart::dynamics::SimpleFrame*> {
                  return self->getShapeFrames();
                })
            .def(
                "removeAllShapeFrames",
                +[](dart::gui::osg::InteractiveTool* self) {
                  self->removeAllShapeFrames();
                });

  ::py::enum_<dart::gui::osg::InteractiveTool::Type>(it, "Type")
      .value("LINEAR", dart::gui::osg::InteractiveTool::Type::LINEAR)
      .value("ANGULAR", dart::gui::osg::InteractiveTool::Type::ANGULAR)
      .value("PLANAR", dart::gui::osg::InteractiveTool::Type::PLANAR)
      .value("NUM_TYPES", dart::gui::osg::InteractiveTool::Type::NUM_TYPES)
      .export_values();

  ::py::class_<
      dart::gui::osg::InteractiveFrame,
      dart::dynamics::SimpleFrame,
      std::shared_ptr<dart::gui::osg::InteractiveFrame>>(m, "InteractiveFrame")
      .def(::py::init<dart::dynamics::Frame*>(), ::py::arg("referenceFrame"))
      .def(
          ::py::init<dart::dynamics::Frame*, const std::string&>(),
          ::py::arg("referenceFrame"),
          ::py::arg("name"))
      .def(
          ::py::init<
              dart::dynamics::Frame*,
              const std::string&,
              const Eigen::Isometry3d&>(),
          ::py::arg("referenceFrame"),
          ::py::arg("name"),
          ::py::arg("relativeTransform"))
      .def(
          ::py::init<
              dart::dynamics::Frame*,
              const std::string&,
              const Eigen::Isometry3d&,
              double>(),
          ::py::arg("referenceFrame"),
          ::py::arg("name"),
          ::py::arg("relativeTransform"),
          ::py::arg("sizeScale"))
      .def(
          ::py::init<
              dart::dynamics::Frame*,
              const std::string&,
              const Eigen::Isometry3d&,
              double,
              double>(),
          ::py::arg("referenceFrame"),
          ::py::arg("name"),
          ::py::arg("relativeTransform"),
          ::py::arg("sizeScale"),
          ::py::arg("thicknessScale"))
      .def(
          "resizeStandardVisuals",
          +[](dart::gui::osg::InteractiveFrame* self) {
            self->resizeStandardVisuals();
          })
      .def(
          "resizeStandardVisuals",
          +[](dart::gui::osg::InteractiveFrame* self, double size_scale) {
            self->resizeStandardVisuals(size_scale);
          },
          ::py::arg("sizeScale"))
      .def(
          "resizeStandardVisuals",
          +[](dart::gui::osg::InteractiveFrame* self,
              double size_scale,
              double thickness_scale) {
            self->resizeStandardVisuals(size_scale, thickness_scale);
          },
          ::py::arg("sizeScale"),
          ::py::arg("thicknessScale"))
      .def(
          "getShapeFrames",
          +[](dart::gui::osg::InteractiveFrame* self)
              -> const std::vector<dart::dynamics::SimpleFrame*> {
            return self->getShapeFrames();
          })
      .def(
          "getShapeFrames",
          +[](const dart::gui::osg::InteractiveFrame* self)
              -> const std::vector<const dart::dynamics::SimpleFrame*> {
            return self->getShapeFrames();
          })
      .def(
          "removeAllShapeFrames", +[](dart::gui::osg::InteractiveFrame* self) {
            self->removeAllShapeFrames();
          });
}

} // namespace python
} // namespace dart


text:
This directory contains modules that export webdriver.io functionality.
The modules contain logic associated to the feature of COINS that they interact with.

Require these modules in your test script, and use them to interact with the browser.


text:
<!DOCTYPE html>
<!--
This test verifies that a fixed position element inside an iframe paints when
it comes into view due to the iframe increasing in size.

If this test passes, you should see a green square.
-->
<html>
<head>
    <style>
        #iframe-containing-fixed-position-element {
            background: red;
            width: 100px;
            height: 0;
            border: 0;
        }
    </style>
    <script src="../../resources/run-after-layout-and-paint.js"></script>
    <script>
        if (window.testRunner)
            testRunner.waitUntilDone();

        if (window.internals)
            window.internals.settings.setPreferCompositingToLCDTextEnabled(true);

        function runTest()
        {
            // Initially, the fixed position element in the iframe will not
            // paint because the iframe has zero height.
            runAfterLayoutAndPaint(function() {
                // Give the iframe a non-zero height. The fixed position element
                // inside the iframe should paint now.
                var iframeElement = document.getElementById("iframe-containing-fixed-position-element");
                iframeElement.style.height = "100px";

                if (window.testRunner)
                    testRunner.notifyDone();
            });
        }
    </script>
</head>
<body onload="runTest()">
    <iframe id="iframe-containing-fixed-position-element" src="resources/subframe-with-fixed-position-element.html"></iframe>
</body>
</html>


text:
(function () {

    // Main module
    var app = angular.module('odalic-app');

    var currentFolder = $.getPathForRelativePath('');
    app.directive('fileinput', function ($filter, rest, filedata, reporth, formsval) {
        return {
            restrict: 'E',
            scope: {
                bind: '=',
                form: '='
            },
            templateUrl: currentFolder + 'fileinput.html',
            link: function (scope, iElement, iAttrs) {

                // Is the form ready?
                scope.taskCreationFormReady = function () {
                    return !!scope.form;
                };

                // Initialization
                formsval.toScope(scope);
                scope.confirm = {};
                scope.files = {};
                scope.remoteFile = {};
                scope.messages = {};
                scope.fileconfig = {};

                // File list
                scope.fileList = {
                    // File selection enabled?
                    fileSelection: (iAttrs['selection'] === 'true'),

                    // List of (uploaded or attached) file identifiers
                    identifiers: [],

                    // Refresh the list of uploaded files
                    refresh: function (callback) {
                        var _ref = this;
                        rest.files.list.exec(
                            // Success
                            function (response) {
                                _ref.identifiers = response;
                                if (callback) {
                                    callback(true);
                                }
                            },
                            // Failure
                            function failure(response) {
                                if (callback) {
                                    callback(false);
                                }
                            }
                        );
                    },

                    getIndex: function (identifier) {
                        var index = null;
                        for (var i = 0; i < this.identifiers.length; i++) {
                            if (this.identifiers[i].id === identifier) {
                                index = i;
                                break;
                            }
                        }
                        return index;
                    },

                    getID: function (index) {
                        return this.identifiers[index].id;
                    },

                    setSelected: function (index) {
                        this.selectedFile = this.identifiers[index];
                    }
                };

                // Miscellaneous
                var testOverwrite = function (fileId, process, fallback) {
                    rest.files.name(fileId).exists(
                        // The file already exists => confirm overwrite
                        function () {
                            scope.confirm.open(function (response) {
                                if (response === true) {
                                    process();
                                } else {
                                    // Overwrite rejected => do some 'cleaning'
                                    fallback();

                                    // Clicking outside of the modal is not registered by angular, but clicking on the modal button is => manually call digest cycle if necessary
                                    if (!scope.$root.$$phase) {
                                        scope.$apply();
                                    }
                                }
                            });
                        },
                        // The file does not exist yet => continue without any prompt
                        process
                    );
                };

                // File uploading
                scope.fileUpload = {
                    // Id of the input-file element
                    inputFileId: 'concreteFile',

                    // Button for file uploading disabled?
                    isUploadDisabled: true,

                    // Identifier of the file to be uploaded
                    identifier: String(),

                    // Automatically fill the 'identifier' when a file is selected
                    fillIdentifier: function () {
                        var name = filedata.fileName(this.inputFileId);
                        this.isUploadDisabled = !name;
                        if (!name) {
                            name = text.randomId();
                        }

                        this.identifier =  $filter('conform')(name, '-a-zA-Z0-9_., ');
                        if (!scope.$$phase) {
                            scope.$apply();
                        }
                    },

                    // Upload the selected file
                    uploadFile: function (f) {
                        // Validate
                        if (!formsval.validate(scope.localFileForm)) {
                            f();
                            return;
                        }

                        // Reference to self
                        var _ref = scope.fileUpload;

                        // Uploading the file asynchronously
                        sendData = function (fileData) {
                            rest.files.name(_ref.identifier).create.upload(filedata.fileObject(_ref.inputFileId)).exec(
                                // Success
                                function () {
                                    // The file has been uploaded successfully => refresh the list of available files
                                    scope.fileList.refresh(function (succes) {
                                        // Display a success message
                                        scope.messages.push('success', scope['msgtxt.uploadSuccessful']);

                                        // Sets the newly uploaded file as the selected one
                                        scope.fileList.setSelected(scope.fileList.getIndex(_ref.identifier));

                                        // Clear the fields
                                        _ref.identifier = new String();
                                        filedata.clearInputFile(_ref.inputFileId);
                                        scope.form.localFileForm.$setPristine();

                                        // Another file may be uploaded again
                                        f();
                                        _ref.isUploadDisabled = true;

                                        // Clear chosen file
                                        angular.element("input[type='file']").val(null);
                                    });
                                },
                                // Failure
                                function (response) {
                                    // The file has not been uploaded => display an error message
                                    scope.messages.push('error', reporth.constrErrorMsg(scope['msgtxt.uploadFailure'], response.data));

                                    // A file may be uploaded again
                                    f();
                                }
                            );
                        };

                        // Read the file and send the data to server
                        var process = function () {
                            filedata.readBase64(_ref.inputFileId,
                                // Success
                                function (fileData) {
                                    sendData(fileData);
                                },
                                // Failure
                                function (response) {
                                    scope.messages.push('error', (new String()).concat(scope['msgtxt.uploadFailure'], ' ', response));

                                    // A file may be uploaded again
                                    f();
                                }
                            );
                        };

                        // Insert the file, if everything is OK
                        testOverwrite(_ref.identifier, process, f);
                    }
                };

                // Remote file attaching
                scope.fileAttach = {
                    // Identifier of the file to be attached
                    identifier: String(),

                    // Location of the file to be attached
                    location: String(),

                    // Attach the selected file
                    attachFile: function (f) {
                        // Reference to self
                        var _ref = scope.fileAttach;

                        // Send the REST request
                        var process = function () {
                            rest.files.name(_ref.identifier).create.remote(_ref.location).exec(
                                // Success
                                function () {
                                    // The file has been attached successfully => refresh the list of available files
                                    scope.fileList.refresh(function (succes) {
                                        // Display a success message
                                        scope.messages.push('success', scope['msgtxt.attachSuccessful']);

                                        // Sets the newly attached file as the selected one
                                        scope.fileList.setSelected(scope.fileList.getIndex(_ref.identifier));

                                        // Clear the fields
                                        _ref.identifier = new String();
                                        _ref.location = scope['deflocation'];
                                        scope.form.remoteFileForm.$setPristine();

                                        // Another file may be uploaded again
                                        f();
                                    });
                                },
                                // Failure
                                function (response) {
                                    // The file has not been attached => display an error message
                                    scope.messages.push('error', reporth.constrErrorMsg(scope['msgtxt.attachFailure'], response.data));

                                    // A file may be uploaded again
                                    f();
                                }
                            );
                        };

                        // Attach the file, if everything is OK
                        testOverwrite(_ref.identifier, process, f);
                    }
                };

                // File configuration
                scope.configureFile = function () {
                    scope.fileconfig.identifier = scope.bind.getSelectedFile();
                    scope.fileconfig.open();
                };

                // Additional actions
                scope.fileList.refresh();

                // Public interface
                scope.bind.isFileSelected = function () {
                    var fl = scope.fileList;
                    return !!fl.selectedFile && !!fl.selectedFile.id;
                };

                scope.bind.getSelectedFile = function () {
                    if (!scope.bind.isFileSelected()) {
                        throw new Error('fileinput component: No file selected.');
                    }
                    return scope.fileList.selectedFile.id;
                };

                scope.bind.setSelectedFile = function (id) {
                    var fl = scope.fileList;
                    if (typeof(id) === 'string') {
                        timed.ready(function () { return !!fl.identifiers && (fl.identifiers.length > 0); }, function () {
                            fl.setSelected(fl.getIndex(id));
                        });
                    } else {
                        throw new Error('fileinput component: Unsupported argument id.');
                    }
                };

                scope.bind.pushAlert = function(type, text) {
                    scope.messages.push(type, text);
                };
            }
        }
    });

})();


text:
import {getMode} from './mode';

/**
 * Reports an error. If the error has an "associatedElement" property
 * the element is marked with the -amp-element-error and displays
 * the message itself. The message is always send to the console.
 * If the error has a "messageArray" property, that array is logged.
 * This way one gets the native fidelity of the console for things like
 * elements instead of stringification.
 * @param {!Error} error
 * @param {!Element=} opt_associatedElement
 */
export function reportErrorToDeveloper(error, opt_associatedElement) {
  if (!window.console) {
    return;
  }
  if (error.reported) {
    return;
  }
  error.reported = true;
  var element = opt_associatedElement || error.associatedElement;
  if (element) {
    element.classList.add('-amp-error');
    if (getMode().development) {
      element.classList.add('-amp-element-error');
      element.setAttribute('error-message', error.message);
    }
  }
  if (error.messageArray) {
    (console.error || console.log).apply(console,
        error.messageArray);
  } else {
    (console.error || console.log).call(console, error.message);
  }
  if (element && element.dispatchCustomEvent) {
    element.dispatchCustomEvent('amp:error', error.message);
  }
}


text:
AFRAME.registerSystem('render-order', {
  schema: {type: 'array'},

  init: function () {
    this.el.renderer.sortObjects = true;
  },

  update: function () {
    this.order = {};
    for (i = 0; i < this.data.length; i++) {
      this.order[this.data[i]] = i;
    }
  }
});

AFRAME.registerComponent('render-order', {
  schema: {type: 'string'},

  multiple: true,

  init: function () {
    this.set = this.set.bind(this);
    this.el.addEventListener('object3dset', evt => {
      if (this.id !== 'nonrecursive') {
        evt.detail.object.traverse(this.set);
      }
    });
  },

  update: function () {
    if (this.id === 'nonrecursive') {
      this.set(this.el.object3D);
    } else {
      this.el.object3D.traverse(this.set);
    }
  },

  set: function (node) {
    // String (named order).
    if (isNaN(this.data)) {
      node.renderOrder = this.system.order[this.data];
    } else {
      node.renderOrder = parseFloat(this.data);
    }
  }
});

AFRAME.registerComponent('render-order-recursive', {
  init: function () {
    this.el.addEventListener('child-attached', evt => {
      evt.detail.el.setAttribute('render-order', this.el.getAttribute('render-order'));
    });
  }
});


text:
#ifndef SkResultsWriter_DEFINED
#define SkResultsWriter_DEFINED

#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "src/utils/SkJSONWriter.h"
#include <cmath>

/**
 NanoJSONResultsWriter helps nanobench writes the test results out in the following format:

 {
    "key": {
      "arch": "Arm7",
      "gpu": "SGX540",
      "os": "Android",
      "model": "GalaxyNexus",
    }
    "gitHash": "d1830323662ae8ae06908b97f15180fd25808894",
    "build_number": "1234",
    "results" : {
        "Xfermode_Luminosity_640_480" : {
           "8888" : {
                 "median_ms" : 143.188128906250,
                 "min_ms" : 143.835957031250,
                 ...
              },
          ...
*/
class NanoJSONResultsWriter : public SkJSONWriter {
public:
    NanoJSONResultsWriter(SkWStream* stream, Mode mode) : SkJSONWriter(stream, mode) {}

    void beginBench(const char* name, int32_t x, int32_t y) {
        SkString id = SkStringPrintf("%s_%d_%d", name, x, y);
        this->beginObject(id.c_str());
    }

    void endBench() { this->endObject(); }

    void appendMetric(const char* name, double value) {
        // Don't record if NaN or Inf.
        if (std::isfinite(value)) {
            this->appendDoubleDigits(name, value, 16);
        }
    }
};

#endif


text:
module ActiveRecord
  class Migration
    module Compatibility # :nodoc: all
      def self.find(version)
        version = version.to_s
        name = "V#{version.tr('.', '_')}"
        unless const_defined?(name)
          versions = constants.grep(/\AV[0-9_]+\z/).map { |s| s.to_s.delete("V").tr("_", ".").inspect }
          raise ArgumentError, "Unknown migration version #{version.inspect}; expected one of #{versions.sort.join(', ')}"
        end
        const_get(name)
      end

      V5_2 = Current

      class V5_1 < V5_2
      end

      class V5_0 < V5_1
        module TableDefinition
          def primary_key(name, type = :primary_key, **options)
            type = :integer if type == :primary_key
            super
          end

          def references(*args, **options)
            super(*args, type: :integer, **options)
          end
          alias :belongs_to :references
        end

        def create_table(table_name, options = {})
          if adapter_name == "PostgreSQL"
            if options[:id] == :uuid && !options.key?(:default)
              options[:default] = "uuid_generate_v4()"
            end
          end

          unless adapter_name == "Mysql2" && options[:id] == :bigint
            if [:integer, :bigint].include?(options[:id]) && !options.key?(:default)
              options[:default] = nil
            end
          end

          # Since 5.1 PostgreSQL adapter uses bigserial type for primary
          # keys by default and MySQL uses bigint. This compat layer makes old migrations utilize
          # serial/int type instead -- the way it used to work before 5.1.
          unless options.key?(:id)
            options[:id] = :integer
          end

          if block_given?
            super do |t|
              yield compatible_table_definition(t)
            end
          else
            super
          end
        end

        def change_table(table_name, options = {})
          if block_given?
            super do |t|
              yield compatible_table_definition(t)
            end
          else
            super
          end
        end

        def create_join_table(table_1, table_2, column_options: {}, **options)
          column_options.reverse_merge!(type: :integer)

          if block_given?
            super do |t|
              yield compatible_table_definition(t)
            end
          else
            super
          end
        end

        def add_column(table_name, column_name, type, options = {})
          if type == :primary_key
            type = :integer
            options[:primary_key] = true
          end
          super
        end

        def add_reference(table_name, ref_name, **options)
          super(table_name, ref_name, type: :integer, **options)
        end
        alias :add_belongs_to :add_reference

        private
          def compatible_table_definition(t)
            class << t
              prepend TableDefinition
            end
            t
          end
      end

      class V4_2 < V5_0
        module TableDefinition
          def references(*, **options)
            options[:index] ||= false
            super
          end
          alias :belongs_to :references

          def timestamps(**options)
            options[:null] = true if options[:null].nil?
            super
          end
        end

        def create_table(table_name, options = {})
          if block_given?
            super do |t|
              yield compatible_table_definition(t)
            end
          else
            super
          end
        end

        def change_table(table_name, options = {})
          if block_given?
            super do |t|
              yield compatible_table_definition(t)
            end
          else
            super
          end
        end

        def add_reference(*, **options)
          options[:index] ||= false
          super
        end
        alias :add_belongs_to :add_reference

        def add_timestamps(_, **options)
          options[:null] = true if options[:null].nil?
          super
        end

        def index_exists?(table_name, column_name, options = {})
          column_names = Array(column_name).map(&:to_s)
          options[:name] =
            if options[:name].present?
              options[:name].to_s
            else
              index_name(table_name, column: column_names)
            end
          super
        end

        def remove_index(table_name, options = {})
          options = { column: options } unless options.is_a?(Hash)
          options[:name] = index_name_for_remove(table_name, options)
          super(table_name, options)
        end

        private
          def compatible_table_definition(t)
            class << t
              prepend TableDefinition
            end
            t
          end

          def index_name_for_remove(table_name, options = {})
            index_name = index_name(table_name, options)

            unless index_name_exists?(table_name, index_name)
              if options.is_a?(Hash) && options.has_key?(:name)
                options_without_column = options.dup
                options_without_column.delete :column
                index_name_without_column = index_name(table_name, options_without_column)

                return index_name_without_column if index_name_exists?(table_name, index_name_without_column)
              end

              raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
            end

            index_name
          end
      end
    end
  end
end


text:
/**
 * @description contains jsObject (for manipulating objects), jsTest (for testing variables),
 * and prototypes
 * @author Clemens Hagenbuchner <hagenbuchner@student.tugraz.at>
 * @module Prototypes
 * @requires jQuery (jsObject.deepclone)
 */

class jsObject {
    /**
     * für alle Attribute eines Objektes die übergebene Funktion ausführen
     *
     * @param {*} obj das zugrundeliegende Objekt
     * @param {function} event die auszuführende Funktion (attribut, attribut-name, objekt)
     */
    static forEachProperty(obj, event) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                event(obj[property], property, obj);
            }
        }
    }

    /**
     * calls the given function on each object in the Array
     * @param {array} array array on which to call the functions
     * @param {function} call function to be called on each item
     */
    static withEach(array, call) {
        if (array === null) return;
        if (array.constructor === Array) {
            if (array.length > 0) {
                array.forEach(call);
            }
        } else {
            call(array);
        }
    }

    /**
     * Clones an object, by assigning each property to a new object
     * (doesn't deep clone!)
     * @param {*} obj Object to be copied
     * @returns {*} new Object
     */
    static shallowClone(obj) {
        return Object.assign({}, obj);
    }

    /**
     * DeepClones an object, by assigning each property to a new object
     * @param {*} obj Object to be copied
     * @returns {*} new Object
     * @requires jQuery
     */
    static deepClone(obj) {
        return jQuery.extend(true, {}, obj);
    }

    /**
     * Merges the given object, values from mainObj will be favorised
     * @param {*} mainObj Primary Object
     * @param {*} newObj Secondary Object, from which to take the new properties
     * @param {*} defaultObj Default Object, for default values
     * @requires jQuery
     */
    static merge(mainObj, newObj, defaultObj) {
        return jQuery.extend(true, {}, defaultObj, newObj, mainObj);
    }
}

/**
 * Weitere Funktionen zum Prüfen von Variablen
 */
class jsTest {
    /**
     *  prüft ob die Variable definiert und auf den gegebenen Wert gesetzt ist
     *
     * @param {*} test zu testende Variable
     * @param {*=} value zu vergleichender Wert (optional, falls nicht gegeben wird gegen true verglichen)
     */
    static isSet(test, value) {
        try {
            return jsTest.isDef(test) ? jsTest.isDef(value) ? test === value : test === true : false;
        } catch (e) { return false; }
    }

    /**
     *  prüft ob die Variable definiert und eine Funktion ist
     * @param {*} test zu testende Variable
     */
    static isFunction(test) {
        try {
            return (jsTest.isDef(test) && test.constructor === Function)
        } catch (e) { return false; }
    }

    /**
     *  prüft ob die Variable definiert und eine Zahl ist
     * @param {*} test zu testende Variable
     */
    static isNumber(test) {
        try {
            return (jsTest.isDef(test) && test.constructor === Number)
        } catch (e) { return false; }
    }

    static isNumberArray(test) {
        try {
            if (!jsTest.isFilledArray(test)) return false;
            return test.all(item => jsTest.isNumber(item));
        } catch (e) { return false; }
    }

    /**
     *  prüft ob die Variable definiert und eine Zahl darstellt (kann auch String sein)
     * @param {*} test zu testende Variable
     */
    static isNumerical(test) {
        try {
            if (jsTest.isString(test)) {
                var match = test.match(/\d+(\\.\d*)?/);
                if (match != null && match.length > 0) return true;
            }
            if (jsTest.isNumber(test)) return true;
            return false;
        } catch (e) { return false; }
    }

    /**
     *  prüft ob die Variable definiert ist
     * @param {*} test zu testende Variable
     */
    static isDef(test) {
            try {
                return (typeof test !== 'undefined' && test !== null && test !== undefined);
            } catch (e) { return false; }
        }
        /**
         * retouniert das Test-Objekt wenn dieses definiert ist, ansonsten den Default-Wert
         *
         * @param {*} test Test-Objekt
         * @param {*} default_value Default-Wert
         * @returns
         */
    static use(test, default_value) {
        return jsTest.isDef(test) ? test : default_value;
    }

    /**
     *  prüft ob die Variable definiert und ein String ist
     * @param {*} test zu testende Variable
     */
    static isString(test) {
            try {
                return (jsTest.isDef(test) && (test.constructor === String || typeof test === 'string'))
            } catch (e) { return false; }
        }
        /**
         *  prüft ob die Variable definiert und ein String ist (nicht leer)
         * @param {*} test zu testende Variable
         */
    static isFilledString(test) {
        return (jsTest.isString(test) && test.length > 0);
    }

    /**
     *  prüft ob die Variable definiert und ein Array ist
     * @param {*} test zu testende Variable
     */
    static isArray(test) {
            try {
                return (jsTest.isDef(test) && test.constructor === Array)
            } catch (e) { return false; }
        }
        /**
         *  prüft ob die Variable definiert und ein Array ist (befüllt)
         * @param {*} test zu testende Variable
         */
    static isFilledArray(test) {
        return (jsTest.isArray(test) && test.length > 0);
    }
};

/**
 * escape ä/ü/ö/... in a string
 */
String.prototype.escapeCharacters = function() {
    return this.replace(/[ä\u00E4]/g, 'ä').replace(/[ü\u00FC]/g, 'ü')
        .replace(/[ö\u00F6]/g, 'ö').replace(/[Ä\u00C4]/g, 'Ä')
        .replace(/[Ü\u00DC]/g, 'Ü').replace(/[Ö\u00D6]/g, 'Ö')
        .replace(/[ß\u00DF]/g, 'ß').replace(/ü/g, 'ü');
}

/**
 * capitalize string
 */
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

/**
 * check if the string contains the text element
 * @param {string} text The text to check if it is contained
 * @returns {boolean} True if it is included
 */
String.prototype.contains = function(text) {
    if (typeof this.includes !== 'undefined') return this.includes(text);
    return this.indexOf(text) > -1;
}

/**
 * splits the string and parses each part as a float
 * @param {string} seperator The seperator for splitting the string
 * @returns {number[]} parsed Numbers
 */
String.prototype.splitNumbers = function(seperator) {
    return this.split(seperator).toFloat();
}

/**
 * entfernt alle nicht definierten Elemente aus dem Array
 *
 * @param {array} array Input-Array (wird nicht verändert)
 */
Array.prototype.clearNullElements = function() {
    //function clearNullElements(array) {
    var newAry = [];
    this.forEach(function(elem) {
        if (elem !== null && typeof(elem) !== 'undefined')
            newAry.push(elem);
    });
    return newAry;
}

/**
 * gibt das größte Element aus dem Array zurück
 * @param {array} array Input Array
 */
Array.prototype.max = function() {
    return Math.max.apply(null, this);
}

/**
 * gibt das kleinste Element aus dem Array zurück
 * @param {array} array Input Array
 */
Array.prototype.min = function() {
    return Math.min.apply(null, this);
}

/**
 * sicherer Zugriff auf ein Array
 * @param {number} index Index im Array
 */
Array.prototype.tryget = function(index) {
    try {
        if (this.length > index && index >= 0) return this[index];
        else return null;
    } catch (err) {
        return null;
    }
}

/**
 * entfernt alle doppelten Einträge aus dem Array
 *
 * @param {array} array altes Array (wird nicht verändert)
 * @requires jQuery
 * @returns neues gefiltertes Array
 */
Array.prototype.unique = function() {
    try {
        var result = [];
        // alle Elemente durchgehen, wenn ein Eintrag noch nicht im Array ist,
        // zum neuen hinzufügen
        this.forEach(function(elem) {
            if (jQuery.inArray(elem, result) == -1 && elem !== null) {
                result.push(elem);
            }
        });
        return result;
    } catch (err) {
        console.error(err);
        return [];
    }
}

/**
 * führt für alle Einträge eine Funktion aus, wobei doppelte Einträge ignoriert werden
 *
 * @param {array} array altes Array (wird nicht verändert)
 * @param {function} call Funktion, welches für jeden Eintrag einmal aufgerufen wird
 * @requires jQuery
 * @returns neues gefiltertes Array
 */
Array.prototype.forEachUnique = function(call) {
    try {
        var result = [];
        // alle Elemente durchgehen, wenn ein Eintrag noch nicht im Array ist,
        // zum neuen hinzufügen
        this.forEach(function(elem) {
            if (jQuery.inArray(elem, result) == -1 && elem !== null) {
                result.push(elem);
                call(elem);
            }
        });
        return result;
    } catch (err) {
        console.error(err);
        return [];
    }
}

/**
 * erweitert das Array in dem jeder Eintrag mit dem Wert von part kombiniert dem
 * Array hinzugefügt wird.
 * Zusätzlich wird ein neuer Eintrag mit dem Wert von part angelegt
 *
 * @param {string[]} array anzupassendes Array (wird nicht verändert)
 * @param {string} part der Anhang zu jedem Eintrag
 * @param {string} seperator Zeichenfolge die zwischen den alten Eintrag und dem Anhang
 * eingefügt wird.
 */
Array.prototype.expandBy = function(part, seperator) {
    try {
        var newA = this.slice(); // erzeugt Kopie des Arrays.
        this.forEach(function(elem) {
            newA.push(elem + seperator + part);
        });
        newA.push(part);
        return newA;
    } catch (err) {
        return [];
    }
}

/**
 * erweitert das Array in dem an jeden Eintrag der Wert von part angehängt wird
 * zusätzlich wird ein neuer Eintrag mit dem Wert von part angelegt
 *
 * @param {string[]} array die ursprünglichen Einträge (wird nicht verändert)
 * @param {string} part der Anhang für jeden Eintrag
 * @param {string} seperator Zeichenfolge die zwischen den alten Eintrag und dem Anhang
 * eingefügt wird.
 */
Array.prototype.extendWith = function(part, seperator) {
    try {
        var newA = [];
        this.forEach(function(elem) {
            newA.push(elem + seperator + part);
        });
        newA.push(part);
        return newA;
    } catch (err) {
        console.error(err);
        return [];
    }
}

/**
 * gibt alle Einträge aus dem Array zurück, welche die Bedingung erfüllen
 * @param {function} testfunction Funktion zum Prüfen des Eintrags (elem => bool)
 * Use .filter
 */
Array.prototype.where = function(testfunction) {
        if (typeof(this.filter) !== 'undefined')
            return this.filter(testfunction);
        try {
            var newA = [];
            this.forEach(function(elem) {
                if (testfunction(elem)) newA.push(elem);
            });
            return newA;
        } catch (err) {
            console.error(err);
            return [];
        }
    }
    /**
     * projiziert alle Einträge in ein neues Format und gibt das neue Array zurück
     * @param {function} convert Funktion zum projizieren der Einträge (elem => newelem)
     */
Array.prototype.select = function(convert) {
        try {
            var newA = [];
            this.forEach(function(elem) {
                try {
                    newA.push(convert(elem));
                } catch (err) { console.error(err); }
            });
            return newA;
        } catch (err) {
            console.error(err);
            return [];
        }
    }
    /**
     * projiziert alle Einträge in ein neues Format (integer) und gibt das neue Array zurück
     */
Array.prototype.toInt = function() {
        return this.select(parseInt);
    }
    /**
     * projiziert alle Einträge in ein neues Format (float) und gibt das neue Array zurück
     */
Array.prototype.toFloat = function() {
        return this.select(parseFloat);
    }
    /**
     * projiziert alle Einträge, die die Bedingung erfüllen in ein neues Format und gibt das neue Array zurück
     * @param {function} testfunction Funktion zum Überprüfen, ob Bedingung erfüllt
     * @param {function} convert Funktion zum projizieren der Einträge (elem => newelem)
     */
Array.prototype.selectwhere = function(testfunction, convert) {
        try {
            var newA = [];
            this.forEach(function(elem) {
                if (testfunction(elem)) newA.push(convert(elem));
            });
            return newA;
        } catch (err) {
            console.error(err);
            return [];
        }
    }
    /**
     * führt für jedes Element die übergebene Funktion aus und gibt das Gesamtergebnis zurück
     * @param {*} seed Startwert
     * @param {function} method Funktion zum Erzeugen des neuen Ergebnisses (elem, old => new)
     */
Array.prototype.aggregate = function(seed, method) {
    try {
        var obj = seed;
        this.forEach(function(elem) {
            obj = method(elem, obj);
        });
        return obj;
    } catch (err) {
        console.error(err);
        return seed;
    }
}

/**
 * fügt ein Objekt hinzu oder entfernt es aus dem Array
 * @param {array} array Array, zu welchem das Element hinzugefügt oder aus welchem es entfernt werden soll
 *  (wird nicht verändert)
 * @param {*} obj hinzu zufügendes oder zu entfernendes Objekt
 * @param {function} compare Funktion zum ermitteln ob das Objekt einem Array-Element entspricht
 * @param {boolean} all falls obj ein Array ist, wird bei all = true, werden alle Layer entweder hinzugefügt oder entfernt
 */
Array.prototype.compareXChange = function(obj, compare, all) {
    if (obj === null || typeof(obj) === 'undefined')
        return this.slice();
    if (obj.constructor === Array) {
        var newArr = [];
        this.forEach(function(elem) {
            for (var i = 0; i < obj.length; i++) {
                if (compare(elem, obj[i])) {
                    if (all) obj = [];
                    else obj.splice(i, 1);
                    return;
                }
            }
            newArr.push(elem);
        });
        newArr = newArr.concat(obj);
    } else {
        var found = false;
        this.forEach(function(elem) {
            if (!compare(elem, obj)) newArr.push(elem);
            else found = true;
        });
        if (!found) newArr.push(obj);
    }
    return newArr;
}

/**
 * fügt ein Objekt hinzu sofern es nicht bereits vorhanden ist
 * @param {array} array Array, zu welchem das Element hinzugefügt werden soll
 *  (wird nicht verändert)
 * @param {*} obj hinzu zufügendes Objekt
 * @param {function} compare Funktion zum ermitteln ob das Objekt einem Array-Element entspricht
 */
Array.prototype.pushOnce = function(obj, compare) {
    if (obj === null || typeof(obj) === 'undefined')
        return this.slice();
    var newArr = this.slice();
    if (obj.constructor === Array) {
        this.forEach(function(elem) {
            for (var i = 0; i < obj.length; i++) {
                if (compare(elem, obj[i]))
                    obj.splice(i, 1);
            }
        });
        return newArr.concat(obj);
    } else {
        var found = false;
        this.forEach(function(elem) {
            if (compare(elem, obj)) found = true;
        });
        if (!found) newArr.push(obj);
        return newArr;
    }
}

/**
 * fügt ein LayerElement hinzu oder entfernt es aus dem Array (Vergleich aufgrund property ol_uid)
 * @param {*} obj Layer welcher hinzugefügt oder entfernt werden soll
 * @param {boolean} all falls obj ein Array ist, wird bei all = true, werden alle Layer entweder hinzugefügt oder entfernt
 */
Array.prototype.layerXChange = function(obj, all) {
    return this.compareXChange(obj, function(elemIn, elemComp) { return (elemIn.ol_uid === elemComp.ol_uid); }, all);
}

/**
 * fügt ein LayerElement hinzu (sofern nicht bereits vorhanden) (Vergleich aufgrund property ol_uid)
 * @param {*} obj Layer welche hinzugefügt werden sollen
 */
Array.prototype.pushLayer = function(obj) {
    if (obj !== null && obj.constructor === Array) {
        var ary = this;
        obj.forEach(function(elem) {
            ary = ary.pushOnce(elem);
        });
        return ary;
    }
    return this.pushOnce(obj, function(elemIn, elemComp) { return (elemIn.ol_uid === elemComp.ol_uid); });
}

/**
 * prüft ob alle Elemente die Bedingung erfüllen
 * @param {function} test Bedingung, welche erfüllt werden soll
 */
Array.prototype.all = function(test) {
    for (var i = 0; i < this.length; i++)
        if (!test(this[i])) return false;
    return true;
}

/**
 * prüft ob zumindest ein Element die Bedingung erfüllt
 * @param {function} test Bedingung, welche erfüllt werden soll
 */
Array.prototype.any = function(test) {
    for (var i = 0; i < this.length; i++)
        if (test(this[i])) return true;
    return false;
}

// Mathematical prototypes

/**
 * calculates the sum of all elements in the array (requires numerical array)
 * @returns {number} sum
 */
Array.prototype.sum = function() {
        return this.aggregate(0, (item, sum) => (sum + item));
    }
    /**
     * calculates the euclidian norm of the array
     * @returns {number} norm of array
     */
Array.prototype.norm = function() {
        return Math.sqrt(this.aggregate(0, (item, sum) => sum + (item * item)));
    }
    /**
     * calculates the difference between the two arrays
     * @param {number[]} array subtractor
     * @returns {number[]} difference array
     */
Array.prototype.difference = function(array) {
        if (this.length != array.length) throw new Error('different array lengths');
        var ary = this.slice();
        for (var i = 0; i < ary.length; i++)
            ary[i] -= array[i];
        return ary;
    }
    /**
     * calculates the distance (= norm of difference) between the two arrays
     * @param {number[]} array subtractor
     * @returns {number} distance
     */
Array.prototype.distance = function(array) {
    if (this.length != array.length) throw new Error('different array lengths');
    var sum = 0;
    for (var i = 0; i < this.length; i++)
        sum += (this[i] - array[i]) * (this[i] - array[i]);
    return Math.sqrt(sum);
}

/**
 * Zahl in Buchstaben umwandeln 0->A,...25->Z, 26->AA, 51->AZ
 *
 * @param {number} nr Zahl
 * @returns {string} Buchstabenkette
 */
Number.prototype.nrToChar = function() {
    var nr = this;
    var output = '';
    var first = true;
    do {
        var charNr = nr % 26;
        if (!first) charNr--;
        else first = false;
        nr = Math.floor(nr / 26);
        output = String.fromCharCode(65 + charNr) + output;
    } while (nr > 0);
    return output;
}

/**
 * formatiert das Datum,
 * verfügbare Variablen: yyyy (4-stelliges Jahr), yy (2-stelliges Jahr), MM (Monat)
 * dd (Tag), hh (Stunde), mm (Minute), ss (Sekunde)
 * @param {string} format Datumsformat
 */
Date.prototype.format = function(format) {
    format = format || "yyyy-MM-dd hh:mm:ss";
    var year = (this.getFullYear().toString()).substring(2);
    var month = (this.getMonth() + 1).toString().padStart(2, '0');
    var day = (this.getDate()).toString().padStart(2, '0');
    var hour = (this.getHours()).toString().padStart(2, '0');
    var min = (this.getMinutes()).toString().padStart(2, '0');
    var sec = (this.getSeconds()).toString().padStart(2, '0');

    return format.replace(/yyyy/g, this.getFullYear())
        .replace(/MM/g, month).replace(/dd/g, day)
        .replace(/yy/g, year).replace(/mm/g, min)
        .replace(/ss/g, sec).replace(/hh/g, hour);
}

/**
 * ermittelt die Position des Events (für Touch und Maus)
 */
Event.prototype.Position = function() {
    if (this.pageX)
        return { x: this.pageX, y: this.pageY };
    if (this.targetTouches && this.targetTouches.length > 0 && this.targetTouches[0].pageX)
        return {
            x: this.targetTouches[0].pageX,
            y: this.targetTouches[0].pageY
        };
    if (this.changedTouches && this.changedTouches.length > 0 && this.changedTouches[0].pageX)
        return {
            x: this.changedTouches[0].pageX,
            y: this.changedTouches[0].pageY
        };
    if (this.clientX)
        return { x: this.clientX, y: this.clientY };
}


text:
import React, { Component } from 'react';
import moment from 'moment';
import utils from '../utils/common';
import WAMP from '../services/wamp';

import processAPI from '../api/processes';

export default class ProcessDetail extends Component {
    constructor(...args) {
        super(...args);

        this.state = {
            label: "",
            isLoading: true,
            operations: [],
            lastCommandResult: null,
            currentOperation: null,
            customOperationParams: []
        }

        this.handlePerformOperation = (operation) => {
            return () => {
                console.info(`performing operation `, operation);
                this.hasAdditionalParams(operation) ?
                    this.showDialogForOperation(operation) :
                    processAPI.performOperation(operation);
            };
        };
    }

    componentDidMount() {
        this.loadDetail(this.props.uri);
    }
    componentWillUnmount() {
        this.unsubscribe();
    }

    performOperationWithParams() {
        const { currentOperation,customOperationParams } = this.state;
        customOperationParams.forEach((p) => {
            const value = this.refs[p.label].value;
            const param = currentOperation.body['dul:hasParameter'].forEach((c, i) => {
                if (c['sh:property']['sh:name']['@value'] === p.label) {
                    currentOperation.body['dul:hasParameter'][i]['dul:hasParameterDataValue'] = value;
                }
            });
        });
        processAPI.performOperation(currentOperation);
        $('#process-modal').modal('hide');
    }
    hasAdditionalParams(operation) {
        return operation.body['dul:hasParameter'];
    }
    showDialogForOperation(operation) {
        console.info("showing operation dialog");
        this.setState({
            customOperationParams: this.getCustomOperationParameters(operation),
            currentOperation: operation
        }, () => {
            $('#process-modal').modal({});
        });
    }
    getCustomOperationParameters(operation) {
        return operation.body['dul:hasParameter'].map((p) => {
            return {
                label: p['sh:property']['sh:name']['@value'],
                defaultValue: p['sh:property']['sh:defaultValue']
            }
        });
    }

    loadDetail(uri) {
        console.info('loading process detail');
        processAPI.loadProcessInformation(uri).then((process) => {
            this.setState({
                label: process.id,
                operations: process.operations,
                lastCommandResult: process.result,
                wamp: process.wamp
            }, () => {
                this.subscribe();
            });
        });
    }
    subscribe() {
        const { wamp } = this.state;
        if (wamp && wamp.topic && wamp.endpoint) {
            console.info("subscribing to process..");
            processAPI.subscribe(wamp.topic, (data) => {
                console.info(`received new command result! `, data);
                this.setState({
                    lastCommandResult: data
                });
            });
        } else {
            console.warn(`unable to subscribe to processes' command results: `, this.props.uri);
        }
    }
    unsubscribe() {
        console.info("unsubscribing from process..");
        this.props.wamp && WAMP.unsubscribe(this.props.wamp.topic);
    }

    renderModalContent() {
        const { customOperationParams } = this.state;
        if (!customOperationParams) {
            return null;
        }
        return (
             <form className="form-horizontal">
                {
                    customOperationParams.map((p, i) => {
                        return (

                                {p.label}
                                <input type="text" className="form-control" ref={p.label} defaultValue={p.defaultValue} />

                        );
                    })
                }
            </form>
        )
    }
    renderModal() {
        return (

                            <button type="button" className="close" data-dismiss="modal" aria-label="Close">×</button>

Perform operation with params

                            {this.renderModalContent()}

                            <button type="button" className="btn btn-primary modal-decline" data-dismiss="modal">Cancel</button>
                            <button type="button" className="btn btn-warning modal-accept" onClick={this.performOperationWithParams.bind(this)}>Perform</button>

        );
    }

    render() {
        const { label, lastCommandResult, operations } = this.state;
        const { baseColor } = this.props;
        return (

{label}

                {
                    operations.map((o) => {
                        const isLast = lastCommandResult && lastCommandResult.value === o.id;
                        return (
                            <button className={`btn operation-btn btn-raised ${isLast ? "active" : ""}`} style={{
                                backgroundColor: utils.lightenDarkenColor(baseColor, isLast ? -40 : 0)
                            }} onClick={this.handlePerformOperation(o)} key={o.id}>
                                {
                                    this.hasAdditionalParams(o) &&

                                }

{o.label}

                                {
                                    isLast &&

last command result at {moment(lastCommandResult.timestamp).format('HH:mm:ss')}

                                }
                            </button>
                        );
                    })
                }
                {this.renderModal()}

        )
    }
}


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

{% block title %}
    航班搜索
{% endblock %}

{% block header %}

{% endblock %}

{% block body %}
    <form class="form-horizontal" role="form" action="/plane/search/" method="get">

             起飞地

                <input type="text" class="form-control" id="starting" name="starting" placeholder="北京">

             目的地

                <input type="text" class="form-control" id="destination" name="destination" placeholder="火奴鲁鲁">

             出发时间

                <input type="date" class="form-control" id="departure" name="departure" placeholder="请选择出发时间">

                <button type="submit" class="btn btn-default">查询</button>

    </form>
{% endblock %}


text:
using System;
using Trybot.Fallback;
using Trybot.Utils;

namespace Trybot
{
    ///
    /// Fallback related <see cref="IBotPolicyBuilder"/> extensions.
    ///
    public static class FallbackBotPolicyBuilderExtensions
    {
        ///
        /// Adds a fallback bot to a <see cref="IBotPolicy"/> with the given configuration.
        ///
        /// <param name="builder">The policy builder.</param>
        /// <param name="configuratorAction">The configurator action.</param>
        /// <returns>The policy builder.</returns>
        /// <example>
        ///
        /// builder.Fallback(config => config
        ///     .WhenExceptionOccurs(exception => exception is HttpRequestException)
        ///     .OnFallback((exception, context) => onFallbackAction()))
        ///
        /// </example>
        public static IBotPolicyBuilder Fallback(this IBotPolicyBuilder builder, Action<FallbackConfiguration> configuratorAction)
        {
            Shield.EnsureNotNull(configuratorAction, nameof(configuratorAction));

            return builder.AddBot((innerBot, config) => new FallbackBot(innerBot, config), configuratorAction);
        }

        ///
        /// Adds a fallback bot to a <see cref="IBotPolicy"/> with the given configuration.
        ///
        /// <param name="builder">The policy builder.</param>
        /// <param name="configuration">The configuraton.</param>
        /// <returns>The policy builder.</returns>
        /// <example>
        ///
        /// builder.Fallback(new FallbackConfiguration()
        ///     .WhenExceptionOccurs(exception => exception is HttpRequestException)
        ///     .OnFallback((exception, context) => onFallbackAction()))
        ///
        /// </example>
        public static IBotPolicyBuilder Fallback(this IBotPolicyBuilder builder, FallbackConfiguration configuration)
        {
            Shield.EnsureNotNull(configuration, nameof(configuration));

            return builder.AddBot((innerBot, config) => new FallbackBot(innerBot, config), configuration);
        }

        ///
        /// Adds a fallback bot to a <see cref="IBotPolicy"/> with the given configuration.
        ///
        /// <param name="builder">The policy builder.</param>
        /// <param name="configuratorAction">The configurator action.</param>
        /// <returns>The policy builder.</returns>
        /// <example>
        ///
        /// builder.Fallback(config => config
        ///     .WhenExceptionOccurs(exception => exception is HttpRequestException)
        ///     .WhenResultIs(result => result != OperationResult.Ok)
        ///     .OnFallback((exception, context) => onFallbackAction()))
        ///
        /// </example>
        public static IBotPolicyBuilder<TResult> Fallback<TResult>(this IBotPolicyBuilder<TResult> builder, Action<FallbackConfiguration<TResult>> configuratorAction)
        {
            Shield.EnsureNotNull(configuratorAction, nameof(configuratorAction));

            return builder.AddBot((innerBot, config) => new FallbackBot<TResult>(innerBot, config), configuratorAction);
        }

        ///
        /// Adds a fallback bot to a <see cref="IBotPolicy"/> with the given configuration.
        ///
        /// <param name="builder">The policy builder.</param>
        /// <param name="configuration">The configuraton.</param>
        /// <returns>The policy builder.</returns>
        /// <example>
        ///
        /// builder.Fallback(new FallbackConfiguration()
        ///     .WhenExceptionOccurs(exception => exception is HttpRequestException)
        ///     .WhenResultIs(result => result != OperationResult.Ok)
        ///     .OnFallback((exception, context) => onFallbackAction()))
        ///
        /// </example>
        public static IBotPolicyBuilder<TResult> Fallback<TResult>(this IBotPolicyBuilder<TResult> builder, FallbackConfiguration<TResult> configuration)
        {
            Shield.EnsureNotNull(configuration, nameof(configuration));

            return builder.AddBot((innerBot, config) => new FallbackBot<TResult>(innerBot, config), configuration);
        }
    }
}


text:
package org.apache.nifi.processors.grpc;

import com.google.common.collect.Sets;

import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.AbstractSessionFactoryProcessor;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.ssl.RestrictedSSLContextService;
import org.apache.nifi.ssl.SSLContextService;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import io.grpc.CompressorRegistry;
import io.grpc.DecompressorRegistry;
import io.grpc.Server;
import io.grpc.ServerInterceptors;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NettyServerBuilder;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContextBuilder;

@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
@CapabilityDescription("Starts a gRPC server and listens on the given port to transform the incoming messages into FlowFiles." +
        " The message format is defined by the standard gRPC protobuf IDL provided by NiFi. gRPC isn't intended to carry large payloads," +
        " so this processor should be used only when FlowFile sizes are on the order of megabytes. The default maximum message size is 4MB.")
@Tags({"ingest", "grpc", "rpc", "listen"})
@WritesAttributes({
        @WritesAttribute(attribute = "listengrpc.remote.user.dn", description = "The DN of the user who sent the FlowFile to this NiFi"),
        @WritesAttribute(attribute = "listengrpc.remote.host", description = "The IP of the client who sent the FlowFile to this NiFi")
})
public class ListenGRPC extends AbstractSessionFactoryProcessor {
    public static final String REMOTE_USER_DN = "listengrpc.remote.user.dn";
    public static final String REMOTE_HOST = "listengrpc.remote.host";

    // properties
    public static final PropertyDescriptor PROP_SERVICE_PORT = new PropertyDescriptor.Builder()
            .name("Local gRPC service port")
            .displayName("Local gRPC Service Port")
            .description("The local port that the gRPC service will listen on.")
            .required(true)
            .addValidator(StandardValidators.PORT_VALIDATOR)
            .build();
    public static final PropertyDescriptor PROP_USE_SECURE = new PropertyDescriptor.Builder()
            .name("Use TLS")
            .displayName("Use TLS")
            .description("Whether or not to use TLS to send the contents of the gRPC messages.")
            .required(false)
            .defaultValue("false")
            .allowableValues("true", "false")
            .build();
    public static final PropertyDescriptor PROP_SSL_CONTEXT_SERVICE = new PropertyDescriptor.Builder()
            .name("SSL Context Service")
            .displayName("SSL Context Service")
            .description("The SSL Context Service used to provide client certificate information for TLS (https) connections.")
            .required(false)
            .identifiesControllerService(RestrictedSSLContextService.class)
            .build();
    public static final PropertyDescriptor PROP_FLOW_CONTROL_WINDOW = new PropertyDescriptor.Builder()
            .name("Flow Control Window")
            .displayName("Flow Control Window")
            .description("The initial HTTP/2 flow control window for both new streams and overall connection." +
                    " Flow-control schemes ensure that streams on the same connection do not destructively interfere with each other." +
                    " The default is 1MB.")
            .defaultValue("1MB")
            .required(false)
            .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
            .build();
    public static final PropertyDescriptor PROP_MAX_MESSAGE_SIZE = new PropertyDescriptor.Builder()
            .name("Max Message Size")
            .displayName("Maximum Message Size")
            .description("The maximum size of FlowFiles that this processor will allow to be received." +
                    " The default is 4MB. If FlowFiles exceed this size, you should consider using another transport mechanism" +
                    " as gRPC isn't designed for heavy payloads.")
            .defaultValue("4MB")
            .required(false)
            .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
            .build();
    public static final PropertyDescriptor PROP_AUTHORIZED_DN_PATTERN = new PropertyDescriptor.Builder()
            .name("Authorized DN Pattern")
            .displayName("Authorized DN Pattern")
            .description("A Regular Expression to apply against the Distinguished Name of incoming connections. If the Pattern does not match the DN, the connection will be refused.")
            .required(true)
            .defaultValue(".*")
            .addValidator(StandardValidators.REGULAR_EXPRESSION_VALIDATOR)
            .build();

    public static final List<PropertyDescriptor> PROPERTIES = Collections.unmodifiableList(Arrays.asList(
            PROP_SERVICE_PORT,
            PROP_USE_SECURE,
            PROP_SSL_CONTEXT_SERVICE,
            PROP_FLOW_CONTROL_WINDOW,
            PROP_AUTHORIZED_DN_PATTERN,
            PROP_MAX_MESSAGE_SIZE
    ));

    // relationships
    public static final Relationship REL_SUCCESS = new Relationship.Builder()
            .name("Success")
            .description("The FlowFile was received successfully.")
            .build();

    public static final Set<Relationship> RELATIONSHIPS = Collections.unmodifiableSet(Sets.newHashSet(Arrays.asList(
            REL_SUCCESS
    )));
    private final AtomicReference<ProcessSessionFactory> sessionFactoryReference = new AtomicReference<>();
    private volatile Server server = null;

    @Override
    public Set<Relationship> getRelationships() {
        return RELATIONSHIPS;
    }

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return PROPERTIES;
    }

    @OnScheduled
    public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException {
        final ComponentLog logger = getLogger();
        // gather configured properties
        final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger();
        final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
        final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B).intValue();
        final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
        final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
        final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);
        final Pattern authorizedDnPattern = Pattern.compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue());
        final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger());
        callInterceptor.enforceDNPattern(authorizedDnPattern);

        final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(),
                sessionFactoryReference,
                context);
        NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port)
                .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor))
                // default (de)compressor registries handle both plaintext and gzip compressed messages
                .compressorRegistry(CompressorRegistry.getDefaultInstance())
                .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
                .flowControlWindow(flowControlWindow)
                .maxMessageSize(maxMessageSize);

        if (useSecure && sslContext != null) {
            // construct key manager
            if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) {
                throw new IllegalStateException("SSL is enabled, but no keystore has been configured. You must configure a keystore.");
            }

            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm(),
                    sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());

            SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory);

            // if the trust store is configured, then client auth is required.
            if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
                final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(),
                        sslContext.getProvider());
                final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
                try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                    trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
                }
                trustManagerFactory.init(trustStore);
                sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
                sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
            } else {
                sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE);
            }
            sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
            serverBuilder = serverBuilder.sslContext(sslContextBuilder.build());
        }
        logger.info("Starting gRPC server on port: {}", new Object[]{port.toString()});
        this.server = serverBuilder.build().start();
    }

    @OnStopped
    public void stopServer(final ProcessContext context) {
        if (this.server != null) {
            try {
                this.server.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                getLogger().warn("Unable to cleanly shutdown embedded gRPC server due to {}", new Object[]{e});
                this.server = null;
            }
        }
    }

    @Override
    public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
        sessionFactoryReference.compareAndSet(null, sessionFactory);
        context.yield();
    }
}


text:
package com.snail.util;

public interface CacheCallBack {

    public void onFinish(String key);
}


text:
package neo4j.models.log;

import global.Global;
import neo4j.models.AbstractModel;
import neo4j.services.Neo4JServiceProvider;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.neo4j.annotation.NodeEntity;
import play.Logger;
import play.api.mvc.AnyContent;
import play.api.mvc.Request;

import java.util.LinkedList;

@NodeEntity
@TypeAlias("PerformanceLog")
public class PerformanceLog extends AbstractLog {

  public long duration;

  public static void create(long duration, LogCategory logCategory, String text) {
    create(duration, logCategory, null, text);
  }

  public static void create(long duration, LogCategory logCategory, Request<AnyContent> request) {
    create(duration, logCategory, request, null);
  }

  public static void create(long duration, LogCategory logCategory, Request<AnyContent> request, String text) {
    if (Global.isPerformanceLogging() == true) {
      PerformanceLog result = new PerformanceLog();
      result.duration = duration;
      abstractCreate(result, logCategory, LogLevel.INFO, request, new LinkedList<AbstractModel>());
      if (text != null) {
        result.httpUrl += " - " + text;
      }
      Neo4JServiceProvider.get().performanceLogRepository.save(result);
    } else {
      String requestString = logCategory.toString();
      if (request != null) {
        requestString += " " + request.uri();
      }
      if (text != null) {
        requestString += " - " + text;
      }
      Logger.info(requestString + " took " + duration + " ms");
    }
  }
}


text:
#include "dreal/util/signal_handler_guard.h"

#include <iostream>
#include <stdexcept>

namespace dreal {

using std::runtime_error;

SignalHandlerGuard::SignalHandlerGuard(const int sig, handler_t handler,
                                       volatile std::atomic_bool* flag)
    : sig_{sig}, flag_{flag}, old_action_{} {
  // Register the new handler and save the current one.
  sigaction_t new_action{};
  new_action.sa_handler = handler;
  sigemptyset(&new_action.sa_mask);
  new_action.sa_flags = SA_RESTART;
  const int result = sigaction(sig_, &new_action, &old_action_);
  if (result != 0) {
    throw runtime_error("Failed to register the signal handler.");
  }
}

SignalHandlerGuard::~SignalHandlerGuard() {
  // Restore the old signal handler
  sigaction(sig_, &old_action_, nullptr);
  if (*flag_) {
    *(flag_) = false;
  }
}
}  // namespace dreal