text:
package ru.job4j.ioc.carsale.service;

import ru.job4j.ioc.carsale.domain.CarBrand;

import java.util.List;

public interface CarBrandService {

    CarBrand getById(int id);

    List<CarBrand> getAll();

    void create(CarBrand carBrand);

    void update(CarBrand carBrand);

    void delete(CarBrand carBrand);
}

redpajama_set_name: RedPajamaGithub


text:
(function() {
    'use strict';
    angular
        .module('app.results')
        .run(appRun);

    appRun.$inject = ['routehelper', 'quiz.json']

    function appRun(routehelper, quiz) {
        routehelper.configureRoutes(getRoutes(quiz));
    }

    function getRoutes(quiz) {
        return [
            {
                url: '/results',
                config: {
                    templateUrl: 'partials/results.html',
                    controller: 'Results',
                    controllerAs: 'vm',
                    page: quiz['subQuizzes'].length+1
                }
            }
        ];
    }
})();


text:
package org.neo4j.driver.integration;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.neo4j.driver.Config.TrustStrategy.trustCustomCertificateSignedBy;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.neo4j.driver.Config;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Record;
import org.neo4j.driver.Session;
import org.neo4j.driver.exceptions.ServiceUnavailableException;
import org.neo4j.driver.internal.DriverFactory;
import org.neo4j.driver.internal.cluster.RoutingSettings;
import org.neo4j.driver.internal.retry.RetrySettings;
import org.neo4j.driver.internal.security.SecurityPlanImpl;
import org.neo4j.driver.internal.util.Clock;
import org.neo4j.driver.internal.util.DriverFactoryWithClock;
import org.neo4j.driver.internal.util.FakeClock;
import org.neo4j.driver.testutil.DatabaseExtension;
import org.neo4j.driver.testutil.ParallelizableIT;

/**
 * Mainly concerned about the connection pool - we want to make sure that bad connections are evacuated from the
 * pool properly if the server dies, or all connections are lost for some other reason.
 */
@ParallelizableIT
class ServerKilledIT {
    @RegisterExtension
    static final DatabaseExtension neo4j = new DatabaseExtension();

    private static Stream<Arguments> data() {
        return Stream.of(
                Arguments.of("plaintext", Config.builder().withoutEncryption()),
                Arguments.of(
                        "tls encrypted",
                        Config.builder()
                                .withEncryption()
                                .withTrustStrategy(trustCustomCertificateSignedBy(neo4j.tlsCertFile()))));
    }

    @ParameterizedTest
    @MethodSource("data")
    void shouldRecoverFromServerRestart(String name, Config.ConfigBuilder configBuilder) {
        // Given config with sessionLivenessCheckTimeout not set, i.e. turned off
        try (Driver driver = GraphDatabase.driver(neo4j.uri(), neo4j.authToken(), configBuilder.build())) {
            acquireAndReleaseConnections(4, driver);

            // When
            neo4j.stopProxy();
            neo4j.startProxy();

            // Then we should be able to start using sessions again, at most O(numSessions) session calls later
            int toleratedFailures = 4;
            for (int i = 0; i < 10; i++) {
                try (Session s = driver.session()) {
                    s.run("RETURN 'Hello, world!'");
                } catch (ServiceUnavailableException e) {
                    if (toleratedFailures-- == 0) {
                        fail("Expected (for now) at most four failures, one for each old connection, but now I've "
                                + "gotten " + "five: " + e.getMessage());
                    }
                }
            }
        }
    }

    @ParameterizedTest
    @MethodSource("data")
    void shouldDropBrokenOldSessions(String name, Config.ConfigBuilder configBuilder) {
        // config with set liveness check timeout
        int livenessCheckTimeoutMinutes = 10;
        configBuilder.withConnectionLivenessCheckTimeout(livenessCheckTimeoutMinutes, TimeUnit.MINUTES);

        FakeClock clock = new FakeClock();

        try (Driver driver = createDriver(clock, configBuilder.build())) {
            acquireAndReleaseConnections(5, driver);

            // restart database access to invalidate all idle connections in the pool
            neo4j.stopProxy();
            neo4j.startProxy();
            // move clock forward more than configured liveness check timeout
            clock.progress(TimeUnit.MINUTES.toMillis(livenessCheckTimeoutMinutes + 1));

            // now all idle connections should be considered too old and will be verified during acquisition
            // they will appear broken because of the database restart and new valid connection will be created
            try (Session session = driver.session()) {
                List<Record> records = session.run("RETURN 1").list();
                assertEquals(1, records.size());
                assertEquals(1, records.get(0).get(0).asInt());
            }
        }
    }

    private static void acquireAndReleaseConnections(int count, Driver driver) {
        if (count > 0) {
            Session session = driver.session();
            session.run("RETURN 1");
            acquireAndReleaseConnections(count - 1, driver);
            session.close();
        }
    }

    private Driver createDriver(Clock clock, Config config) {
        DriverFactory factory = new DriverFactoryWithClock(clock);
        RoutingSettings routingSettings = RoutingSettings.DEFAULT;
        RetrySettings retrySettings = RetrySettings.DEFAULT;
        return factory.newInstance(
                neo4j.uri(), neo4j.authToken(), routingSettings, retrySettings, config, SecurityPlanImpl.insecure());
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: MAGID
 * Date: 10/03/2016
 * Time: 16:19
 */

namespace Test\FrontBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class VoitureController extends Controller
{
    public function newVoitureAction(Request $request, $id)
    {
        /*
        $em = $this->getDoctrine()->getManager();
        $regions = $em->getRepository('TestFrontBundle:t_region')->findAll();
        */
        $formHandler = $this->get('voiture_handler');

        if($formHandler->process()){ echo 'validado'; }

        return $this->render('TestFrontBundle:Default:newVoiture.html.twig', array(
            'form2'    => $formHandler->getForm()->createView(),
            'id' => $id
            /*'regions' => $regions*/

        ));
    }
    function modelesByMarqueAction($idMarque)
    {
        $modeles = $this->getDoctrine()->getManager()->getRepository('TestFrontBundle:modelo_auto')->findByidMarca($idMarque);
        $modelesJSON = array();
        foreach($modeles as $modele){ $modelesJSON[]=array('id'=> $modele->getId(), 'modele' => $modele->getDescription()); }
        return new Response(json_encode($modelesJSON));
    }

}


text:
package com.streamsets.pipeline.stage.destination.hdfs.metadataexecutor;

import com.streamsets.pipeline.api.base.BaseEnumChooserValues;

public class TaskTypeChooserValues extends BaseEnumChooserValues<TaskType> {
  public TaskTypeChooserValues() {
    super(TaskType.class);
  }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.16-7-c-i-21
description: >
    Array.prototype.every - element to be retrieved is inherited
    accessor property without a get function on an Array-like object
---*/

        var accessed = false;

        function callbackfn(val, idx, obj) {
            accessed = true;
            return typeof val === "undefined";
        }

        var proto = {};
        Object.defineProperty(proto, "1", {
            set: function () { },
            configurable: true
        });

        var Con = function () { };
        Con.prototype = proto;

        var child = new Con();
        child.length = 2;

assert(Array.prototype.every.call(child, callbackfn), 'Array.prototype.every.call(child, callbackfn) !== true');
assert(accessed, 'accessed !== true');


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_UTIL_CONSTRAINTS_SAMETYPE_H_
#define _BLAZE_UTIL_CONSTRAINTS_SAMETYPE_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/util/typetraits/IsSame.h>

namespace blaze {

//=================================================================================================
//
//  MUST_BE_SAME_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are not the same (ignoring all cv-qualifiers of both data
// types), a compilation error is created. The following example illustrates the behavior of this
// constraint:

   \code
   BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( double, double );        // No compilation error
   BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( double, const double );  // No compilation error (only cv-qualifiers differ)
   BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( double, float );         // Compilation error, different data types!
   \endcode

// In case the cv-qualifiers should not be ignored (e.g. 'double' and 'const double' should be
// considered to be unequal), use the blaze::BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE constraint.
*/
#define BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE(A,B) \
   static_assert( ::blaze::IsSame<A,B>::value, "Non-matching types detected" )
//*************************************************************************************************

//=================================================================================================
//
//  MUST_NOT_BE_SAME_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are the same (ignoring all cv-qualifiers of both data
// types), a compilation error is created. The following example illustrates the behavior of
// this constraint:

   \code
   BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE( double, float );         // No compilation error, different data types
   BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE( double, const double );  // Compilation error (only cv-qualifiers differ)
   BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE( double, double );        // Compilation error, same data type!
   \endcode

// In case the cv-qualifiers should not be ignored (e.g. 'double' and 'const double' should
// be considered to be unequal), use the blaze::BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE
// constraint.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE(A,B) \
   static_assert( !::blaze::IsSame<A,B>::value, "Matching types detected" )
//*************************************************************************************************

//=================================================================================================
//
//  MUST_BE_STRICTLY_SAME_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are not the same, a compilation error is created. Note
// that this constraint even considers two types as unequal if the cv-qualifiers differ, e.g.

   \code
   BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE( double, double );        // No compilation error
   BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE( double, const double );  // Compilation error, different cv-qualifiers!
   BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE( double, float );         // Compilation error, different data types!
   \endcode

// In case the cv-qualifiers should be ignored (e.g. 'double' and 'const double' should be
// considered to be equal), use the blaze::BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE constraint.
*/
#define BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE(A,B) \
   static_assert( ::blaze::IsStrictlySame<A,B>::value, "Non-matching types detected" )
//*************************************************************************************************

//=================================================================================================
//
//  MUST_NOT_BE_STRICTLY_SAME_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are the same, a compilation error is created. Note that
// this constraint even considers two types as unequal if the cv-qualifiers differ, e.g.

   \code
   BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE( double, float );         // No compilation error, different data types
   BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE( double, const double );  // No compilation error, different cv-qualifiers!
   BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE( double, double );        // Compilation error, same data type!
   \endcode

// In case the cv-qualifiers should be ignored (e.g. 'double' and 'const double' should be
// considered to be equal), use the blaze::BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE constraint.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE(A,B) \
   static_assert( !::blaze::IsStrictlySame<A,B>::value, "Matching types detected" )
//*************************************************************************************************

} // namespace blaze

#endif


text:
var dgram = require('dgram');

/*
    FlightControlsSender
*/
var FlightControlsSender = function() {
    this._localPort = 8091;
    this._remotePort = 8081;
    this._remoteAddress = '127.0.0.1';

    this._udpSocket = dgram.createSocket('udp4');
    this._udpSocket.on(
        'listening',
        function() {
            var address = this._udpSocket.address();
            console.log('FlightControlsSender: opened UDP socket on ' + address.address + ':' + address.port);
        }.bind(this)
    );
    this._udpSocket.bind(this._localPort, '127.0.0.1');
};

FlightControlsSender.prototype.dispose = function() {
    console.log('FlightControlsSender.dispose: to do!');
    // CLOSE SOCKET!
};

function toBuffer(ab) {
    var buf = new Buffer(ab.byteLength);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
    }
    return buf;
}
FlightControlsSender.prototype.send = function(flightControls) {

    var uint8Array = new Uint8Array(512);
    var dataView = new DataView(uint8Array.buffer);
    var offset = 0;
    dataView.setFloat32(offset, flightControls.throttle, true);     // true for little endian!!!
    offset+=4;
    dataView.setFloat32(offset, flightControls.rudder, true);
    offset+=4;
    dataView.setFloat32(offset, flightControls.elevators, true);
    offset+=4;
    dataView.setFloat32(offset, flightControls.ailerons, true);
    offset+=4;

    dataView.setFloat32(offset, flightControls.pTerm, true);
    offset+=4;
    dataView.setFloat32(offset, flightControls.iTerm, true);
    offset+=4;
    dataView.setFloat32(offset, flightControls.dTerm, true);
    offset+=4;

    var buffer = toBuffer(uint8Array); //Buffer.from(uint8Array);       // There must be ways to avoid this copy here...
    this._udpSocket.send(buffer, 0, offset, this._remotePort, this._remoteAddress, function(err, bytes) {
        if (err) {
            console.warn('FlightControlsSender: error while sending data');
            // close?
        }
    });

    // console.log('FlightControlsSender: to ' + this._remoteAddress + ':' + this._remotePort + ": " +
    //    FlightControlsSender._uint8ArrayAsHexString(uint8Array, offset) + " - " + JSON.stringify(flightControls));
};

FlightControlsSender._uint8ArrayAsHexString = function( uint8Array, length ){
    if ( length===undefined ) {
        length = uint8Array.length;
    }
    var string = "";
    for ( var i=0; i<length; i++ )
    {
        string += uint8Array[i].toString(16);
    }
    return string;
};

exports.FlightControlsSender = FlightControlsSender;


text:
<?xml version='1.0' encoding='UTF-8'?>
<server xmlns="urn:jboss:domain:1.7">
  <extensions>
    <extension module="org.jboss.as.clustering.infinispan" />
    <extension module="org.jboss.as.connector" />
    <extension module="org.jboss.as.deployment-scanner" />
    <extension module="org.jboss.as.ee" />
    <extension module="org.jboss.as.ejb3" />
    <extension module="org.jboss.as.jaxrs" />
    <extension module="org.jboss.as.jdr" />
    <extension module="org.jboss.as.jmx" />
    <extension module="org.jboss.as.jpa" />
    <extension module="org.jboss.as.jsf" />
    <extension module="org.jboss.as.logging" />
    <extension module="org.jboss.as.mail" />
    <extension module="org.jboss.as.naming" />
    <extension module="org.jboss.as.pojo" />
    <extension module="org.jboss.as.remoting" />
    <extension module="org.jboss.as.sar" />
    <extension module="org.jboss.as.security" />
    <extension module="org.jboss.as.threads" />
    <extension module="org.jboss.as.transactions" />
    <extension module="org.jboss.as.web" />
    <extension module="org.jboss.as.webservices" />
    <extension module="org.jboss.as.weld" />
    <extension module="org.keycloak.keycloak-subsystem" />
  </extensions>
  <management>
    <security-realms>
      <security-realm name="ManagementRealm">
        <authentication>
          <local default-user="$local" skip-group-loading="true" />
          <properties path="mgmt-users.properties" relative-to="jboss.server.config.dir" />
        </authentication>
        <authorization map-groups-to-roles="false">
          <properties path="mgmt-groups.properties" relative-to="jboss.server.config.dir" />
        </authorization>
      </security-realm>
      <security-realm name="ApplicationRealm">
        <authentication>
          <local default-user="$local" allowed-users="*" skip-group-loading="true" />
          <properties path="application-users.properties" relative-to="jboss.server.config.dir" />
        </authentication>
        <authorization>
          <properties path="application-roles.properties" relative-to="jboss.server.config.dir" />
        </authorization>
      </security-realm>
    </security-realms>
    <audit-log>
      <formatters>
        <json-formatter name="json-formatter" />
      </formatters>
      <handlers>
        <file-handler name="file" formatter="json-formatter" relative-to="jboss.server.data.dir"
          path="audit-log.log" />
      </handlers>
      <logger log-boot="true" log-read-only="false" enabled="false">
        <handlers>
          <handler name="file" />
        </handlers>
      </logger>
    </audit-log>
    <management-interfaces>
      <native-interface security-realm="ManagementRealm">
        <socket-binding native="management-native" />
      </native-interface>
      <http-interface security-realm="ManagementRealm">
        <socket-binding http="management-http" />
      </http-interface>
    </management-interfaces>
    <access-control provider="simple">
      <role-mapping>
        <role name="SuperUser">
          <include>
            <user name="$local" />
          </include>
        </role>
      </role-mapping>
    </access-control>
  </management>
  <profile>
    <subsystem xmlns="urn:jboss:domain:logging:1.5">
      <console-handler name="CONSOLE">
        <level name="INFO" />
        <formatter>
          <named-formatter name="COLOR-PATTERN" />
        </formatter>
      </console-handler>
      <periodic-rotating-file-handler name="FILE" autoflush="true">
        <formatter>
          <named-formatter name="PATTERN" />
        </formatter>
        <file relative-to="jboss.server.log.dir" path="server.log" />
        <suffix value=".yyyy-MM-dd" />
        <append value="true" />
      </periodic-rotating-file-handler>
      <logger category="com.arjuna">
        <level name="WARN" />
      </logger>
      <logger category="org.apache.tomcat.util.modeler">
        <level name="WARN" />
      </logger>
      <logger category="org.jboss.as.config">
        <level name="DEBUG" />
      </logger>
      <logger category="sun.rmi">
        <level name="WARN" />
      </logger>
      <logger category="jacorb">
        <level name="WARN" />
      </logger>
      <logger category="jacorb.config">
        <level name="ERROR" />
      </logger>
      <root-logger>
        <level name="INFO" />
        <handlers>
          <handler name="CONSOLE" />
          <handler name="FILE" />
        </handlers>
      </root-logger>
      <formatter name="PATTERN">
        <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n" />
      </formatter>
      <formatter name="COLOR-PATTERN">
        <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n" />
      </formatter>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:datasources:1.2">
      <datasources>
        <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true"
          use-java-context="true">
          <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
          <driver>h2</driver>
          <security>
            <user-name>sa</user-name>
            <password>sa</password>
          </security>
        </datasource>
        <datasource jndi-name="java:jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true"
          use-java-context="true">
          <connection-url>jdbc:h2:${jboss.server.data.dir}/keycloak;AUTO_SERVER=TRUE</connection-url>
          <driver>h2</driver>
          <security>
            <user-name>sa</user-name>
            <password>sa</password>
          </security>
        </datasource>
        <drivers>
          <driver name="h2" module="com.h2database.h2">
            <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
          </driver>
        </drivers>
      </datasources>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1">
      <deployment-scanner path="deployments" relative-to="jboss.server.base.dir"
        scan-interval="5000" />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:ee:1.2">
      <spec-descriptor-property-replacement>false</spec-descriptor-property-replacement>
      <jboss-descriptor-property-replacement>true</jboss-descriptor-property-replacement>
      <annotation-property-replacement>false</annotation-property-replacement>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:ejb3:1.5">
      <session-bean>
        <stateless>
          <bean-instance-pool-ref pool-name="slsb-strict-max-pool" />
        </stateless>
        <stateful default-access-timeout="5000" cache-ref="simple" />
        <singleton default-access-timeout="5000" />
      </session-bean>
      <pools>
        <bean-instance-pools>
          <strict-max-pool name="slsb-strict-max-pool" max-pool-size="20"
            instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES" />
          <strict-max-pool name="mdb-strict-max-pool" max-pool-size="20"
            instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES" />
        </bean-instance-pools>
      </pools>
      <caches>
        <cache name="simple" aliases="NoPassivationCache" />
        <cache name="passivating" passivation-store-ref="file" aliases="SimpleStatefulCache" />
      </caches>
      <passivation-stores>
        <file-passivation-store name="file" />
      </passivation-stores>
      <async thread-pool-name="default" />
      <timer-service thread-pool-name="default" default-data-store="default-file-store">
        <data-stores>
          <file-data-store name="default-file-store" path="timer-service-data" relative-to="jboss.server.data.dir" />
        </data-stores>
      </timer-service>
      <remote connector-ref="remoting-connector" thread-pool-name="default" />
      <thread-pools>
        <thread-pool name="default">
          <max-threads count="10" />
          <keepalive-time time="100" unit="milliseconds" />
        </thread-pool>
      </thread-pools>
      <default-security-domain value="other" />
      <default-missing-method-permissions-deny-access value="true" />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:infinispan:1.5">
      <cache-container name="apiman-gateway" default-cache="registry" start="EAGER">
        <local-cache name="registry" batching="true">
          <file-store passivation="false" purge="false" />
        </local-cache>
        <local-cache name="rate-limiter" batching="true">
          <file-store passivation="false" purge="false" />
        </local-cache>
        <local-cache name="shared-state" batching="true">
          <file-store passivation="false" purge="false" />
        </local-cache>
        <local-cache name="caching" batching="true">
          <file-store passivation="false" purge="false" />
        </local-cache>
      </cache-container>
      <cache-container name="web" aliases="standard-session-cache" default-cache="local-web"
        module="org.jboss.as.clustering.web.infinispan">
        <local-cache name="local-web" batching="true">
          <file-store passivation="false" purge="false" />
        </local-cache>
      </cache-container>
      <cache-container name="hibernate" default-cache="local-query" module="org.jboss.as.jpa.hibernate:4">
        <local-cache name="entity">
          <transaction mode="NON_XA" />
          <eviction strategy="LRU" max-entries="10000" />
          <expiration max-idle="100000" />
        </local-cache>
        <local-cache name="local-query">
          <transaction mode="NONE" />
          <eviction strategy="LRU" max-entries="10000" />
          <expiration max-idle="100000" />
        </local-cache>
        <local-cache name="timestamps">
          <transaction mode="NONE" />
          <eviction strategy="NONE" />
        </local-cache>
      </cache-container>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:jaxrs:1.0" />
    <subsystem xmlns="urn:jboss:domain:jca:1.1">
      <archive-validation enabled="true" fail-on-error="true" fail-on-warn="false" />
      <bean-validation enabled="true" />
      <default-workmanager>
        <short-running-threads>
          <core-threads count="50" />
          <queue-length count="50" />
          <max-threads count="50" />
          <keepalive-time time="10" unit="seconds" />
        </short-running-threads>
        <long-running-threads>
          <core-threads count="50" />
          <queue-length count="50" />
          <max-threads count="50" />
          <keepalive-time time="10" unit="seconds" />
        </long-running-threads>
      </default-workmanager>
      <cached-connection-manager />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:jdr:1.0" />
    <subsystem xmlns="urn:jboss:domain:jmx:1.3">
      <expose-resolved-model />
      <expose-expression-model />
      <remoting-connector />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:jpa:1.1">
      <jpa default-datasource="" default-extended-persistence-inheritance="DEEP" />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:jsf:1.0" />
    <subsystem xmlns="urn:jboss:domain:mail:1.2">
      <mail-session name="default" jndi-name="java:jboss/mail/Default">
        <smtp-server outbound-socket-binding-ref="mail-smtp" />
      </mail-session>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:naming:1.4">
      <remote-naming />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:pojo:1.0" />
    <subsystem xmlns="urn:jboss:domain:remoting:1.2">
      <connector name="remoting-connector" socket-binding="remoting" security-realm="ApplicationRealm" />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:resource-adapters:1.1" />
    <subsystem xmlns="urn:jboss:domain:sar:1.0" />
    <subsystem xmlns="urn:jboss:domain:security:1.2">
      <security-domains>
        <security-domain name="other" cache-type="default">
          <authentication>
            <login-module code="Remoting" flag="optional">
              <module-option name="password-stacking" value="useFirstPass" />
            </login-module>
            <login-module code="RealmDirect" flag="required">
              <module-option name="password-stacking" value="useFirstPass" />
            </login-module>
          </authentication>
        </security-domain>
        <security-domain name="jboss-web-policy" cache-type="default">
          <authorization>
            <policy-module code="Delegating" flag="required" />
          </authorization>
        </security-domain>
        <security-domain name="jboss-ejb-policy" cache-type="default">
          <authorization>
            <policy-module code="Delegating" flag="required" />
          </authorization>
        </security-domain>
        <security-domain name="keycloak">
          <authentication>
            <login-module code="org.keycloak.adapters.jboss.KeycloakLoginModule" flag="required" />
          </authentication>
        </security-domain>
        <security-domain name="sp" cache-type="default">
          <authentication>
            <login-module code="org.picketlink.identity.federation.bindings.wildfly.SAML2LoginModule"
              flag="required" />
          </authentication>
        </security-domain>
      </security-domains>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:threads:1.1" />
    <subsystem xmlns="urn:jboss:domain:transactions:1.5">
      <core-environment>
        <process-id>
          <uuid />
        </process-id>
      </core-environment>
      <recovery-environment socket-binding="txn-recovery-environment"
        status-socket-binding="txn-status-manager" />
      <coordinator-environment default-timeout="300" />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:web:2.2" default-virtual-server="default-host" native="false">
      <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" />
      <connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">
        <ssl name="ssl" password="secret" protocol="TLSv1" key-alias="apimancert" certificate-key-file="${jboss.server.config.dir}/apiman.jks" />
      </connector>
      <virtual-server name="default-host" enable-welcome-root="true">
        <alias name="localhost" />
        <alias name="example.com" />
      </virtual-server>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:webservices:1.2">
      <modify-wsdl-address>true</modify-wsdl-address>
      <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>
      <endpoint-config name="Standard-Endpoint-Config" />
      <endpoint-config name="Recording-Endpoint-Config">
        <pre-handler-chain name="recording-handlers"
          protocol-bindings="##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM">
          <handler name="RecordingHandler" class="org.jboss.ws.common.invocation.RecordingServerHandler" />
        </pre-handler-chain>
      </endpoint-config>
      <client-config name="Standard-Client-Config" />
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:weld:1.0" />
    <subsystem xmlns="urn:jboss:domain:keycloak:1.0">
      <auth-server name="main-auth-server">
        <enabled>true</enabled>
        <web-context>auth</web-context>
      </auth-server>
      <kc:realm xmlns:kc="urn:jboss:domain:keycloak:1.0" name="apiman">
        <kc:realm-public-key>MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB
        </kc:realm-public-key>
        <kc:auth-server-url>/auth</kc:auth-server-url>
        <kc:ssl-required>none</kc:ssl-required>
        <kc:enable-cors>false</kc:enable-cors>
        <kc:principal-attribute>preferred_username</kc:principal-attribute>
      </kc:realm>
      <kc:secure-deployment xmlns:kc="urn:jboss:domain:keycloak:1.0" name="apiman.war">
        <kc:realm>apiman</kc:realm>
        <kc:resource>apiman</kc:resource>
        <kc:credential name="secret">
          password
        </kc:credential>
        <kc:enable-basic-auth>true</kc:enable-basic-auth>
        <kc:disable-trust-manager>true</kc:disable-trust-manager>
      </kc:secure-deployment>
      <kc:secure-deployment xmlns:kc="urn:jboss:domain:keycloak:1.0" name="apimanui.war">
        <kc:realm>apiman</kc:realm>
        <kc:resource>apimanui</kc:resource>
        <kc:credential name="secret">
          password
        </kc:credential>
        <kc:disable-trust-manager>true</kc:disable-trust-manager>
      </kc:secure-deployment>
      <kc:secure-deployment xmlns:kc="urn:jboss:domain:keycloak:1.0" name="apiman-gateway-api.war">
        <kc:realm>apiman</kc:realm>
        <kc:resource>apiman-gateway-api</kc:resource>
        <kc:credential name="secret">
          password
        </kc:credential>
        <kc:enable-basic-auth>true</kc:enable-basic-auth>
        <kc:disable-trust-manager>true</kc:disable-trust-manager>
      </kc:secure-deployment>
    </subsystem>
  </profile>
  <interfaces>
    <interface name="management">
      <inet-address value="${jboss.bind.address.management:127.0.0.1}" />
    </interface>
    <interface name="public">
      <inet-address value="${jboss.bind.address:127.0.0.1}" />
    </interface>
    <!-- TODO - only show this if the jacorb subsystem is added -->
    <interface name="unsecure">
      <!-- ~ Used for IIOP sockets in the standard configuration. ~ To secure JacORB you need to setup SSL -->
      <inet-address value="${jboss.bind.address.unsecure:127.0.0.1}" />
    </interface>
  </interfaces>
  <socket-binding-group name="standard-sockets" default-interface="public"
    port-offset="${jboss.socket.binding.port-offset:0}">
    <socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}" />
    <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}" />
    <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9443}" />
    <socket-binding name="ajp" port="8009" />
    <socket-binding name="http" port="8080" />
    <socket-binding name="https" port="8443" />
    <socket-binding name="remoting" port="4447" />
    <socket-binding name="txn-recovery-environment" port="4712" />
    <socket-binding name="txn-status-manager" port="4713" />
    <outbound-socket-binding name="mail-smtp">
      <remote-destination host="localhost" port="25" />
    </outbound-socket-binding>
  </socket-binding-group>
</server>


text:
<?php

namespace WebinoAppLib\Event;

use WebinoAppLib\Application\AbstractApplication;
use WebinoAppLib\Application\ConfiguredApplicationInterface;
use WebinoBaseLib\Util\ToString;
use Zend\Http\AbstractMessage;
use Zend\Stdlib\RequestInterface;
use Zend\Stdlib\ResponseInterface;

/**
 * Class DispatchEvent
 */
class DispatchEvent extends AppEvent implements
    DispatchEventInterface
{
    /**
     * @param ConfiguredApplicationInterface|AbstractApplication $app
     */
    public function __construct(ConfiguredApplicationInterface $app)
    {
        parent::__construct(AppEvent::DISPATCH);
        $this->setApp($app);
    }

    /**
     * @return RequestInterface
     */
    public function getRequest()
    {
        return $this->getEventParam($this::REQUEST);
    }

    /**
     * @param RequestInterface $request
     * @return $this
     */
    public function setRequest(RequestInterface $request)
    {
        $this->setEventParam($this::REQUEST, $request);
        return $this;
    }

    /**
     * @return ResponseInterface|AbstractMessage
     */
    public function getResponse()
    {
        return $this->getEventParam($this::RESPONSE);
    }

    /**
     * Set response
     *
     * It sets response content when response is a string.
     * It joins values to a string when response is an array.
     * It converts to string when response is an object.
     * It sets response object when response is an interface.
     *
     * @param string|array|ResponseInterface $response
     * @return $this
     */
    public function setResponse($response)
    {
        if ($response instanceof ResponseInterface) {
            $this->setEventParam($this::RESPONSE, $response);
            return $this;
        }

        $_response = $this->getResponse();
        $_response->setContent($_response->getContent() . $this->normalizeResponseContent($response));
        return $this;
    }

    /**
     * Reset response
     *
     * @param string|array|ResponseInterface $response
     * @return $this
     */
    public function resetResponse($response = null)
    {
        if ($response instanceof ResponseInterface) {
            // TODO implement??
            return $this;
        }
        $this->getResponse()->setContent($this->normalizeResponseContent($response));
        return $this;
    }

    /**
     * @param string|array $content
     * @return string
     */
    private function normalizeResponseContent($content)
    {
        return ToString::value($content);
    }
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\Subresource\Shared;

use Oro\Bundle\ApiBundle\Metadata\EntityMetadata;
use Oro\Bundle\ApiBundle\Processor\Subresource\Shared\SetHttpAllowHeaderForSubresource;
use Oro\Bundle\ApiBundle\Provider\ResourcesProvider;
use Oro\Bundle\ApiBundle\Provider\SubresourcesProvider;
use Oro\Bundle\ApiBundle\Request\ApiAction;
use Oro\Bundle\ApiBundle\Request\ApiSubresource;
use Oro\Bundle\ApiBundle\Tests\Unit\Processor\Subresource\GetSubresourceProcessorTestCase;

class SetHttpAllowHeaderForSubresourceTest extends GetSubresourceProcessorTestCase
{
    /** @var \PHPUnit\Framework\MockObject\MockObject|ResourcesProvider */
    private $resourcesProvider;

    /** @var \PHPUnit\Framework\MockObject\MockObject|SubresourcesProvider */
    private $subresourcesProvider;

    /** @var SetHttpAllowHeaderForSubresource */
    private $processor;

    protected function setUp()
    {
        parent::setUp();

        $this->resourcesProvider = $this->createMock(ResourcesProvider::class);
        $this->subresourcesProvider = $this->createMock(SubresourcesProvider::class);

        $this->processor = new SetHttpAllowHeaderForSubresource(
            $this->resourcesProvider,
            $this->subresourcesProvider
        );
    }

    public function testProcessWhenResponseStatusCodeIsNot405()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $this->resourcesProvider->expects(self::never())
            ->method('getResourceExcludeActions');
        $this->subresourcesProvider->expects(self::never())
            ->method('getSubresource');

        $this->context->setResponseStatusCode(404);
        $this->context->setParentClassName('Test\Class');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertFalse($this->context->getResponseHeaders()->has('Allow'));
    }

    public function testProcessWhenAllowResponseHeaderAlreadySet()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $this->resourcesProvider->expects(self::never())
            ->method('getResourceExcludeActions');
        $this->subresourcesProvider->expects(self::never())
            ->method('getSubresource');

        $this->context->setResponseStatusCode(405);
        $this->context->getResponseHeaders()->set('Allow', 'GET');
        $this->context->setParentClassName('Test\Class');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals('GET', $this->context->getResponseHeaders()->get('Allow'));
    }

    public function testProcessWhenAllActionsDisabled()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $this->resourcesProvider->expects(self::once())
            ->method('getResourceExcludeActions')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn([
                ApiAction::GET_SUBRESOURCE,
                ApiAction::UPDATE_SUBRESOURCE,
                ApiAction::ADD_SUBRESOURCE,
                ApiAction::DELETE_SUBRESOURCE
            ]);
        $this->subresourcesProvider->expects(self::once())
            ->method('getSubresource')
            ->with('Test\Class', 'testAssociation', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn(null);

        $this->context->setResponseStatusCode(405);
        $this->context->setParentClassName('Test\Class');
        $this->context->setIsCollection(false);
        $this->context->setAssociationName('testAssociation');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals(404, $this->context->getResponseStatusCode());
        self::assertFalse($this->context->getResponseHeaders()->has('Allow'));
    }

    public function testProcessWhenAllActionsEnabled()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $subresource = new ApiSubresource();

        $this->resourcesProvider->expects(self::once())
            ->method('getResourceExcludeActions')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn([]);
        $this->subresourcesProvider->expects(self::once())
            ->method('getSubresource')
            ->with('Test\Class', 'testAssociation', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn($subresource);

        $this->context->setResponseStatusCode(405);
        $this->context->setParentClassName('Test\Class');
        $this->context->setIsCollection(false);
        $this->context->setAssociationName('testAssociation');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals('OPTIONS, GET, PATCH, POST, DELETE', $this->context->getResponseHeaders()->get('Allow'));
    }

    public function testProcessWhenOnlyGetSubresourceEnabled()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $this->resourcesProvider->expects(self::once())
            ->method('getResourceExcludeActions')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn([
                ApiAction::UPDATE_SUBRESOURCE,
                ApiAction::ADD_SUBRESOURCE,
                ApiAction::DELETE_SUBRESOURCE
            ]);
        $this->subresourcesProvider->expects(self::once())
            ->method('getSubresource')
            ->with('Test\Class', 'testAssociation', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn(null);

        $this->context->setResponseStatusCode(405);
        $this->context->setParentClassName('Test\Class');
        $this->context->setIsCollection(false);
        $this->context->setAssociationName('testAssociation');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals('OPTIONS, GET', $this->context->getResponseHeaders()->get('Allow'));
    }

    public function testProcessWhenOnlyUpdateSubresourceEnabled()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $this->resourcesProvider->expects(self::once())
            ->method('getResourceExcludeActions')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn([
                ApiAction::GET_SUBRESOURCE,
                ApiAction::ADD_SUBRESOURCE,
                ApiAction::DELETE_SUBRESOURCE
            ]);
        $this->subresourcesProvider->expects(self::once())
            ->method('getSubresource')
            ->with('Test\Class', 'testAssociation', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn(null);

        $this->context->setResponseStatusCode(405);
        $this->context->setParentClassName('Test\Class');
        $this->context->setIsCollection(false);
        $this->context->setAssociationName('testAssociation');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals('OPTIONS, PATCH', $this->context->getResponseHeaders()->get('Allow'));
    }

    public function testProcessWhenEntityDoesNotHaveIdentifierFields()
    {
        $metadata = new EntityMetadata();

        $this->resourcesProvider->expects(self::once())
            ->method('getResourceExcludeActions')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn([
                ApiAction::UPDATE_SUBRESOURCE,
                ApiAction::ADD_SUBRESOURCE,
                ApiAction::DELETE_SUBRESOURCE
            ]);
        $this->subresourcesProvider->expects(self::once())
            ->method('getSubresource')
            ->with('Test\Class', 'testAssociation', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn(null);

        $this->context->setResponseStatusCode(405);
        $this->context->setParentClassName('Test\Class');
        $this->context->setIsCollection(false);
        $this->context->setAssociationName('testAssociation');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals('OPTIONS, GET', $this->context->getResponseHeaders()->get('Allow'));
    }

    public function testProcessWhenActionDisabledForParticularAssociation()
    {
        $metadata = new EntityMetadata();
        $metadata->setIdentifierFieldNames(['id']);

        $subresource = new ApiSubresource();
        $subresource->setExcludedActions([ApiAction::UPDATE_SUBRESOURCE]);

        $this->resourcesProvider->expects(self::once())
            ->method('getResourceExcludeActions')
            ->with('Test\Class', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn([ApiAction::ADD_SUBRESOURCE, ApiAction::DELETE_SUBRESOURCE]);
        $this->subresourcesProvider->expects(self::once())
            ->method('getSubresource')
            ->with('Test\Class', 'testAssociation', $this->context->getVersion(), $this->context->getRequestType())
            ->willReturn($subresource);

        $this->context->setResponseStatusCode(405);
        $this->context->setParentClassName('Test\Class');
        $this->context->setIsCollection(false);
        $this->context->setAssociationName('testAssociation');
        $this->context->setMetadata($metadata);
        $this->processor->process($this->context);

        self::assertEquals('OPTIONS, GET', $this->context->getResponseHeaders()->get('Allow'));
    }
}


text:
package com.mood.jenaPlus;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.EditText;

import com.robotium.solo.Solo;

/**
 * Created by carrotji on 2017-03-13.
 */

public class EditMoodActivityTest extends ActivityInstrumentationTestCase2 {

    public Solo solo;

    public EditMoodActivityTest() {
        super(com.mood.jenaPlus.WelcomeActivity.class);
    }

    public void testStart() throws Exception {
        Activity activity = getActivity();
    }

    public void setUp() throws Exception{
        solo = new Solo(getInstrumentation(),getActivity());
    }

    public void testEditMood() {
        solo.assertCurrentActivity("Wrong Activity", WelcomeActivity.class);
        solo.clearEditText((EditText) solo.getView(R.id.loginUserName));
        solo.enterText((EditText) solo.getView(R.id.loginUserName), "josefina");
        solo.clickOnButton("Log in");
        solo.assertCurrentActivity("Wrong Activity", MoodPlusActivity.class);

        solo.clickLongInList(0);
        solo.clickOnText("Edit");
        solo.assertCurrentActivity("Wrong Activity", EditMoodActivity.class);
        solo.clearEditText((EditText) solo.getView(R.id.message));
        solo.enterText((EditText) solo.getView(R.id.message),"Test message");

        solo.waitForActivity("EditMoodActivity");
        solo.clickOnText("Save");
        solo.waitForActivity("MoodPlusActivity");
        solo.assertCurrentActivity("Wrong Activity", MoodPlusActivity.class);

    }

    @Override
    public void tearDown() throws Exception{
        solo.finishOpenedActivities();
    }

}


text:
    copyright
2017 Copyright {{ site.name }} | All rights reserved


text:
<?php foreach($model->galleries as $gallery): ?>

    <?php if($gallery->title): ?>

<?php echo e($gallery->title); ?>

    <?php endif; ?>
    <?php echo $gallery->present()->body; ?>

    <?php echo $__env->make('galleries::public._thumbs', ['model' => $gallery], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>

<?php endforeach; ?>


text:
namespace boost_no_cv_specializations = empty_boost;
#endif

int main( int, char *[] )
{
   return boost_no_cv_specializations::test();
}


text:
import Ember from 'ember';

const isNone = Ember.isNone;
const get = Ember.get;
const set = Ember.set;

export default function setp(target, path, value) {
  let segments = path.split('.');
  segments.pop(); // Don't see the actual value, use Ember.set for that
  segments.forEach((segment, i) => {
    let nextSegment = segments[i + 1];
    let currentPath = segments.slice(0, i + 1).join('.');
    if (isNone(get(target, currentPath))) {
      if (isNaN(parseInt(nextSegment, 10))) {
        set(target, currentPath, {});
      } else {
        set(target, currentPath, []);
      }
    }
  });
  return set(target, path, value);
}


text:
package com.mtech.easyexchange.ordersolver.consumer;

import com.mtech.easyexchange.SessionFactoryProvider;
import com.mtech.easyexchange.manager.factory.OrderManagerFactory;
import com.mtech.easyexchange.manager.order.IOrderManager;
import com.mtech.easyexchange.ordersolver.OrderMessageHolder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class OrderMessageConsumer implements MessageListener {

    protected OrderMessageHolder holder;

    protected OrderMessageListener listener;

    public OrderMessageConsumer(OrderMessageHolder holder)
    {
        this.holder = holder;
    }

    @Override
    public void onMessage(Message message) {

        if(!isListenerInitialized()) {
            initializeListener();
        }

        listener.process(message);

    }

    protected Boolean isListenerInitialized() {
        return listener != null;
    }

    protected void initializeListener() {
        SessionFactoryProvider.openSession();
        IOrderManager orderManager = OrderManagerFactory.createOrderManager();

        listener = new OrderMessageListener(holder, orderManager);
    }
}


text:
package jhi.buntata.data;

import java.sql.*;
import java.util.*;

import jhi.buntata.resource.*;
import jhi.database.server.*;
import jhi.database.server.parser.*;
import jhi.database.server.query.*;
import jhi.database.shared.exception.*;
import jhi.database.shared.util.*;

/**
 * @author Sebastian Raubach
 */
public class AttributeValueDAO extends WriterDAO<BuntataAttributeValue>
{
	public List<BuntataAttributeValue> getAllForNode(long id)
	{
		try
		{
			return new DatabaseObjectQuery<BuntataAttributeValue>("SELECT * FROM attributevalues WHERE node_id = ?")
				.setLong(id)
				.run()
				.getObjects(Parser.Inst.get(), true);
		}
		catch (DatabaseException e)
		{
			e.printStackTrace();
		}

		return new ArrayList<>();
	}

	@Override
	protected DatabaseObjectWriter<BuntataAttributeValue> getWriter()
	{
		return Writer.Inst.get();
	}

	public BuntataAttributeValue getFor(Long nodeId, Long attributeId)
	{
		try
		{
			return new DatabaseObjectQuery<BuntataAttributeValue>("SELECT * FROM attributevalues WHERE node_id = ? AND attribute_id = ?")
				.setLong(nodeId)
				.setLong(attributeId)
				.run()
				.getObject(Parser.Inst.get());
		}
		catch (DatabaseException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public BuntataAttributeValue get(Long id)
	{
		try
		{
			return new DatabaseObjectQuery<BuntataAttributeValue>("SELECT * FROM attributevalues WHERE id = ?")
				.setLong(id)
				.run()
				.getObject(Parser.Inst.get());
		}
		catch (DatabaseException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public boolean delete(Long id)
	{
		try
		{
			new ValueQuery("DELETE FROM attributevalues WHERE id = ?")
				.setLong(id)
				.execute();
			return true;
		}
		catch (DatabaseException e)
		{
			e.printStackTrace();
			return false;
		}
	}

	public void update(BuntataAttributeValue av)
	{
		try
		{
			new ValueQuery("UPDATE `attributevalues` SET value = ? WHERE node_id = ? AND attribute_id = ?")
				.setString(av.getValue())
				.setLong(av.getNodeId())
				.setLong(av.getAttributeId())
				.execute();
		}
		catch (DatabaseException e)
		{
			e.printStackTrace();
		}
	}

	public static class Writer extends DatabaseObjectWriter<BuntataAttributeValue>
	{
		public static final class Inst
		{
			/**
			 * {@link InstanceHolder} is loaded on the first execution of {@link #get()} or the first access to {@link InstanceHolder#INSTANCE}, not
			 * before.
			 *

			 * This solution (Initialization-on-demand holder
			 * idiom) is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
			 *
			 * @author Sebastian Raubach
			 */
			private static final class InstanceHolder
			{
				private static final Writer INSTANCE = new Writer();
			}

			public static Writer get()
			{
				return InstanceHolder.INSTANCE;
			}
		}

		@Override
		public DatabaseStatement getStatement(Database database)
			throws DatabaseException
		{
			return database.prepareStatement("INSERT INTO `attributevalues` (`id`, `node_id`, `attribute_id`, `value`, `created_on`, `updated_on`) VALUES (?, ?, ?, ?, ?, ?)");
		}

		@Override
		public void write(BuntataAttributeValue object, DatabaseStatement stmt)
			throws DatabaseException
		{
			int i = 1;
			stmt.setLong(i++, object.getId());
			stmt.setLong(i++, object.getNodeId());
			stmt.setLong(i++, object.getAttributeId());
			stmt.setString(i++, object.getValue());
			if (object.getCreatedOn() != null)
				setDate(i++, object.getCreatedOn(), stmt);
			else
				stmt.setNull(i++, Types.DATE);
			if (object.getUpdatedOn() != null)
				setDate(i++, object.getUpdatedOn(), stmt);
			else
				stmt.setNull(i++, Types.TIMESTAMP);

			List<Long> ids = stmt.execute();

			if (ids.size() > 0)
				object.setId(ids.get(0));
		}

		@Override
		public void writeBatched(BuntataAttributeValue object, DatabaseStatement stmt)
			throws DatabaseException
		{
			int i = 1;
			stmt.setLong(i++, object.getId());
			stmt.setLong(i++, object.getNodeId());
			stmt.setLong(i++, object.getAttributeId());
			stmt.setString(i++, object.getValue());
			if (object.getCreatedOn() != null)
				setDate(i++, object.getCreatedOn(), stmt);
			else
				stmt.setNull(i++, Types.DATE);
			if (object.getUpdatedOn() != null)
				setDate(i++, object.getUpdatedOn(), stmt);
			else
				stmt.setNull(i++, Types.TIMESTAMP);

			stmt.addBatch();
		}
	}

	public static class Parser extends DatabaseObjectParser<BuntataAttributeValue>
	{
		public static final class Inst
		{
			/**
			 * {@link InstanceHolder} is loaded on the first execution of {@link Inst#get()} or the first access to {@link InstanceHolder#INSTANCE},
			 * not before.
			 *

			 * This solution (Initialization-on-demand holder
			 * idiom) is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
			 *
			 * @author Sebastian Raubach
			 */
			private static final class InstanceHolder
			{
				private static final Parser INSTANCE = new Parser();
			}

			public static Parser get()
			{
				return InstanceHolder.INSTANCE;
			}
		}

		private AttributeDAO dao = new AttributeDAO();

		@Override
		public BuntataAttributeValue parse(DatabaseResult rs, boolean includeForeign)
			throws DatabaseException
		{
			BuntataAttributeValue value = new BuntataAttributeValue(rs.getLong(DatabaseObject.ID), rs.getTimestamp(DatabaseObject.CREATED_ON), rs.getTimestamp(DatabaseObject.UPDATED_ON))
				.setNodeId(rs.getLong(BuntataAttributeValue.FIELD_NODE_ID))
				.setAttributeId(rs.getLong(BuntataAttributeValue.FIELD_ATTRIBUTE_ID))
				.setValue(rs.getString(BuntataAttributeValue.FIELD_VALUE));

			if (includeForeign)
				value.setAttribute(dao.get(rs.getLong(BuntataAttributeValue.FIELD_ATTRIBUTE_ID)));

			return value;
		}
	}
}


text:
module ConsoleCandy
  # Your code goes here...

  module ActiveRecord

    def self.included(base)
      base.send(:extend,ClassMethods)
      base.send(:include,InstanceMethods)
    end

    module ClassMethods

      def add_convenience_find_ids(*args)
        @convenience_ids = args
      end

      # A shortcut for find
      # Pass it either an id, a range, or a conditions string
      # Note that this returns nil if the items w/ indicated ID's are not there
      def [](*args)
        convenience_ids = [:id] + Array(@convenience_ids)
        if args.length > 1
          # Assume it's a bunch of IDS
          if @convenience_ids.blank?
            find(args)
          else
            conditions = [convenience_ids.map { |att| "#{att} IN (?)"}.join(" OR ")] + [args]*convenience_ids.length
            find(:all,:conditions => conditions )
          end
        else
          arg = args.first
          if Range === arg
            # Note that this returns the objects based upon :offset, not the key, so User[0..3] returns the
            # the first 4 objects in the User table, not the users with ids 0 through 3
            if arg.first > 0
              self.all(:offset => arg.first, :limit => arg.to_a.length)
            else
              self.all(:offset => arg.last.abs-1, :limit => arg.to_a.length,:order => 'id DESC').reverse
            end
          else
            if String === arg && (arg.first == '%' || arg.last == '%')
              conditions = [convenience_ids.map { |att| %{#{att} LIKE ?} }.join(" OR ")] + [arg]*convenience_ids.length
            else
              conditions = [convenience_ids.map { |att| "#{att} = ?" }.join(" OR ")] + [arg]*convenience_ids.length
            end

            # We generally return only one, but if we have several matches, then return them all
            f = find(:all,:conditions => conditions)
            f.length == 1 ? f.first : f
          end
        end
      end
    end

    module InstanceMethods
      # This method presents an easy way to display ActiveRecord objects in a readable format
      # for the console or embedding into an email
      def pps
        order = [:special,:integer,:float,:boolean,:datetime,:date,:string,:text]
        sorted = {:special => []}
        %w(id type title name status kind).each { |s|
          sorted[:special] << s if attribute_names.include?(s)
        }
        (attribute_names-sorted[:special]).inject(sorted) { |h,att_name|
          (h[column_for_attribute(att_name).type] ||= []) << att_name
          h
        }
        # find the max name length
        mnl = attribute_names.map { |n| n.length }.max + 1
        order.inject([]) { |arr,type|
          arr << (sorted[type] || []).map { |att_name| sprintf "%-#{mnl}s: %s", att_name, read_attribute(att_name).to_s.wrap(75-mnl).gsub("\n","\n#{' '*(mnl+2)}") }
          }.flatten.compact.join("\n")
      end

      def pp
        puts pps
      end

    end
  end
end


text:
package jp.co.opentone.bsol.linkbinder.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.dbunit.dataset.ITable;
import org.junit.Test;

import jp.co.opentone.bsol.framework.core.dao.KeyDuplicateException;
import jp.co.opentone.bsol.framework.test.AbstractDaoTestCase;
import jp.co.opentone.bsol.linkbinder.dto.User;
import jp.co.opentone.bsol.linkbinder.dto.WorkflowTemplate;
import jp.co.opentone.bsol.linkbinder.dto.code.WorkflowType;

/**
 * WorkflowTemplateDaoImplのテストケース.
 * @author opentone
 */
public class WorkflowTemplateDaoImplTest extends AbstractDaoTestCase {

    /**
     * テスト対象.
     */
    @Resource
    private WorkflowTemplateDaoImpl dao;

    /**
     * {@link WorkflowTemplateDaoImpl#findByWorkflowTemplateUserId}のテストケース.
     * @throws Exception
     */
    @Test
    public void testFindByWorkflowTemplateUserId() throws Exception {
        // テスト実行
        List<WorkflowTemplate> actual = dao.findByWorkflowTemplateUserId(1L);

        // 取得したオブジェクトと、Excelファイルに定義済の期待値を比較する
        assertNotNull(actual);
        assertDataSetEquals(newDataSet("WorkflowTemplateDaoImplTest_testFindByWorkflowTemplateUserId_expected.xls"),
            actual);
    }

    /**
     * {@link WorkflowTemplateDaoImpl#findByWorkflowTemplateUserId}のテストケース.
     * データが取得できない
     * @throws Exception
     */
    @Test
    public void testFindByWorkflowTemplateUserIdNoData() throws Exception {
        // テスト実行
        List<WorkflowTemplate> actual = dao.findByWorkflowTemplateUserId(999L);

        // 取得したオブジェクトと、Excelファイルに定義済の期待値を比較する
        assertNotNull(actual);
        assertTrue(actual.isEmpty());
    }

    /**
     * {@link WorkflowTemplateDaoImpl#create}のテストケース.
     * @throws Exception
     */
    @Test
    public void testCreate() throws Exception {
        WorkflowTemplate entity = new WorkflowTemplate();
        entity.setWorkflowTemplateUserId(1L);

        User user = new User();
        user.setEmpNo("ZZA10");
        user.setNameE("John Winston Ono Lennon");

        entity.setUser(user);
        entity.setWorkflowType(WorkflowType.CHECKER);
        entity.setWorkflowNo(9L);

        User loginUser = new User();
        loginUser.setEmpNo("ZZA05");
        loginUser.setNameE("Keiichi Ogiwara");
        entity.setCreatedBy(loginUser);
        entity.setUpdatedBy(loginUser);

        Long id = null;
        // テスト実行
        while(true) {
            try {
                id = dao.create(entity);
                break;
            } catch (KeyDuplicateException e) {
                continue;
            }
        }
        assertNotNull(id);

        // 登録したデータを取得する
        String sql = "select * from workflow_template where id = " + id;
        ITable actual = getConnection().createQueryTable("actual", sql);

        assertEquals(id.toString(), actual.getValue(0, "id").toString());
        assertEquals(entity.getWorkflowTemplateUserId().toString(), actual.getValue(0, "workflow_template_user_id").toString());
        assertEquals(user.getEmpNo(), actual.getValue(0, "emp_no").toString());
        assertEquals(entity.getWorkflowType().getValue().toString(), actual.getValue(0, "workflow_type").toString());
        assertEquals(entity.getWorkflowNo().toString(), actual.getValue(0, "workflow_no").toString());
        assertEquals(entity.getCreatedBy().getEmpNo(), actual.getValue(0, "created_by").toString());
        assertNotNull(actual.getValue(0, "created_at"));
        assertEquals(entity.getUpdatedBy().getEmpNo(), actual.getValue(0, "updated_by").toString());
        assertEquals(String.valueOf(0L), actual.getValue(0, "delete_no").toString());
    }

    /**
     * {@link WorkflowTemplateDaoImpl#deleteByWorkflowTemplateUserId}のテストケース.
     * @throws Exception
     */
    @Test
    public void testDeleteByWorkflowTemplateUserId() throws Exception {
        Long id = 1L;
        WorkflowTemplate workflowTemplate = new WorkflowTemplate();
        workflowTemplate.setWorkflowTemplateUserId(id);

        User loginUser = new User();
        loginUser.setEmpNo("ZZA05");
        loginUser.setNameE("Keiichi Ogiwara");
        workflowTemplate.setUpdatedBy(loginUser);

        // 削除前のデータを取得
        String sql = "select * from workflow_template where workflow_template_user_id = " + id;
        ITable before = getConnection().createQueryTable("actual", sql);

        // テスト実行
        Integer record = dao.deleteByWorkflowTemplateUserId(workflowTemplate);

        assertTrue(8 == record);
        // 削除後のデータを取得
        ITable after = getConnection().createQueryTable("actual", sql);

        assertEquals(before.getRowCount(), after.getRowCount());

        for (int i = 0 ; i < record ; i++) {
            assertEquals(before.getValue(i, "id").toString(), after.getValue(i, "id").toString());
            assertEquals(before.getValue(i, "workflow_template_user_id").toString(), after.getValue(i, "workflow_template_user_id").toString());
            assertEquals(before.getValue(i, "emp_no"), after.getValue(i, "emp_no"));
            assertEquals(before.getValue(i, "workflow_type"), after.getValue(i, "workflow_type"));
            assertEquals(before.getValue(i, "workflow_no"), after.getValue(i, "workflow_no"));
            assertEquals(before.getValue(i, "created_by"), after.getValue(i, "created_by"));
            assertEquals(before.getValue(i, "created_at"), after.getValue(i, "created_at"));
            assertEquals(loginUser.getEmpNo(), after.getValue(i, "updated_by").toString());
            assertFalse(before.getValue(i, "updated_at").toString().equals(after.getValue(i, "updated_at").toString()));
            assertFalse(before.getValue(i, "delete_no").toString().equals(after.getValue(i, "delete_no").toString()));
        }
    }
}


text:
package controllers.eab

import cats.implicits._
import cats.data.OptionT
import connectors.DataCacheConnector
import controllers.{AmlsBaseController, CommonPlayDependencies}
import javax.inject.Inject
import models.eab.Eab
import play.api.libs.json._
import play.api.mvc.MessagesControllerComponents
import services.ProxyCacheService
import utils.AuthAction
import models.businessmatching.{EstateAgentBusinessService => EAB}
import services.businessmatching.ServiceFlow
import utils.DateOfChangeHelper

class EabController @Inject()(proxyCacheService  : ProxyCacheService,
                              authAction         : AuthAction,
                              val cacheConnector : DataCacheConnector,
                              val ds: CommonPlayDependencies,
                              val cc: MessagesControllerComponents,
                              val serviceFlow: ServiceFlow) extends AmlsBaseController(ds, cc) with DateOfChangeHelper {

  def get(credId: String) = Action.async {
    implicit request => {
      proxyCacheService.getEab(credId).map {
        _.map(Ok(_: JsValue)).getOrElse(NotFound)
      }
    }
  }

  def set(credId: String) = Action.async(parse.json) {
    implicit request => {
      proxyCacheService.setEab(credId, request.body).map {
        _ => {
          Ok(Json.obj("_id" -> credId))
        }
      }
    }
  }

  def requireDateOfChange(credId: String,
                          submissionStatus: String) = Action.async(parse.json) {

    implicit request => {

      def newEabServices: List[String] = Eab(
        request.body.as[JsObject].value("data").as[JsObject]
      ).services.getOrElse(List())

      for {
        currentEab    <- cacheConnector.fetch[Eab](credId, Eab.key)
        isNewActivity <- serviceFlow.isNewActivity(credId, EAB)
      } yield {

        def currentServices: Option[List[String]] = {
          currentEab.getOrElse(Eab(Json.obj())).services
        }

        if (!isNewActivity & dateOfChangApplicable(submissionStatus, currentServices, newEabServices)) {
          Ok(Json.obj("requireDateOfChange" -> true))
        } else {
          Ok(Json.obj("requireDateOfChange" -> false))
        }
      }
    }
  }

  def accept = authAction.async {
    implicit request =>
      (for {
        eab <- OptionT(cacheConnector.fetch[Eab](request.credId, Eab.key))
        _ <- OptionT.liftF(cacheConnector.save[Eab](request.credId, Eab.key, eab.copy(hasAccepted = true)))
      } yield Redirect(controllers.routes.RegistrationProgressController.get)) getOrElse InternalServerError("Could not update EAB")
  }
}


text:
DVLA ARE GENDER INSENSITIVE!!!

Now that I've got that out the way I can explain to you why I think that.

I recently worked on a project for making it easier to verify and approve drivers, en masse, for businesses that require it. As part of the project I had to build a licence "verification" tool to prevent drivers from inputting wrong details or licence numbers into the system. The tool works by creating its own licence number from the user's personal details and comparing it with the number they provided - If there's a match then the system can continue on to the next step, otherwise throw a big red "invalid" message back to the user.

The licence number is derivable from the personal information due to the way DVLA designed it - This can be found here. In a nutshell, each driving licence number has a 16 digit long unique sequence of characters and is constructed using the following rules:

1-5th The first five letters of your surname. If surname is less than five characters in length,
the remaining spaces will comprise of the digit 9.

6th The decade digit from the year of birth.

7-8th the month of birth. Add 5 to the 7th character if driver is female

9-10th The date of birth

11th The year digit from the year of birth

12-13th The first two initials of your forenames. The second character will comprise of
the digit 9 if no middle name

14-16th Usually 9, Computer check digits

Note: For our purposes we can discard the last 3 digits and work with the rest

So after reading that, do you see any problem with how the number is generated?

…………………….. go on, take your time …………………………

……………. hint: it's related to the title of this post ……………..

………………………. I can wait all day ………………………….

Fine! I'll tell you - They only cater for 2 genders, male and female. That is tantamount to blasphemy in this day and age of freedom, of both speech and most importantly expression. I find this anti-progressive, as by default I would want to provide users multiple gender options without thinking twice about it.

–

"Gender identities are complex and for many people, describing themselves as just a man or just
a woman has always been inadequate," - Professor Stephen Whittle, vice-president at Press
for Change.

The European Court of Human Rights has upheld the right to develop our gender identity, as key to our personal autonomy.

–

At this time where UK Facebook users are allowed to choose from 71 gender options, I believe everybody should follow suite. If DVLA ever update their forms to cater for more genders, I wonder how they will cope with people who choose different genders other than male or female on the application form. Based on the current driving licence generator no verification can be done on other genders.

Easy mode would be for DVLA to stop taking gender into consideration at all, not just for the generator but the form too - It doesn't really help identify a person at face value.

–

Enter your personal details to check your driving licence

<input type="text" id="firstname" placeholder="First Name" />
<input type="text" id="lastname" placeholder="Last Name" />
<input type="text" id="middlename" placeholder="Middle Name" />
<select id="gender">
  <option value="Male" id="male"> Male</option>
  <option value="Female" id="female"> Female</option>
  <option value="Other" id="other"> Other</option>
</select>
<input type="text" id="dob" placeholder="DOB" />

<input id="submit" type="submit" />


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

		<link href="../../assets/css/bootstrap.css" rel="stylesheet" type="text/css">

		<link href="../../assets/css/global.css" rel="stylesheet" type="text/css">
		<link href="update.css" rel="stylesheet" type="text/css">
		<title class="i18n">PageUpdateTitle</title>
		<link rel="shortcut icon" href="../../assets/img/logo/48.png" type="image/x-icon" />
		<base target="_blank" />

PageUpdateTitle

			PageUpdateHowToManual

				Version

				UpdateAvailableNow

PageUpdateReadyText

PageUpdateRestartNow

PageUpdateRestartLater

InstalledTitle

InstalledText

UpdatedTitle

UpdatedText

PageUpdateInstalled


text:
package org.locationtech.geomesa.security

import org.geotools.data.{FeatureReader, FeatureSource}
import org.geotools.feature.FeatureCollection
import org.junit.runner.RunWith
import org.opengis.feature.simple.{SimpleFeature, SimpleFeatureType}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class DataStoreSecurityServiceTest extends Specification with Mockito {

  sequential

  "DataStoreSecurityService" should {

    "use default, no security, provider when no provider is registered" >> {

      "for a FeatureReader" >> {
        val fr = mock[FeatureReader[SimpleFeatureType, SimpleFeature]]
        val result = DataStoreSecurityService.provider.secure(fr)
        result mustEqual fr
      }

      "for a FeatureCollection" >> {
        val fc = mock[FeatureCollection[SimpleFeatureType, SimpleFeature]]
        val result = DataStoreSecurityService.provider.secure(fc)
        result mustEqual fc
      }

      "for a FeatureSource" >> {
        val fs = mock[FeatureSource[SimpleFeatureType, SimpleFeature]]
        val result = DataStoreSecurityService.provider.secure(fs)
        result mustEqual fs
      }
    }
  }
}


text:
module ActiveHook
  module App
    class Middleware
      def initialize(app)
        @app = app
      end

      def call(env)
        @env = env
        @req = Rack::Request.new(env)

        if validation_request? then response(Validation)
        #Not enabling webhook creation yet.
        #elsif creation_request? then response(Creation)
        else @app.call(@env)
        end
      end

      def validation_request?
        @req.path == ActiveHook.config.validation_path && @req.get?
      end

      def creation_request?
        @req.path == ActiveHook.config.creation_path && @req.post?
      end

      def response(klass)
        response =
          if klass.new(@req).start then { code: 200, status: true }
          else { code: 400, status: false }
          end
        [response[:code], { "Content-Type" => "application/json" }, [{ status: response[:status] }.to_json]]
      end
    end

    Validation = Struct.new(:req) do
      def start
        hook = { id: req.params['id'].to_i, key: req.params['key'] }
        ActiveHook::Validate.new(hook).perform
      rescue
        false
      end
    end

    Creation = Struct.new(:req) do
      def start
        hook = JSON.parse(req.body.read)
        ActiveHook::Hook.new(hook).perform
      rescue
        false
      end
    end
  end
end


text:
using Fasterflect;
using Newtonsoft.Json;
using QuantConnect.Brokerages;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.Python;
using QuantConnect.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace QuantConnect.Queues
{
    /// <summary>
    /// Implementation of local/desktop job request:
    /// </summary>
    public class JobQueue : IJobQueueHandler
    {
        // The type name of the QuantConnect.Brokerages.Paper.PaperBrokerage
        private static readonly TextWriter Console = System.Console.Out;

        private const string PaperBrokerageTypeName = "PaperBrokerage";
        private const string DefaultHistoryProvider = "SubscriptionDataReaderHistoryProvider";
        private const string DefaultDataQueueHandler = "LiveDataQueue";
        private const string DefaultDataChannelProvider = "DataChannelProvider";
        private bool _liveMode = Config.GetBool("live-mode");
        private static readonly string AccessToken = Config.Get("api-access-token");
        private static readonly string OrganizationId = Config.Get("job-organization-id");
        private static readonly int UserId = Config.GetInt("job-user-id", 0);
        private static readonly int ProjectId = Config.GetInt("job-project-id", 0);
        private readonly string AlgorithmTypeName = Config.Get("algorithm-type-name");
        private readonly Language Language = (Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language"), ignoreCase: true);

        /// <summary>
        /// Physical location of Algorithm DLL.
        /// </summary>
        private string AlgorithmLocation
        {
            get
            {
                // we expect this dll to be copied into the output directory
                return Config.Get("algorithm-location", "QuantConnect.Algorithm.CSharp.dll");
            }
        }

        /// <summary>
        /// Initialize the job queue:
        /// </summary>
        public void Initialize(IApi api)
        {
            //
        }

        /// <summary>
        /// Gets Brokerage Factory for provided IDQH
        /// </summary>
        /// <param name="dataQueueHandler"></param>
        /// <returns>An Instance of Brokerage Factory if possible, otherwise null</returns>
        public static IBrokerageFactory GetFactoryFromDataQueueHandler(string dataQueueHandler)
        {
            IBrokerageFactory brokerageFactory = null;
            var dataQueueHandlerType = Composer.Instance.GetExportedTypes<IBrokerage>()
                .FirstOrDefault(x =>
                    x.FullName != null &&
                    x.FullName.EndsWith(dataQueueHandler, StringComparison.InvariantCultureIgnoreCase) &&
                    x.HasAttribute(typeof(BrokerageFactoryAttribute)));

            if (dataQueueHandlerType != null)
            {
                var attribute = dataQueueHandlerType.GetCustomAttribute<BrokerageFactoryAttribute>();
                brokerageFactory = (BrokerageFactory)Activator.CreateInstance(attribute.Type);
            }
            return brokerageFactory;
        }

        /// <summary>
        /// Desktop/Local Get Next Task - Get task from the Algorithm folder of VS Solution.
        /// </summary>
        /// <returns></returns>
        public AlgorithmNodePacket NextJob(out string location)
        {
            location = GetAlgorithmLocation();

            Log.Trace($"JobQueue.NextJob(): Selected {location}");

            // check for parameters in the config
            var parameters = new Dictionary<string, string>();

            var parametersConfigString = Config.Get("parameters");
            if (parametersConfigString != string.Empty)
            {
                parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersConfigString);
            }

            var controls = new Controls()
            {
                MinuteLimit = Config.GetInt("symbol-minute-limit", 10000),
                SecondLimit = Config.GetInt("symbol-second-limit", 10000),
                TickLimit = Config.GetInt("symbol-tick-limit", 10000),
                RamAllocation = int.MaxValue,
                MaximumDataPointsPerChartSeries = Config.GetInt("maximum-data-points-per-chart-series", 4000),
                StorageLimit = Config.GetValue("storage-limit", 10737418240L),
                StorageFileCount = Config.GetInt("storage-file-count", 10000),
                StoragePermissions = (FileAccess)Config.GetInt("storage-permissions", (int)FileAccess.ReadWrite)
            };

            var algorithmId = Config.Get("algorithm-id", AlgorithmTypeName);

            //If this isn't a backtesting mode/request, attempt a live job.
            if (_liveMode)
            {
                var dataHandlers = Config.Get("data-queue-handler", DefaultDataQueueHandler);
                var liveJob = new LiveNodePacket
                {
                    Type = PacketType.LiveNode,
                    Algorithm = File.ReadAllBytes(AlgorithmLocation),
                    Brokerage = Config.Get("live-mode-brokerage", PaperBrokerageTypeName),
                    HistoryProvider = Config.Get("history-provider", DefaultHistoryProvider),
                    DataQueueHandler = dataHandlers,
                    DataChannelProvider = Config.Get("data-channel-provider", DefaultDataChannelProvider),
                    Channel = AccessToken,
                    UserToken = AccessToken,
                    UserId = UserId,
                    ProjectId = ProjectId,
                    OrganizationId = OrganizationId,
                    Version = Globals.Version,
                    DeployId = algorithmId,
                    Parameters = parameters,
                    Language = Language,
                    Controls = controls,
                    PythonVirtualEnvironment = Config.Get("python-venv")
                };

                Type brokerageName = null;
                try
                {
                    // import the brokerage data for the configured brokerage
                    var brokerageFactory = Composer.Instance.Single<IBrokerageFactory>(factory => factory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
                    brokerageName = brokerageFactory.BrokerageType;
                    liveJob.BrokerageData = brokerageFactory.BrokerageData;
                }
                catch (Exception err)
                {
                    Log.Error(err, $"Error resolving BrokerageData for live job for brokerage {liveJob.Brokerage}");
                }

                foreach (var dataHandlerName in dataHandlers.DeserializeList())
                {
                    var brokerageFactoryForDataHandler = GetFactoryFromDataQueueHandler(dataHandlerName);
                    if (brokerageFactoryForDataHandler == null)
                    {
                        Log.Trace($"JobQueue.NextJob(): Not able to fetch data handler factory with name: {dataHandlerName}");
                        continue;
                    }
                    if (brokerageFactoryForDataHandler.BrokerageType == brokerageName)
                    {
                        //Don't need to add brokearageData again if added by brokerage
                        continue;
                    }
                    foreach (var data in brokerageFactoryForDataHandler.BrokerageData)
                    {
                        if (data.Key == "live-holdings")
                        {
                            //live-holdings not required for data handler
                            continue;
                        }
                        else if (!liveJob.BrokerageData.ContainsKey(data.Key))
                        {
                            liveJob.BrokerageData.Add(data.Key, data.Value);
                        }
                        else
                        {
                            throw new ArgumentException($"JobQueue.NextJob(): Key already exists in BrokerageData -- {data.Key}");
                        }
                    }
                }
                return liveJob;
            }

            //Default run a backtesting job.
            var backtestJob = new BacktestNodePacket(0, 0, "", new byte[] { }, Config.Get("backtest-name", "local"))
            {
                Type = PacketType.BacktestNode,
                Algorithm = File.ReadAllBytes(AlgorithmLocation),
                HistoryProvider = Config.Get("history-provider", DefaultHistoryProvider),
                Channel = AccessToken,
                UserToken = AccessToken,
                UserId = UserId,
                ProjectId = ProjectId,
                OrganizationId = OrganizationId,
                Version = Globals.Version,
                BacktestId = algorithmId,
                Language = Language,
                Parameters = parameters,
                Controls = controls,
                PythonVirtualEnvironment = Config.Get("python-venv")
            };

            return backtestJob;
        }

        /// <summary>
        /// Get the algorithm location for client side backtests.
        /// </summary>
        /// <returns></returns>
        private string GetAlgorithmLocation()
        {
            if (Language == Language.Python)
            {
                if (!File.Exists(AlgorithmLocation))
                {
                    throw new FileNotFoundException($"JobQueue.TryCreatePythonAlgorithm(): Unable to find py file: {AlgorithmLocation}");
                }

                // Add this directory to our Python Path so it may be imported properly
                var pythonFile = new FileInfo(AlgorithmLocation);
                PythonInitializer.AddAlgorithmLocationPath(pythonFile.Directory.FullName);
            }

            return AlgorithmLocation;
        }

        /// <summary>
        /// Desktop/Local acknowledge the task processed. Nothing to do.
        /// </summary>
        /// <param name="job"></param>
        public void AcknowledgeJob(AlgorithmNodePacket job)
        {
            // Make the console window pause so we can read log output before exiting and killing the application completely
            Console.WriteLine("Engine.Main(): Analysis Complete.");
            // closing automatically is useful for optimization, we don't want to leave open all the ended lean instances
            if (!Config.GetBool("close-automatically"))
            {
                Console.WriteLine("Engine.Main(): Press any key to continue.");
                System.Console.Read();
            }
        }
    }
}


text:
package alluxio;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runners.model.Statement;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * Unit tests for {@link SystemErrRule}.
 */
public class SystemErrRuleTest {
  private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream();
  private static final PrintStream ORIGINAL_SYSTEM_ERR = System.err;

  private Statement mStatement = new Statement() {
    @Override
    public void evaluate() throws Throwable {
      System.err.println("2048");
      assertEquals("2048\n", OUTPUT.toString());
      OUTPUT.reset();

      System.err.println("1234");
      assertEquals("1234\n", OUTPUT.toString());
    }
  };

  @Test
  public void testSystemErrRule() throws Throwable {
    new SystemErrRule(OUTPUT).apply(mStatement, null).evaluate();
    assertEquals(System.err, ORIGINAL_SYSTEM_ERR);
  }
}