text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>de.gishmo.gwt</groupId>
  <artifactId>gwt-editor-apt</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>gwt-editor-apt</name>
  <description>GWT Editor generator ported as an annotation processor</description>
  <url>https://github.com/FrankHossfeld/gwt-editor-apt</url>
  <inceptionYear>2016</inceptionYear>
  <licenses>
    <license>
      <name>The Apache License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
    </license>
  </licenses>
  <developers>
    <developer>
      <name>Frank Hossfeld</name>
      <email>frank.hossfeld@hossfeld-solutions.de</email>
    </developer>
  </developers>
  <scm>
    <connection>scm:git:https://github.com/FrankHossfeld/gwt-editor-apt</connection>
    <developerConnection>scm:git:git@github.com:FrankHossfeld/gwt-editor-apt.git</developerConnection>
    <url>https://github.com/tbroyer/gwt-places</url>
    <tag>HEAD</tag>
  </scm>
  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/FrankHossfeld/gwt-editor-apt/issues</url>
  </issueManagement>

  <!--<distributionManagement>-->
    <!--<snapshotRepository>-->
      <!--<id>ossrh</id>-->
      <!--<url>https://oss.sonatype.org/content/repositories/snapshots</url>-->
    <!--</snapshotRepository>-->
  <!--</distributionManagement>-->

  <properties>
    <plugin.compiler.version>3.1</plugin.compiler.version>
    <plugin.source.version>2.4</plugin.source.version>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.build.outputEncoding>UTF-8</project.build.outputEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <project.source.version>1.8</project.source.version>
    <project.target.version>1.8</project.target.version>

    <auto.common.version>0.6</auto.common.version>
    <auto.service.version>1.0-rc2</auto.service.version>
    <compile.testing.version>0.9</compile.testing.version>
    <gwt.version>2.7.0</gwt.version>
    <javapoet.version>1.4.0</javapoet.version>
    <junit.version>4.12</junit.version>
    <google.truth.version>0.28</google.truth.version>
    <org.truth.version>0.23</org.truth.version>
    <validation-api.version>1.1.0.Final</validation-api.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.gwt</groupId>
        <artifactId>gwt</artifactId>
        <version>${gwt.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-user</artifactId>
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>com.google.auto</groupId>
      <artifactId>auto-common</artifactId>
      <version>${auto.common.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.auto.service</groupId>
      <artifactId>auto-service</artifactId>
      <version>${auto.service.version}</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>com.squareup</groupId>
      <artifactId>javapoet</artifactId>
      <version>${javapoet.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>${validation-api.version}</version>
    </dependency>
    <!--<dependency>-->
      <!--<groupId>com.squareup</groupId>-->
      <!--<artifactId>javapoet</artifactId>-->
      <!--<version>1.1.0</version>-->
    <!--</dependency>-->
    <!--<dependency>-->
      <!--<groupId>com.google.guava</groupId>-->
      <!--<artifactId>guava</artifactId>-->
      <!--<version>18.0</version>-->
    <!--</dependency>-->
    <dependency>
      <groupId>com.google.testing.compile</groupId>
      <artifactId>compile-testing</artifactId>
      <version>${compile.testing.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.truth0</groupId>
      <artifactId>truth</artifactId>
      <version>${org.truth.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/client/**</include>
          <include>**/rebind/**</include>
          <include>**/processor/**</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/client/**</include>
          <include>**/shared/**</include>
          <include>**/*.gwt.xml</include>
          <include>**/*.html</include>
          <include>**/public/**</include>
        </includes>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${plugin.compiler.version}</version>
        <configuration>
          <source>${project.source.version}</source>
          <target>${project.target.version}</target>
          <compilerArgument>-Xlint:all</compilerArgument>
          <showWarnings>true</showWarnings>
          <showDeprecation>true</showDeprecation>
        </configuration>
        <executions>
          <execution>
            <id>default-testCompile</id>
            <configuration>
              <proc>none</proc>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>${plugin.source.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>test-jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <!--<plugin>-->
        <!--<groupId>org.apache.maven.plugins</groupId>-->
        <!--<artifactId>maven-shade-plugin</artifactId>-->
        <!--<version>2.4</version>-->
        <!--<executions>-->
          <!--<execution>-->
            <!--<goals>-->
              <!--<goal>shade</goal>-->
            <!--</goals>-->
          <!--</execution>-->
        <!--</executions>-->
        <!--<configuration>-->
          <!--<minimizeJar>true</minimizeJar>-->
          <!--<artifactSet>-->
            <!--<excludes>-->
              <!--<exclude>com.google.gwt:gwt-user</exclude>-->
              <!--<exclude>com.google.auto.service:auto-service</exclude>-->
            <!--</excludes>-->
          <!--</artifactSet>-->
          <!--<relocations>-->
            <!--<relocation>-->
              <!--<pattern>com.google.auto</pattern>-->
              <!--<shadedPattern>net.ltgt.gwt.place.thirdparty.com.google.auto</shadedPattern>-->
            <!--</relocation>-->
            <!--<relocation>-->
              <!--<pattern>com.google.common</pattern>-->
              <!--<shadedPattern>net.ltgt.gwt.place.thirdparty.com.google.common</shadedPattern>-->
            <!--</relocation>-->
            <!--<relocation>-->
              <!--<pattern>com.squareup</pattern>-->
              <!--<shadedPattern>net.ltgt.gwt.place.thirdparty.com.squareup</shadedPattern>-->
            <!--</relocation>-->
          <!--</relocations>-->
        <!--</configuration>-->
      <!--</plugin>-->
      <!--<plugin>-->
        <!--<groupId>org.apache.maven.plugins</groupId>-->
        <!--<artifactId>maven-invoker-plugin</artifactId>-->
        <!--<version>1.10</version>-->
        <!--<configuration>-->
          <!--<cloneProjectsTo>${project.build.directory}/it-tests</cloneProjectsTo>-->
          <!--<localRepositoryPath>${project.build.directory}/it-repo</localRepositoryPath>-->
          <!--<settingsFile>src/it/settings.xml</settingsFile>-->
          <!--<streamLogs>true</streamLogs>-->
          <!--<showErrors>true</showErrors>-->
        <!--</configuration>-->
        <!--<executions>-->
          <!--<execution>-->
            <!--<id>integration-test</id>-->
            <!--<goals>-->
              <!--<goal>install</goal>-->
              <!--<goal>run</goal>-->
            <!--</goals>-->
          <!--</execution>-->
        <!--</executions>-->
      <!--</plugin>-->
      <!--<plugin>-->
        <!--<groupId>org.apache.maven.plugins</groupId>-->
        <!--<artifactId>maven-enforcer-plugin</artifactId>-->
        <!--<version>1.4</version>-->
        <!--<executions>-->
          <!--<execution>-->
            <!--<goals>-->
              <!--<goal>enforce</goal>-->
            <!--</goals>-->
          <!--</execution>-->
        <!--</executions>-->
        <!--<configuration>-->
          <!--<rules>-->
            <!--<requireMavenVersion>-->
              <!--<!– We use wildcard dependency exclusions –>-->
              <!--<version>[3.2.1,)</version>-->
            <!--</requireMavenVersion>-->
          <!--</rules>-->
        <!--</configuration>-->
      <!--</plugin>-->
      <!--<plugin>-->
        <!--<groupId>org.sonatype.plugins</groupId>-->
        <!--<artifactId>nexus-staging-maven-plugin</artifactId>-->
        <!--<version>1.6.5</version>-->
        <!--<extensions>true</extensions>-->
        <!--<configuration>-->
          <!--<serverId>ossrh</serverId>-->
          <!--<nexusUrl>https://oss.sonatype.org/</nexusUrl>-->
          <!--<autoReleaseAfterClose>true</autoReleaseAfterClose>-->
        <!--</configuration>-->
      <!--</plugin>-->
      <!--<plugin>-->
        <!--<groupId>org.apache.maven.plugins</groupId>-->
        <!--<artifactId>maven-release-plugin</artifactId>-->
        <!--<version>2.5.2</version>-->
        <!--<configuration>-->
          <!--<autoVersionSubmodules>true</autoVersionSubmodules>-->
          <!--<useReleaseProfile>false</useReleaseProfile>-->
          <!--<releaseProfiles>release</releaseProfiles>-->
          <!--<goals>deploy</goals>-->
        <!--</configuration>-->
      <!--</plugin>-->
    </plugins>
  </build>

  <!--<profiles>-->
    <!--<profile>-->
      <!--<id>release</id>-->
      <!--<build>-->
        <!--<plugins>-->
          <!--<plugin>-->
            <!--<groupId>org.apache.maven.plugins</groupId>-->
            <!--<artifactId>maven-enforcer-plugin</artifactId>-->
            <!--<configuration>-->
              <!--<rules>-->
                <!--<requireJavaVersion>-->
                  <!--<version>[1.8,1.9)</version>-->
                <!--</requireJavaVersion>-->
              <!--</rules>-->
            <!--</configuration>-->
          <!--</plugin>-->
          <!--<plugin>-->
            <!--<groupId>org.apache.maven.plugins</groupId>-->
            <!--<artifactId>maven-source-plugin</artifactId>-->
            <!--<executions>-->
              <!--<execution>-->
                <!--<id>attach-sources</id>-->
                <!--<goals>-->
                  <!--<goal>jar-no-fork</goal>-->
                <!--</goals>-->
              <!--</execution>-->
            <!--</executions>-->
          <!--</plugin>-->
          <!--<plugin>-->
            <!--<groupId>org.apache.maven.plugins</groupId>-->
            <!--<artifactId>maven-javadoc-plugin</artifactId>-->
            <!--<version>2.10.3</version>-->
            <!--<executions>-->
              <!--<execution>-->
                <!--<id>attach-javadocs</id>-->
                <!--<goals>-->
                  <!--<goal>jar</goal>-->
                <!--</goals>-->
              <!--</execution>-->
            <!--</executions>-->
          <!--</plugin>-->
          <!--<plugin>-->
            <!--<groupId>org.apache.maven.plugins</groupId>-->
            <!--<artifactId>maven-gpg-plugin</artifactId>-->
            <!--<version>1.6</version>-->
            <!--<executions>-->
              <!--<execution>-->
                <!--<id>sign-artifacts</id>-->
                <!--<phase>verify</phase>-->
                <!--<goals>-->
                  <!--<goal>sign</goal>-->
                <!--</goals>-->
              <!--</execution>-->
            <!--</executions>-->
          <!--</plugin>-->
        <!--</plugins>-->
      <!--</build>-->
    <!--</profile>-->
  <!--</profiles>-->
</project>


text:
class Client
{
    bool connected = false;
    QTcpSocket *tcpSocket;

public:
    Client();
    bool connect(QString host);
    QString getTemperature();
};

#endif // CONTROLS_H

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2019 Cisco and/or its affiliates.
//
// 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 local

import (
	"context"
	"fmt"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connectioncontext"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/networkservice"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/registry"
	"github.com/networkservicemesh/networkservicemesh/controlplane/pkg/api/nsm"
	"github.com/networkservicemesh/networkservicemesh/controlplane/pkg/common"
	"github.com/networkservicemesh/networkservicemesh/controlplane/pkg/model"
	"github.com/networkservicemesh/networkservicemesh/pkg/tools/spanhelper"
)

// ConnectionService makes basic Mechanism selection for the incoming connection
type endpointSelectorService struct {
	nseManager nsm.NetworkServiceEndpointManager
}

func (cce *endpointSelectorService) Request(ctx context.Context, request *networkservice.NetworkServiceRequest) (*connection.Connection, error) {
	logger := common.Log(ctx)
	span := spanhelper.GetSpanHelper(ctx)
	clientConnection := common.ModelConnection(ctx)
	dp := common.Forwarder(ctx)

	if clientConnection == nil {
		return nil, errors.Errorf("client connection need to be passed")
	}

	// 4. Check if Heal/Update if we need to ask remote NSM or it is a just local mechanism change requested.
	// true if we detect we need to request NSE to upgrade/update connection.
	// 4.1 New Network service is requested, we need to close current connection and do re-request of NSE.
	requestNSEOnUpdate := cce.checkNSEUpdateIsRequired(ctx, clientConnection, request, logger, dp)
	span.LogObject("requestNSEOnUpdate", requestNSEOnUpdate)

	// 7. do a Request() on NSE and select it.
	if clientConnection.ConnectionState == model.ClientConnectionHealing && !requestNSEOnUpdate {
		return cce.checkUpdateConnectionContext(ctx, request, clientConnection)
	}

	// 7.1 try find NSE and do a Request to it.
	var lastError error
	ignoreEndpoints := common.IgnoredEndpoints(ctx)
	parentCtx := ctx
	attempt := 0
	for {
		attempt++
		span := spanhelper.FromContext(parentCtx, fmt.Sprintf("select-nse-%v", attempt))

		logger := span.Logger()
		ctx = common.WithLog(span.Context(), logger)

		// 7.1.1 Clone Connection to support iteration via EndPoints
		newRequest, endpoint, err := cce.prepareRequest(ctx, request, clientConnection, ignoreEndpoints)
		if err != nil {
			span.Finish()
			return cce.combineErrors(span, lastError, err)
		}
		if err = cce.checkTimeout(parentCtx, span); err != nil {
			span.Finish()
			return nil, err
		}

		// 7.1.7 perform request to NSE/remote NSMD/NSE
		ctx = common.WithEndpoint(ctx, endpoint)
		// Perform passing execution to next chain element.
		conn, err := common.ProcessNext(ctx, newRequest)

		// 7.1.8 in case of error we put NSE into ignored list to check another one.
		if err != nil {
			logger.Errorf("NSM:(7.1.8) NSE respond with error: %v ", err)
			lastError = err
			ignoreEndpoints[endpoint.GetEndpointNSMName()] = endpoint
			span.Finish()
			continue
		}
		// We could put endpoint to clientConnection.
		clientConnection.Endpoint = endpoint
		if !cce.nseManager.IsLocalEndpoint(endpoint) {
			clientConnection.RemoteNsm = endpoint.GetNetworkServiceManager()
		}
		// 7.1.9 We are fine with NSE connection and could continue.
		span.Finish()
		return conn, nil
	}
}

func (cce *endpointSelectorService) combineErrors(span spanhelper.SpanHelper, err, lastError error) (*connection.Connection, error) {
	if lastError != nil {
		span.LogError(lastError)
		return nil, errors.Errorf("NSM:(7.1.5) %v. Last NSE Error: %v", err, lastError)
	}
	return nil, err
}

func (cce *endpointSelectorService) selectEndpoint(ctx context.Context, clientConnection *model.ClientConnection, ignoreEndpoints map[registry.EndpointNSMName]*registry.NSERegistration, nseConn *connection.Connection) (*registry.NSERegistration, error) {
	var endpoint *registry.NSERegistration
	if clientConnection.ConnectionState == model.ClientConnectionHealing {
		// 7.1.2 Check previous endpoint, and it we will be able to contact it, it should be fine.
		endpointName := clientConnection.Endpoint.GetEndpointNSMName()
		if clientConnection.Endpoint != nil && ignoreEndpoints[endpointName] == nil {
			endpoint = clientConnection.Endpoint
		} else {
			// Ignored, we need to update DSTid.
			clientConnection.Xcon.Destination.Id = "-"
		}
		//TODO: Add check if endpoint are in registry or not.
	}
	// 7.1.3 Check if endpoint is not ignored yet
	if endpoint == nil {
		// 7.1.4 Choose a new endpoint
		return cce.nseManager.GetEndpoint(ctx, nseConn, ignoreEndpoints)
	}
	return endpoint, nil
}

func (cce *endpointSelectorService) checkNSEUpdateIsRequired(ctx context.Context, clientConnection *model.ClientConnection, request *networkservice.NetworkServiceRequest, logger logrus.FieldLogger, dp *model.Forwarder) bool {
	requestNSEOnUpdate := false
	if clientConnection.ConnectionState == model.ClientConnectionHealing {
		if request.Connection.GetNetworkService() != clientConnection.GetNetworkService() {
			requestNSEOnUpdate = true

			// Just close, since client connection already passed with context.
			// Network service is closing, we need to close remote NSM and re-program local one.
			if _, err := common.ProcessClose(ctx, request.GetConnection()); err != nil {
				logger.Errorf("NSM:(4.1) Error during close of NSE during Request.Upgrade %v Existing connection: %v error %v", request, clientConnection, err)
			}
		} else {
			// 4.2 Check if NSE is still required, if some more context requests are different.
			requestNSEOnUpdate = cce.checkNeedNSERequest(logger, request.Connection, clientConnection, dp)
			if requestNSEOnUpdate {
				logger.Infof("Context is different, NSE request is required")
			}
		}
	}
	return requestNSEOnUpdate
}

func (cce *endpointSelectorService) validateConnection(ctx context.Context, conn *connection.Connection) error {
	return conn.IsComplete()
}

func (cce *endpointSelectorService) updateConnectionContext(ctx context.Context, source, destination *connection.Connection) error {
	if err := cce.validateConnection(ctx, destination); err != nil {
		return err
	}

	if err := source.UpdateContext(destination.GetContext()); err != nil {
		return err
	}

	return nil
}

/**
check if we need to do a NSE/Remote NSM request in case of our connection Upgrade/Healing procedure.
*/
func (cce *endpointSelectorService) checkNeedNSERequest(logger logrus.FieldLogger, nsmConn *connection.Connection, existingCC *model.ClientConnection, dp *model.Forwarder) bool {
	// 4.2.x
	// 4.2.1 Check if context is changed, if changed we need to
	if !proto.Equal(nsmConn.GetContext(), existingCC.GetConnectionSource().GetContext()) {
		return true
	}
	// We need to check, dp has mechanism changes in our Remote connection selected mechanism.

	if dst := existingCC.GetConnectionDestination(); dst.IsRemote() {
		dstM := dst.GetMechanism()

		// 4.2.2 Let's check if remote destination is matches our forwarder destination.
		if dpM := cce.findMechanism(dp.RemoteMechanisms, dstM.GetType()); dpM != nil {
			// 4.2.3 We need to check if source mechanism type and source parameters are different
			for k, v := range dpM.GetParameters() {
				rmV := dstM.GetParameters()[k]
				if v != rmV {
					logger.Infof("NSM:(4.2.3) Remote mechanism parameter %s was different with previous one : %v  %v", k, rmV, v)
					return true
				}
			}
			if !dpM.Equals(dstM) {
				logger.Infof("NSM:(4.2.4)  Remote mechanism was different with previous selected one : %v  %v", dstM, dpM)
				return true
			}
		} else {
			logger.Infof("NSM:(4.2.5) Remote mechanism previously selected was not found: %v  in forwarder %v", dstM, dp.RemoteMechanisms)
			return true
		}
	}

	return false
}

func (cce *endpointSelectorService) findMechanism(mechanismPreferences []*connection.Mechanism, mechanismType string) *connection.Mechanism {
	for _, m := range mechanismPreferences {
		if m.GetType() == mechanismType {
			return m
		}
	}
	return nil
}

func (cce *endpointSelectorService) Close(ctx context.Context, connection *connection.Connection) (*empty.Empty, error) {
	return common.ProcessClose(ctx, connection)
}

func (cce *endpointSelectorService) checkUpdateConnectionContext(ctx context.Context, request *networkservice.NetworkServiceRequest, clientConnection *model.ClientConnection) (*connection.Connection, error) {
	// We do not need to do request to endpoint and just need to update all stuff.
	// 7.2 We do not need to access NSE, since all parameters are same.
	logger := common.Log(ctx)
	clientConnection.Xcon.Source.Mechanism = request.Connection.GetMechanism()
	clientConnection.Xcon.Source.State = connection.State_UP

	// 7.3 Destination context probably has been changed, so we need to update source context.
	if err := cce.updateConnectionContext(ctx, request.GetConnection(), clientConnection.GetConnectionDestination()); err != nil {
		err = errors.Errorf("NSM:(7.3) Failed to update source connection context: %v", err)

		// Just close since client connection is already passed with context
		if _, closeErr := common.ProcessClose(ctx, request.GetConnection()); closeErr != nil {
			logger.Errorf("Failed to perform close: %v", closeErr)
		}
		return nil, err
	}

	if !cce.nseManager.IsLocalEndpoint(clientConnection.Endpoint) {
		clientConnection.RemoteNsm = clientConnection.Endpoint.GetNetworkServiceManager()
	}
	return request.Connection, nil
}

func (cce *endpointSelectorService) prepareRequest(ctx context.Context, request *networkservice.NetworkServiceRequest, clientConnection *model.ClientConnection, ignoreEndpoints map[registry.EndpointNSMName]*registry.NSERegistration) (*networkservice.NetworkServiceRequest, *registry.NSERegistration, error) {
	newRequest := request.Clone()
	nseConn := newRequest.Connection
	span := spanhelper.GetSpanHelper(ctx)

	endpoint, err := cce.selectEndpoint(ctx, clientConnection, ignoreEndpoints, nseConn)
	if err != nil {
		return nil, nil, err
	}

	span.LogObject("selected endpoint", endpoint)
	if nseConn.GetContext() == nil {
		nseConn.Context = &connectioncontext.ConnectionContext{}
	}

	newRequest.Connection = nseConn
	return newRequest, endpoint, nil
}

func (cce *endpointSelectorService) checkTimeout(ctx context.Context, span spanhelper.SpanHelper) error {
	if ctx.Err() != nil {
		newErr := errors.Errorf("NSM:(7.1.0) Context timeout, during find/call NSE... %v", ctx.Err())
		span.LogError(newErr)
		return newErr
	}
	return nil
}

// NewEndpointSelectorService - creates a service to select endpoint
func NewEndpointSelectorService(nseManager nsm.NetworkServiceEndpointManager) networkservice.NetworkServiceServer {
	return &endpointSelectorService{
		nseManager: nseManager,
	}
}


text:
#include <assert.h>
#include <h2o.h>
#include <stddef.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <postgresql/libpq-fe.h>
#include <yajl/yajl_gen.h>

#include "bitset.h"
#include "database.h"
#include "error.h"
#include "request_handler.h"
#include "thread.h"
#include "utility.h"
#include "world.h"

#define ID_KEY "id"
#define MAX_QUERIES 500
#define QUERIES_PARAMETER "queries="
#define RANDOM_NUM_KEY "randomNumber"

typedef enum {
	NO_UPDATE = 0,
	CREATE,
	COPY_1,
	COPY_2,
	UPDATE
} update_state_t;

typedef struct {
	uint32_t id;
	uint32_t random_number;
} query_result_t;

typedef struct {
	db_query_param_t param;
	yajl_gen gen;
	const char *id_pointer;
	h2o_req_t *req;
	uint32_t id;
	int id_format;
	int id_len;
} single_query_ctx_t;

typedef struct {
	single_query_ctx_t single;
	size_t num_query;
	size_t num_result;
	update_state_t update_state;
	query_result_t res[];
} multiple_query_ctx_t;

static int do_multiple_queries(update_state_t update_state, h2o_req_t *req);
static int initialize_single_query_context(h2o_req_t *req,
                                           on_result_t on_result,
                                           single_query_ctx_t *query_ctx);
static void on_database_error(db_query_param_t *param, const char *error_string);
static void on_database_timeout(db_query_param_t *param);
static result_return_t on_multiple_query_result(db_query_param_t *param, PGresult *result);
static result_return_t on_single_query_result(db_query_param_t *param, PGresult *result);
static result_return_t on_update_result(db_query_param_t *param, PGresult *result);
static int on_update_write_ready(db_query_param_t *param, PGconn *db_conn);
static int serialize_item(uint32_t id, uint32_t random_number, yajl_gen gen);
static void serialize_items(const query_result_t *res,
                            size_t num_result,
                            yajl_gen gen,
                            h2o_req_t *req);

static int do_multiple_queries(update_state_t update_state, h2o_req_t *req)
{
	thread_context_t * const ctx = H2O_STRUCT_FROM_MEMBER(thread_context_t,
	                                                      event_loop.h2o_ctx,
	                                                      req->conn->ctx);
	int num_query = 0;

	if (req->query_at < SIZE_MAX) {
		const char * const n = get_query_param(req->path.base + req->query_at + 1,
		                                       req->path.len - req->query_at - 1,
		                                       QUERIES_PARAMETER,
		                                       sizeof(QUERIES_PARAMETER) - 1);

		if (n)
			num_query = atoi(n);
	}

	if (num_query < 1)
		num_query = 1;
	else if (num_query > MAX_QUERIES)
		num_query = MAX_QUERIES;

	const size_t sz = offsetof(multiple_query_ctx_t, res) + num_query * sizeof(query_result_t);
	multiple_query_ctx_t * const query_ctx = h2o_mem_alloc_pool(&req->pool, sz);

	if (!query_ctx || initialize_single_query_context(req,
	                                                  on_multiple_query_result,
	                                                  &query_ctx->single))
		send_error(INTERNAL_SERVER_ERROR, MEM_ALLOC_ERR_MSG, req);
	else {
		// MAX_ID is a relatively small number, so allocate on the stack.
		DEFINE_BITSET(bitset, MAX_ID);

		memset(&query_ctx->single + 1,
		       0,
		       offsetof(multiple_query_ctx_t, res) - sizeof(query_ctx->single));
		query_ctx->num_query = num_query;
		query_ctx->update_state = update_state;

		size_t max_rand = MAX_ID - query_ctx->num_query + 1;

		for (size_t i = 0; i < query_ctx->num_query; i++) {
			query_ctx->res[i].id = get_random_number(max_rand, &ctx->random_seed);

			if (BITSET_ISSET(query_ctx->res[i].id, bitset))
				query_ctx->res[i].id = max_rand - 1;

			BITSET_SET(query_ctx->res[i].id++, bitset);
			max_rand++;
		}

		query_ctx->single.id = htonl(query_ctx->res->id);

		if (execute_query(ctx, &query_ctx->single.param)) {
			yajl_gen_free(query_ctx->single.gen);
			send_service_unavailable_error(DB_REQ_ERROR, req);
		}
	}

	return 0;
}

static int initialize_single_query_context(h2o_req_t *req,
                                           on_result_t on_result,
                                           single_query_ctx_t *query_ctx)
{
	int ret = EXIT_FAILURE;

	memset(query_ctx, 0, sizeof(*query_ctx));
	query_ctx->gen = get_json_generator(&req->pool);

	if (query_ctx->gen) {
		query_ctx->id_format = 1;
		query_ctx->id_len = sizeof(query_ctx->id);
		query_ctx->id_pointer = (const char *) &query_ctx->id;
		query_ctx->param.command = WORLD_TABLE_NAME;
		query_ctx->param.nParams = 1;
		query_ctx->param.on_error = on_database_error;
		query_ctx->param.on_result = on_result;
		query_ctx->param.on_timeout = on_database_timeout;
		query_ctx->param.paramFormats = &query_ctx->id_format;
		query_ctx->param.paramLengths = &query_ctx->id_len;
		query_ctx->param.paramValues = &query_ctx->id_pointer;
		query_ctx->param.flags = IS_PREPARED;
		query_ctx->param.resultFormat = 1;
		query_ctx->req = req;
		ret = EXIT_SUCCESS;
	}

	return ret;
}

static void on_database_error(db_query_param_t *param, const char *error_string)
{
	single_query_ctx_t * const query_ctx = H2O_STRUCT_FROM_MEMBER(single_query_ctx_t,
	                                                              param,
	                                                              param);

	yajl_gen_free(query_ctx->gen);
	send_error(BAD_GATEWAY, error_string, query_ctx->req);
}

static void on_database_timeout(db_query_param_t *param)
{
	single_query_ctx_t * const query_ctx = H2O_STRUCT_FROM_MEMBER(single_query_ctx_t,
	                                                              param,
	                                                              param);

	yajl_gen_free(query_ctx->gen);
	send_error(GATEWAY_TIMEOUT, DB_TIMEOUT_ERROR, query_ctx->req);
}

static result_return_t on_multiple_query_result(db_query_param_t *param, PGresult *result)
{
	multiple_query_ctx_t * const query_ctx = H2O_STRUCT_FROM_MEMBER(multiple_query_ctx_t,
	                                                                single.param,
	                                                                param);

	if (PQresultStatus(result) == PGRES_TUPLES_OK) {
		thread_context_t * const ctx = H2O_STRUCT_FROM_MEMBER(thread_context_t,
		                                                      event_loop.h2o_ctx,
		                                                      query_ctx->single.req->conn->ctx);
		uint32_t * const random_number = &query_ctx->res[query_ctx->num_result++].random_number;

		assert(PQnfields(result) == 2);
		assert(PQntuples(result) == 1);
		assert(PQgetlength(result, 0, 1) == sizeof(*random_number));
		// Use memcpy() in case the result is not aligned.
		memcpy(random_number, PQgetvalue(result, 0, 1), sizeof(*random_number));
		*random_number = ntohl(*random_number);
		PQclear(result);

		if (query_ctx->num_result < query_ctx->num_query) {
			query_ctx->single.id = htonl(query_ctx->res[query_ctx->num_result].id);

			if (!execute_query(ctx, &query_ctx->single.param))
				return DONE;

			send_service_unavailable_error(DB_REQ_ERROR, query_ctx->single.req);
		}
		else if (query_ctx->update_state == NO_UPDATE) {
			serialize_items(query_ctx->res,
			                query_ctx->num_result,
			                query_ctx->single.gen,
			                query_ctx->single.req);
			return DONE;
		}
		else {
			query_ctx->single.param.command = UPDATE_QUERY;
			query_ctx->single.param.nParams = 0;
			query_ctx->single.param.on_result = on_update_result;
			query_ctx->single.param.on_write_ready = on_update_write_ready;
			query_ctx->single.param.paramFormats = NULL;
			query_ctx->single.param.paramLengths = NULL;
			query_ctx->single.param.paramValues = NULL;
			query_ctx->single.param.flags = 0;

			if (!execute_query(ctx, &query_ctx->single.param))
				return DONE;

			send_service_unavailable_error(DB_REQ_ERROR, query_ctx->single.req);
		}
	}
	else {
		send_error(BAD_GATEWAY, PQresultErrorMessage(result), query_ctx->single.req);
		PQclear(result);
	}

	yajl_gen_free(query_ctx->single.gen);
	return DONE;
}

static result_return_t on_single_query_result(db_query_param_t *param, PGresult *result)
{
	single_query_ctx_t * const query_ctx = H2O_STRUCT_FROM_MEMBER(single_query_ctx_t,
	                                                              param,
	                                                              param);

	if (PQresultStatus(result) == PGRES_TUPLES_OK) {
		uint32_t random_number;

		assert(PQnfields(result) == 2);
		assert(PQntuples(result) == 1);
		assert(PQgetlength(result, 0, 1) == sizeof(random_number));

		// Use memcpy() in case the result is not aligned.
		memcpy(&random_number, PQgetvalue(result, 0, 1), sizeof(random_number));
		random_number = ntohl(random_number);
		PQclear(result);

		if (!serialize_item(ntohl(query_ctx->id), random_number, query_ctx->gen) &&
		    !send_json_response(query_ctx->gen, NULL, query_ctx->req))
			return DONE;

		send_error(INTERNAL_SERVER_ERROR, MEM_ALLOC_ERR_MSG, query_ctx->req);
	}
	else {
		send_error(BAD_GATEWAY, PQresultErrorMessage(result), query_ctx->req);
		PQclear(result);
	}

	yajl_gen_free(query_ctx->gen);
	return DONE;
}

static result_return_t on_update_result(db_query_param_t *param, PGresult *result)
{
	multiple_query_ctx_t * const query_ctx = H2O_STRUCT_FROM_MEMBER(multiple_query_ctx_t,
	                                                                single.param,
	                                                                param);
	result_return_t ret = SUCCESS;
	const ExecStatusType status = PQresultStatus(result);

	switch (query_ctx->update_state) {
		case CREATE:
		case COPY_2:
			if (status != PGRES_COMMAND_OK)
				goto error;

			query_ctx->update_state++;
			break;
		case COPY_1:
			if (status != PGRES_COPY_IN)
				goto error;

			ret = WANT_WRITE;
			break;
		case UPDATE:
			if (status != PGRES_COMMAND_OK)
				goto error;

			serialize_items(query_ctx->res,
			                query_ctx->num_result,
			                query_ctx->single.gen,
			                query_ctx->single.req);
			ret = DONE;
			break;
		default:
			goto error;
	}

	PQclear(result);
	return ret;
error:
	yajl_gen_free(query_ctx->single.gen);
	send_error(BAD_GATEWAY, PQresultErrorMessage(result), query_ctx->single.req);
	PQclear(result);
	return DONE;
}

static int on_update_write_ready(db_query_param_t *param, PGconn *db_conn)
{
	multiple_query_ctx_t * const query_ctx = H2O_STRUCT_FROM_MEMBER(multiple_query_ctx_t,
	                                                                single.param,
	                                                                param);
	thread_context_t * const ctx = H2O_STRUCT_FROM_MEMBER(thread_context_t,
	                                                      event_loop.h2o_ctx,
	                                                      query_ctx->single.req->conn->ctx);

	if (query_ctx->num_result == query_ctx->num_query && query_ctx->update_state != COPY_2) {
		const int rc = PQputCopyData(db_conn, H2O_STRLIT(COPY_HEADER));

		if (!rc)
			return 1;
		else if (rc < 0)
			return rc;

		query_ctx->num_result = 0;
		query_ctx->update_state = COPY_2;
	}

	if (query_ctx->num_result < query_ctx->num_query) {
		assert(query_ctx->num_query - query_ctx->num_result <= MAX_QUERIES);

		// There are at most MAX_QUERIES elements, so allocate on the stack.
		struct __attribute__ ((__packed__)) {
			uint16_t field_count;
			uint32_t id_size;
			uint32_t id;
			uint32_t random_number_size;
			uint32_t random_number;
		} data[query_ctx->num_query - query_ctx->num_result];

		memset(&data, 0, sizeof(data));

		for (size_t i = 0; i < query_ctx->num_query; i++) {
			query_ctx->res[i].random_number = get_random_number(MAX_ID, &ctx->random_seed) + 1;
			data[i].field_count = htons(2);
			data[i].id_size = htonl(sizeof(data->id));
			data[i].id = htonl(query_ctx->res[i].id);
			data[i].random_number_size = htonl(sizeof(data->random_number));
			data[i].random_number = htonl(query_ctx->res[i].random_number);
		}

		const int rc = PQputCopyData(db_conn, (const char *) &data, sizeof(data));

		if (!rc)
			return 1;
		else if (rc < 0)
			return rc;

		query_ctx->num_result = query_ctx->num_query;
	}

	if (query_ctx->num_result == query_ctx->num_query) {
		const int rc = PQputCopyEnd(db_conn, NULL);

		if (!rc)
			return 1;
		else if (rc < 0)
			return rc;
	}

	return PQflush(db_conn);
}

static int serialize_item(uint32_t id, uint32_t random_number, yajl_gen gen)
{
	CHECK_YAJL_STATUS(yajl_gen_map_open, gen);
	CHECK_YAJL_STATUS(yajl_gen_string, gen, YAJL_STRLIT(ID_KEY));
	CHECK_YAJL_STATUS(yajl_gen_integer, gen, id);
	CHECK_YAJL_STATUS(yajl_gen_string, gen, YAJL_STRLIT(RANDOM_NUM_KEY));
	CHECK_YAJL_STATUS(yajl_gen_integer, gen, random_number);
	CHECK_YAJL_STATUS(yajl_gen_map_close, gen);
	return EXIT_SUCCESS;
error_yajl:
	return EXIT_FAILURE;
}

static void serialize_items(const query_result_t *res,
                            size_t num_result,
                            yajl_gen gen,
                            h2o_req_t *req)
{
	CHECK_YAJL_STATUS(yajl_gen_array_open, gen);

	for (size_t i = 0; i < num_result; i++)
		if (serialize_item(res[i].id, res[i].random_number, gen))
			goto error_yajl;

	CHECK_YAJL_STATUS(yajl_gen_array_close, gen);

	if (send_json_response(gen, NULL, req)) {
error_yajl:
		yajl_gen_free(gen);
		send_error(INTERNAL_SERVER_ERROR, MEM_ALLOC_ERR_MSG, req);
	}
}

int multiple_queries(struct st_h2o_handler_t *self, h2o_req_t *req)
{
	IGNORE_FUNCTION_PARAMETER(self);

	return do_multiple_queries(NO_UPDATE, req);
}

int single_query(struct st_h2o_handler_t *self, h2o_req_t *req)
{
	IGNORE_FUNCTION_PARAMETER(self);

	thread_context_t * const ctx = H2O_STRUCT_FROM_MEMBER(thread_context_t,
	                                                      event_loop.h2o_ctx,
	                                                      req->conn->ctx);
	single_query_ctx_t * const query_ctx = h2o_mem_alloc_pool(&req->pool, sizeof(*query_ctx));

	if (!query_ctx || initialize_single_query_context(req,
	                                                  on_single_query_result,
	                                                  query_ctx))
		send_error(INTERNAL_SERVER_ERROR, MEM_ALLOC_ERR_MSG, req);
	else {
		query_ctx->id = htonl(get_random_number(MAX_ID, &ctx->random_seed) + 1);

		if (execute_query(ctx, &query_ctx->param)) {
			yajl_gen_free(query_ctx->gen);
			send_service_unavailable_error(DB_REQ_ERROR, req);
		}
	}

	return 0;
}

int updates(struct st_h2o_handler_t *self, h2o_req_t *req)
{
	IGNORE_FUNCTION_PARAMETER(self);

	return do_multiple_queries(CREATE, req);
}


text:
import logging
logger = logging.getLogger(__name__)

import datetime
from random import random, randrange, choice
from math import ceil, floor

from django.db import models
from django.utils import timezone
from model_utils.managers import InheritanceManager

from django.core.exceptions import ValidationError
from slave.logic import AssignmentError, TaskError

from item.models import Item, ItemRecipe
from area.models import Location
from slave.helpers import *
from slave.settings import *

class AssignmentManager(models.Manager):

    def assign(self, task, slave):
        """ Perform the necessary checks and make Assignment """
        # FIXME! This is not a Manager thing to do. Move this to Assignment->create()
        if not slave.get_location().get_region() == task.get_location().get_region():
            raise AssignmentError("Slave in wrong region")

        if not slave.is_free():
            raise AssignmentError("Slave is busy")

        if not task.applicable_for_slave(slave):
            raise AssignmentError("Slave is not trained for this")

    # If Task is not yet saved - do it now.
        if task._state.adding:
            task.save()

        a = Assignment(slave=slave, task=task)
        a.save()

      # Save task again to update estimated date_finish.
        task.save()
        logger.info("User: {0} - Slave: {1} - Task: {2} Successfully assigned with assignment {3}."\
            .format(slave.owner, slave, task, a))
        return True

class TaskManager(models.Manager):
    """ Operations on multiple Tasks """

    def get_finished(self, ttype=None):
        """ Return all finished not yet retrieved tasks """
        if not ttype:
            logger.info("Return all non-retrieved tasks")
            return Task.objects.all().filter(_retrieved=0, date_finish__lte=timezone.now()).all()
        else:
            logger.info("Returning all tasks of type", ttype)
            return Task.objects.all().filter(type=ttype, _retrieved=0, date_finish__lte=timezone.now()).all()

class TaskDirectory(models.Model):
    name   = models.CharField(max_length=127)
    location_type = models.ForeignKey('area.LocationType')
    area_per_worker = models.PositiveIntegerField(default=1)

    min_slaves = models.PositiveIntegerField(default=1)
    max_slaves = models.PositiveIntegerField(default=1)

    primary_skill = models.ForeignKey('skill.Skill', related_name='+')
    secondary_skill   = models.ManyToManyField('skill.Skill', related_name='+')

    #objects = InheritanceManager()

    # FIXME Need some Meta here for exec_time or exec_work to be null. Not together.

    def __str__(self):
        return "{0}: {1}".format(self.get_type_readable(), self.name)

    def get_type(self):
        """ Return list of types relative to TaskType """
        for t in TASK_DIRECTORIES:
            if hasattr(self, t[0]):
                    #print("The type of task is", t[1], t[0])
                    return t[0]
        return False

    def get_type_readable(self):
        """ Return list of types relative to TaskType """
        for t in TASK_DIRECTORIES:
            if hasattr(self, t[0]):
                    #print("The type of task is", t[1], t[0])
                    return t[1]
        return False

    def is_time_fixed(self):
        """ The task is executed some fixed time. """
        # If a subtype has the _exec_time attribute then it has time limit
        try:
            return getattr(self, self.get_type())._exec_time is not None
        except AttributeError:
            return False

    def is_work_fixed(self):
        """ The task needs some fixed work to be done """
        # If a subtype has the work_units attribute then it has work limit
        try:
            return getattr(self, self.get_type()).work_units is not None
        except AttributeError:
            return False

    def get_param(self, param):
        """ Return the requested 'param' of 'itype' child """
        try:
            return getattr(getattr(self, self.get_type()), ('get_' + clean_string_lower(param)))()
        except AttributeError:
            return False

        # The old way looks too complex and didn't catch exceptions
        #itype = self.get_type()
        #print(itype)
        #t = [k[0] for k in TASK_DIRECTORIES if k[0] == itype]
        #if len(t) == 0:
            #raise AttributeError("Invalid attribute 'itype'")

        #this is the old way:
        #child_type = getattr(self, t[0])
        #get_method = getattr(child_type, ('get_' + clean_string_lower(param)))
        #return get_method()

    """ Basic get() methods for TaskDirectory instance properties """
    def get_location_type(self):
        return self.location_type

    def get_area_per_worker(self):
        return self.area_per_worker

    def get_min_slaves(self):
        return self.min_slaves

    def get_max_slaves(self):
        return self.max_slaves

    def get_primary_skill(self):
        if self.primary_skill:
            return self.primary_skill
        else:
            return False

    def get_secondary_skill(self):
        if self.secondary_skill.all().exists():
            return self.secondary_skill.all()
        else:
            return []

class FarmingTaskDirectory(TaskDirectory):
    """ General subtype of farming task types. """

    _yield_item  = models.ForeignKey('item.ItemDirectory')
    _base_yield  = models.PositiveSmallIntegerField(default=1)
    _exec_time   = models.PositiveSmallIntegerField(default=1)

    """ Basic get() methods for FarmingTaskDirectory properties. """
    def get_yield_item(self):
        return self._yield_item

    def get_base_yield(self):
        return self._base_yield

    def get_exec_time(self):
        return self._exec_time

class CraftingTaskDirectory(TaskDirectory):
    """ General subtype of crafting task types. """

    item  = models.ForeignKey('item.ItemDirectory', related_name='yeild_item')
    work_units  = models.PositiveIntegerField(default=1)

    """ Basic get() methods for CraftingTaskDirectory properties. """
    def get_item(self):
        return self.item

    def get_yield_item(self):
        return self.item

    def get_work_units(self):
        return self.work_units

    def get_ingredients(self):
        return self.ingredients.all()

class HarvestingTaskDirectory(TaskDirectory):
    """ General subtype of harvesting task types. """

    item  = models.ForeignKey('item.ItemDirectory', related_name='+')
    work_units  = models.PositiveIntegerField(default=1)

    """ Basic get() methods for CraftingTaskDirectory properties. """
    def get_item(self):
        """ Return the harvested item type. """
        return self.item

    def get_yield_item(self):
        """ Alias for get_item() """
        return self.item

    def get_work_units(self):
        """ Return required work units to harvest the item. """
        return self.work_units

class BuildingTaskDirectory(TaskDirectory):
    """ General subtype of building task types. """

    work_units  = models.PositiveIntegerField(default=1)
    building  = models.ForeignKey('area.LocationDirectory')
#    material  = models.ManyToManyField('item.MaterialDirectory',\
#        through='area.BuildingMaterialRecipe',\
#        through_fields=('task_type', 'material'))

    """ Basic get() methods for CraftingTaskDirectory properties. """
    def __str__(self):
        return str(self.building)

    def get_work_units(self):
        return self.work_units

    def get_building(self):
        return self.building

    def get_yield_building(self):
        return self.building

    def get_ingredients(self):
        """ This is alias of get_materials(). """
#        Different recipes may call the same shit in a different way.
        return self.materials.all()

    def get_materials(self):
        return self.materials.all()

class Task(models.Model):
    date_start  = models.DateTimeField()
    date_finish = models.DateTimeField()
    date_updated = models.DateTimeField()

    _retrieved  = models.BooleanField(default=False)
    _yield      = models.FloatField(default=0.0)
    _fulfilled  = models.FloatField(default=0.0)

    type        = models.ForeignKey(TaskDirectory)
    location    = models.ForeignKey('area.Location', related_name='tasks')
    owner       = models.ForeignKey('auth.User', related_name='tasks')

    objects     = TaskManager()

    def get_test(self):
        pass

    def __str__(self):
        """ Return string name to show Task name in API. """
        return str(self.type)

    def get_name_readable(self):
        """ Return string name to show Task name in API. """
        return str(self.type)

    def get_type(self):
        return self.type

    def get_type_readable(self):
        """ Get type directory (group of types). """
        return self.type.get_type_readable()

    def get_location(self):
        return self.location

    def get_region(self):
        return self.get_location().get_region()

    def get_owner(self):
        return self.owner

    def auth_allowed(self, user):
        """ Check permissions to access object """
        return True if self.get_owner() == user else False

    def is_retrieved(self):
        return self._retrieved

    def is_finished(self):
        return self.get_date_finish() <= timezone.now()

    def get_primary_skill(self):
        return self.type.get_primary_skill()

    def get_secondary_skill(self):
        return self.type.get_secondary_skill()

    def get_date_start(self):
        return self.date_start

    def get_date_finish(self):
        return self.date_finish

    def get_date_updated(self):
        return self.date_updated

    def get_assignments(self, running=False):
        return self.assignments.all() if not running else\
                self.assignments.all().filter(date_released__isnull=True)

    def has_open_vacancy(self):
        """ Returns if there are free working places. """
        return self.get_assignments(running=True).count() < self.get_type().get_max_slaves()

    def has_free_space_in_location(self):
        """ Check if there is free space for more assignments. """
        required_area = self.type.get_area_per_worker()
        available_area = self.get_location().get_free_area()
#        print("Location needs {0} area and currently has {1}.".format(required_area, available_area))
        return available_area >= required_area

    def applicable_for_slave(self, slave):
        """ Check if Slave possesses required skills for this Task """

        ps = self.get_primary_skill()
        ss = self.get_secondary_skill()

        slave_skills = slave.get_trained_skills()

        if ps in list(slave_skills.keys()) and slave_skills[ps] > 0:
            print("The slave posesses primary skill.")
            return True
        elif any(s in list(slave_skills.keys()) and slave_skills[s] > 0 for s in ss):
                print("The slave posesses some secondary skill.")
                return True
        else:
            return False

    def get_farming_yield_item(self):
        return self.get_type().get_param('plant').get_yield_item()

    def get_yield(self):
        return self._yield

    def get_fulfilled(self):
        return self._fulfilled

#######################
# UPDATE PROPERTIES
#######################
    def add_fulfilled(self, amount=0):
        """ Add some work_units when assignment is closed. """
        self._fulfilled += amount

        # Check if finished the task. Then force soon retrieve.
        if self._fulfilled >= self.type.get_param('work_units'):
            self.date_finish = timezone.now()

        self.save()

    def add_yield(self, y=0):
        """ Add some yield results when assignment is closed. """
        if not y:
            return False

        y = fit_to_range_float(y, minv=0)
        if not y:
            raise AttributeError("Yield must be positive float")

        self._yield += y
        self.save()

#######################
# OTHER
#######################
    def save(self, *args, **kwargs):
        """ We save _dates automatically with no need to override """
        self.clean()
        if not self.date_start:
            self.date_start = timezone.now()
##### This is the place to make ON FIRST SAVE actions. #####
            logger.info("First save for task type: {0}".format(self.get_type_readable()))
    ## Crafting task first save
            if self.get_type_readable() == 'Crafting':
                try:
                    self.take_ingredients(amount=1)
                except TaskError as status_message:
                    print("Couldn't save Task due to: {0}".format(status_message))
                    return None
    ## Building task first save
            elif self.get_type_readable() == 'Building':
            # Take materials
            # This is not DRYed because more complex action will
            # come a bit later (tools etc.)
                try:
                    self.take_ingredients(amount=1)
                except TaskError as status_message:
                    print("Couldn't save Task due to: {0}".format(status_message))
                    return None
            # FIXME! Should reserve Region AREA at this point!

        print("Setting date_finish to: {0}".format(self.calculate_date_finish()))
        self.date_finish = self.calculate_date_finish()
        self.date_updated = timezone.now()
        super(Task, self).save(*args, **kwargs)

    def take_ingredients(self, amount=1):
        """ Take ingredients for task from warehouse. """
        # Determine the recipe
        # Get a list of items from Recipe
        ingredients = self.type.get_param('ingredients')

        # Check ingredients
        hq = self.get_region().get_locations('hq').first()
        for i in ingredients:
            if not Item.objects.exists(item=i.ingredient, location=hq, amount=i.amount):
                raise TaskError("ERROR! Not enough ingredient {0}".format(i.ingredient))

        # Take ingredients from the warehouse
        for i in ingredients:
            print("Taking {0} of {1}".format(i.amount, i.ingredient))
            Item.objects.take(item=i.ingredient, location=hq, amount=i.amount)
        return True

    def calculate_date_finish(self):
        """ Automatically calculates estimated finish time of task.
            This is saved to optimize filter for robots """
        ### FIXME Need to complete this function!

      # When the task is finished it also needs to save, so we return now()
        if self._retrieved:
            return timezone.now()

      # If task type has fixed exec time
        if self.type.is_time_fixed():
          # Return time.start + delta of execution
            return self.get_date_start() + \
                datetime.timedelta(seconds=(self.type.get_param('exec_time') * GAME_DAY))

      # Else if type has fixed worker
        elif self.type.is_work_fixed():
#            return timezone.now() + \
#                datetime.timedelta(seconds=(self.type.get_param('work_units') * GAME_DAY))

          # Get remaining amount of work
            work_left = self.type.get_param('work_units') - self.get_fulfilled()

          # Summarize estimated work from all assignments
            current_work_per_day = 0
            running_assignments = self.get_assignments(running=True)
            """print("RUNNING ASSIGNMENTS. Number: {0}. Start first: {1}. Start last: {2}.".format( \
                running_assignments.count(), \
                running_assignments.first().get_date_assigned(), \
                running_assignments.last().get_date_assigned() \
                ))"""
            for a in running_assignments:
              # Calculate estimated work per second
                current_work_per_day += a.get_work_per_day()

#            print("CURRENT_WORK_PER_DAY", current_work_per_day)
          # Calculate remaining GAME_DAYs
            if current_work_per_day > 0:
                days_left = ceil(work_left / current_work_per_day)
            else:
                #days_left = ceil(work_left)
                # We hardcode time here to refresh hung tasks at least once per year.
                days_left = 360

          # Return Estimated time of finish.
          # We take the start time of the first assignment and calculate
          # with estimate work_per_day. In case we add new workers in the
          # middle of the process, we shall receive estimated time
          # earlier than actual finish (even possibly time in the past).
          # This will run automated retriever one extra time and it will
          # add fulfilled work, refresh assignments and recalculate
          # estimates in the proper way.
            if running_assignments.count() > 0:
                last_saved_time = running_assignments.first().get_date_assigned()
            else:
                last_saved_time = timezone.now()

            return last_saved_time + datetime.timedelta(seconds=(days_left * GAME_DAY))

    def clean(self):
        """ Check the location type vs required one for this type of task """
        if not self.get_location().get_type() == self.get_type().get_location_type():
            raise AssignmentError("Wrong type of location")

    def retrieve(self):
        logger.info("Task: {0} - Retrieving.".format(self))

        if not self.is_finished():
            raise TaskError("Task is not finished yet.")

        if self.is_retrieved():
            raise TaskError("Task was already retrieved.")

        #print("Cancelling assignments")
        current_assignments = self.get_assignments(running=True)
      # In case we did not yet finish, we shall assign the same slaves again.
        previous_slaves = []
        if len(current_assignments) > 0:
            for a in current_assignments:
                #print("{0} is released".format(a.get_slave()))
                previous_slaves.append(a.get_slave())
                a.release()
        else:
            logger.info("Task: {0} - No Assignments to release.".format(self))

##########
#        print("Retrieving yield")

        if str(self.type.get_type()) == 'farmingtaskdirectory':
            self._retrieved = True
            self.finish_farming()

        elif str(self.type.get_type()) == 'craftingtaskdirectory':
          # Check if not all of the required work is finished.
            logger.info("Task: {0} - Fullfilled {1} of {2}".format(self, self.get_fulfilled(),
                self.type.craftingtaskdirectory.get_work_units()))
            if self.get_fulfilled() < self.type.craftingtaskdirectory.get_work_units():
                #print("Previous Slaves: {0}".format(previous_slaves))
                for s in previous_slaves:
                    logger.info("Task: {0} - Reassigning Slave {1}.".format(self, s))
                    Assignment.objects.assign(task=self, slave=s)
          # Otherwise finish the task
            else:
                self._retrieved = True
                self.finish_crafting()

        elif str(self.type.get_type()) == 'harvestingtaskdirectory':
          # Check if not all of the required work is finished.
            logger.info("Task: {0} - Fullfilled {1} of {2}".format(self, self.get_fulfilled(),
                self.type.harvestingtaskdirectory.get_work_units()))
            if self.get_fulfilled() < self.type.harvestingtaskdirectory.get_work_units():
                #print("Previous Slaves: {0}".format(previous_slaves))
                for s in previous_slaves:
                    logger.info("Task: {0} - Reassigning Slave {1}.".format(self, s))
                    Assignment.objects.assign(task=self, slave=s)
          # Otherwise finish the task
            else:
                self._retrieved = True
                self.finish_harvesting()

        elif str(self.type.get_type()) == 'buildingtaskdirectory':
          # Check if not all of the required work is finished.
            if self.get_fulfilled() < self.type.buildingtaskdirectory.get_work_units():
                for s in previous_slaves:
                    print("Reassigning Slave {0} to Task {1}".format(s, self))
                    Assignment.objects.assign(task=self, slave=s)
          # Otherwise finish the task
            else:
                self._retrieved = True
                self.finish_building()

        self.save()
        return True

    def finish_farming(self):
        """ Put to warehouse farmed goods. """
        print("FINISH FARMING")
        amount_produced = 0
        item_produced = self.get_type().get_param('yield_item')
        warehouse = self.get_region().get_locations('hq').first()

      # To get base amount produced the amount of fulfilled work  must be equal
      # to base duration multiplied by PRIMARY_SKILL_WORK_VALUE * 100%
        base_work = self.get_type().get_param('exec_time')
        work_fulfilled = self.get_fulfilled() / base_work
        amount_produced = int(work_fulfilled * self.get_type().get_param('base_yield'))

        logger.info("Task: {0} - Produced {1} work resulting in {2} of {3}".format(self, work_fulfilled, amount_produced, item_produced))

        try:
            Item.objects.put(item=item_produced, location=warehouse, amount=amount_produced)
        except Exception:
            logger.info("ERROR! Task: {0} - Some shit while putting crafted item to warehouse.".format(self))

    def finish_crafting(self):
        """ Put to warehouse crafted items. """
#        print("FINISH CRAFTING")
#        amount_produced = floor(self.get_fulfilled() // self.get_type().get_param('work_units'))
    # We need to take ingredients in case we have occasionally
    # produced more then 1 amount. This is not ready, so we fix amount to 1.
        amount_produced = 1
        item_produced = self.get_type().get_param('yield_item')
        work_fulfilled = self.get_fulfilled()
        warehouse = self.get_region().get_locations('hq').first()

        logger.info("Task: {0} - Produced {1} work resulting in {2} of {3}".format(self, work_fulfilled, amount_produced, item_produced))

    # Now put to warehouse
        try:
            Item.objects.put(item=item_produced, location=warehouse, amount=amount_produced)
        except Exception:
            logger.info("ERROR! Task: {0} - Some shit while putting crafted item to warehouse.".format(self))

    def finish_harvesting(self):
        """ Put to warehouse harvested items. """
        work_fulfilled = self.get_fulfilled()
        amount_produced = floor(work_fulfilled // self.get_type().get_param('work_units'))
        item_produced = self.get_type().get_param('yield_item')
        warehouse = self.get_region().get_locations('hq').first()

        logger.info("Task: {0} - Produced {1} work resulting in {2} of {3}".format(self, work_fulfilled, amount_produced, item_produced))

    # Now put to warehouse
        try:
            Item.objects.put(item=item_produced, location=warehouse, amount=amount_produced)
        except Exception:
            logger.info("ERROR! Task: {0} - Some shit while putting crafted item to warehouse.".format(self))

    def finish_building(self):
        """ Place new Location. """
        # This is the first draft version. We do not reserve area for location in advance.
        # We simply create new Location in Region now.
        print("FINISH BUILDING")

        region = self.get_region()
        building_type = self.get_type().get_param('yield_building')
        name = self.generate_location_name(building_type)
        print("Creating {0} in {1}".format(building_type, region))

        new_location = Location.objects.create(name=name, region=region, design=building_type)

        print("Created {0} in {1}".format(new_location, region))

    def generate_location_name(self, design):
        """ Generates a new name for location. """
        number_of_locations = self.get_region().get_locations(design=design).count()
        return "{0} #{1}".format(str(design), str(number_of_locations+1))

        """def get_yield_farming(self, strict=False):
    # FIXME TO BE REMOVED FROM HERE!
        "" There can be several primary and secondary skills.
        The functions calculates the part of each one and the total output.
        Primary skill = 50%, Secondary split by number. This results in base_yield.
        Bonuses may add extra. ""

        print("Trying to yield from farming task")
        ps = self.get_type().get_primary_skill()
        ss = self.get_type().get_secondary_skill()

        print("Now task specific stuff")
        cummulative_result = 0
        for a in self.get_assignments():
            a.release()

            slave_skills = a.get_slave().get_trained_skills()
#           sec_sl_skills = (self.slave.get_skills(*ss))
            print("Slave %s posesses:" % (str(a.get_slave())),  slave_skills)

            print("Comparing:", ps, list(slave_skills.keys()))

            if ps not in list(slave_skills.keys()) or slave_skills[ps] == 0:
                print("The slave doesn't posess primary skill. Looking for secondaries")
                slave_skills[ps] = 0 # Should be set by Slave obj, but this is for safety
                if not any(s in list(slave_skills.keys()) and slave_skills[s] > 0 for s in ss):

                     print("The slave doesn't posess required skills. There is no yield!")
                     return 0

            result = 0
            by = self.get_type().farmingtaskdirectory.get_plant().get_base_yield()
            print("Base yield: {0}".format(by))
            result += (by * (slave_skills[ps] / 100.0) * PRIMARY_SKILL_WORK_VALUE)
#            print(slave_skills[ps])
#            print((slave_skills[ps] / 100.0) * PRIMARY_SKILL_FARMING_VALUE)
            print("Primary skill harvested: {0}".format(result))

            ss_part = SECONDARY_SKILLS_WORK_VALUE / ss.count()

            for s in ss:
                if s in list(slave_skills.keys()) and slave_skills[s] > 0:
                    result += (by * (slave_skills[s] / 100.0) * ss_part)
#                    print(slave_skills[s])
#                    print((slave_skills[s] / 100.0) * ss_part)
                    print("Secondary skill {0} added some yield with result: {1}".format(s, result))

            if not strict:
                result += (result * (randrange(-YIELD_RANDOMIZER, YIELD_RANDOMIZER) / 100.0))
            print("Slave %s added %s to cummulative result" % (str(a.get_slave()), str(result)))
            cummulative_result += result

        return (self.get_type().farmingtaskdirectory.get_plant().get_yield_item(), cummulative_result)

    def get_yield_crafting(self):
        pass """

class Assignment(models.Model):
    """ This class controls assignments of Slaves to Tasks. """
    task     = models.ForeignKey(Task, related_name='assignments')
    slave    = models.ForeignKey('slave.Slave', related_name='assignments')

    date_assigned = models.DateTimeField()
    date_released = models.DateTimeField(null=True)

    objects = AssignmentManager()

    class Meta:
        unique_together = (("slave", "date_released"),)

    def get_task(self):
        return self.task

    def get_slave(self):
        return self.slave

    def get_date_assigned(self):
        return self.date_assigned

    def get_date_released(self):
        return self.date_released

    def get_duration(self):
        """ Returns the actual "working" duration.
            Could be shorter than nominal duration as there might be some lag with releasing. """
        return min(timezone.now(), self.get_date_released(), self.get_task().get_date_finish())  - self.get_date_assigned()

    def is_running(self):
        return False if self.date_released else True

    def get_estimated_yield(self):
        return " - "

    def save(self, *args, **kwargs):
        self.clean()
        if not self.date_assigned:
            self.date_assigned = timezone.now()
            logger.info("Assignment: {0} - Creating new with date: {1}.".format(self.id, self.date_assigned))

        super(Assignment, self).save(*args, **kwargs)
        logger.info("Assignment: {0} - Saved with date: {1}.".format(self.id, self.date_assigned))

    def clean(self):
        """ Check if Assignment is going to be valid """
        # We check if_running to skip this verification
        # while saving on assignment.release()
        if not self.task.has_open_vacancy() and self.is_running():
            raise AssignmentError("Too many slaves for this task")

        if not self.task.has_free_space_in_location() and self.is_running():
            raise AssignmentError("There is no free space in Location of this task")

    def release(self):
        """ Releasing the Slave from Assignment (and closing the Assignment).
        Yield and production are calculated here. Slave new Experience also. """
    # Check if Assignment is not released already
        if not self.is_running():
            logger.warning("Assignment {0} - Already released.".format(self))
            return False

        # Now the duration will count till this date_released point.
        # In case of bugs your may need to extra save() here.
        self.date_released = timezone.now()

    ### Updating slave Skill Experience
        # We use all skills available for the Slave at the moment.
        # And for any of them he will get some experience
        slave_skills = self.get_slave().get_available_skills()
        ps = self.task.get_primary_skill()
        ss = self.task.get_secondary_skill()

        # We use only full Game days. If the assignment was shorter
        # - no training and no fulfilled work happens.
        # This should prevent any possible short assignments bugs.
        # We also ensure that duration is positive.
        duration = max(0, (datetime.timedelta.total_seconds(self.get_duration()) / GAME_DAY))
        print("The total duration of assignment was {0} GAME DAYS".format(duration))

      # WORK REQUIRED
      # Eexperience should also depend on other more skilled slaves working simultaneously.
        # Experience directly depends on assignment duration
        exp  = int(duration * BASE_EXP_PER_DAY)
        # The part of each secondary skill output depends on their number.
        exp_for_secondary_skill = int((duration * SECONDARY_SKILLS_EXP_PER_DAY) / ss.count())

        # Adding exp for Primary Skill.
        if ps in slave_skills:
            logger.debug("{0} gained {1} experience for {2}".format(self.get_slave(), exp, ps))
            self.slave.add_skill_exp(ps, exp)

        for s in ss:
            if s in slave_skills:
                logger.debug("{0} gained {1} experience for {2}".format(self.slave, exp_for_secondary_skill, s))
                self.slave.add_skill_exp(s, exp_for_secondary_skill)

        # Calculate and update work_units for parent Task.
        #logger.debug(duration, self.get_work_per_day())
        assignment_work = duration * self.get_work_per_day()
        logger.debug("Total work produced by Assignment is: {0}".format(assignment_work))

        self.task.add_fulfilled(amount=assignment_work)
        self.save()
        logger.info("Assignment: {0} - Released. Produced {1} of work for task {2}.".format(self.id, assignment_work, self.task.id))
        return True

    def get_work_per_day(self):
        """ Return the amount of work per minimum assignment time unit (GAME_DAY). """

        ps = self.task.get_primary_skill()
        ss = self.task.get_secondary_skill()
        slave_skills = self.get_slave().get_available_skills()

        assignment_work = 0.0
      # Calculate result work for Primary skill
        if ps in slave_skills:

            skill_level = self.get_slave().get_skill(ps)
            assignment_work += skill_level * 0.01 * PRIMARY_SKILL_WORK_VALUE
            # print("Skill {0} produced {1} of work units".format(ps, skill_work))

      # The part of each secondary skill output depends on their number
        part_of_secondary_skill = SECONDARY_SKILLS_WORK_VALUE / ss.count()

      # Calculate result work for Secondary skills
        for s in ss:
            if s in slave_skills:
                skill_level = self.get_slave().get_skill(s)
                assignment_work += skill_level * 0.01 * part_of_secondary_skill
                # print("Skill {0} produced {1} of work units".format(s, skill_work))

        return assignment_work


text:
package tachyon.client;

import java.io.IOException;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import tachyon.TestUtils;
import tachyon.master.LocalTachyonCluster;

/**
 * Unit tests for tachyon.client.RemoteBlockInStream.
 */
public class RemoteBlockInStreamTest {
  private final int MIN_LEN = 0;
  private final int MAX_LEN = 255;
  private final int DELTA = 33;

  private LocalTachyonCluster mLocalTachyonCluster = null;
  private TachyonFS mTfs = null;

  @After
  public final void after() throws Exception {
    mLocalTachyonCluster.stop();
    System.clearProperty("tachyon.user.quota.unit.bytes");
    System.clearProperty("tachyon.user.remote.read.buffer.size.byte");
  }

  @Before
  public final void before() throws IOException {
    System.setProperty("tachyon.user.quota.unit.bytes", "1000");
    System.setProperty("tachyon.user.remote.read.buffer.size.byte", "100");
    mLocalTachyonCluster = new LocalTachyonCluster(10000);
    mLocalTachyonCluster.start();
    mTfs = mLocalTachyonCluster.getClient();
  }

  /**
   * Test void read(). Read from underfs.
   */
  @Test
  public void readTest1() throws IOException {
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.NO_CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      byte[] ret = new byte[k];
      int value = is.read();
      int cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt ++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      if (k == 0) {
        Assert.assertTrue(file.isInMemory());
      } else {
        Assert.assertFalse(file.isInMemory());
      }

      is = file.getInStream(ReadType.CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      ret = new byte[k];
      value = is.read();
      cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt ++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());

      is = file.getInStream(ReadType.CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof LocalBlockInStream);
      }
      ret = new byte[k];
      value = is.read();
      cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt ++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());
    }
  }

  /**
   * Test void read(byte b[]). Read from underfs.
   */
  @Test
  public void readTest2() throws IOException {
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.NO_CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      byte[] ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      if (k == 0) {
        Assert.assertTrue(file.isInMemory());
      } else {
        Assert.assertFalse(file.isInMemory());
      }

      is = file.getInStream(ReadType.CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());

      is = file.getInStream(ReadType.CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof LocalBlockInStream);
      }
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());
    }
  }

  /**
   * Test void read(byte[] b, int off, int len). Read from underfs.
   */
  @Test
  public void readTest3() throws IOException {
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.NO_CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      byte[] ret = new byte[k / 2];
      Assert.assertEquals(k / 2, is.read(ret, 0, k / 2));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k / 2, ret));
      is.close();
      if (k == 0) {
        Assert.assertTrue(file.isInMemory());
      } else {
        Assert.assertFalse(file.isInMemory());
      }

      is = file.getInStream(ReadType.CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret, 0, k));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());

      is = file.getInStream(ReadType.CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof LocalBlockInStream);
      }
      ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());
    }
  }

  /**
   * Test void read(). Read from remote data server.
   */
  @Test
  public void readTest4() throws IOException {
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.MUST_CACHE;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      RemoteBlockInStream is = new RemoteBlockInStream(file, ReadType.NO_CACHE, 0);
      Assert.assertTrue(is instanceof RemoteBlockInStream);
      byte[] ret = new byte[k];
      int value = is.read();
      int cnt = 0;
      while (value != -1) {
        Assert.assertTrue(value >= 0);
        Assert.assertTrue(value < 256);
        ret[cnt ++] = (byte) value;
        value = is.read();
      }
      Assert.assertEquals(cnt, k);
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      is.close();
      Assert.assertTrue(file.isInMemory());
    }
  }

  /**
   * Test void read(byte b[]). Read from remote data server.
   */
  @Test
  public void readTest5() throws IOException {
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.MUST_CACHE;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = new RemoteBlockInStream(file, ReadType.NO_CACHE, 0);
      Assert.assertTrue(is instanceof RemoteBlockInStream);
      byte[] ret = new byte[k];
      int start = 0;
      while (start < k) {
        int read = is.read(ret);
        Assert.assertTrue(TestUtils.equalIncreasingByteArray(start, read, ret));
        start += read;
      }
      is.close();
      Assert.assertTrue(file.isInMemory());
    }
  }

  /**
   * Test void read(byte[] b, int off, int len). Read from remote data server.
   */
  @Test
  public void readTest6() throws IOException {
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.MUST_CACHE;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = new RemoteBlockInStream(file, ReadType.NO_CACHE, 0);
      Assert.assertTrue(is instanceof RemoteBlockInStream);
      byte[] ret = new byte[k / 2];
      int start = 0;
      while (start < k / 2) {
        int read = is.read(ret, 0, (k / 2) - start);
        Assert.assertTrue(TestUtils.equalIncreasingByteArray(start, read, ret));
        start += read;
      }
      is.close();
      Assert.assertTrue(file.isInMemory());
    }
  }

  /**
   * Test void read(byte b[]). Read from underfs.
   */
  @Test
  public void readTest7() throws IOException {
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.NO_CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }
      byte[] ret = new byte[k];
      Assert.assertEquals(k, is.read(ret));
      Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
      Assert.assertEquals(-1, is.read(ret));
      is.close();
      Assert.assertFalse(file.isInMemory());
    }
  }

  /**
   * Test void seek(long pos).
   *
   * @throws IOException
   */
  @Test
  public void seekExceptionTest() throws IOException {
    for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.NO_CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }

      try {
        is.seek(-1);
      } catch (IOException e) {
        // This is expected
        continue;
      }
      is.close();
      throw new IOException("Except seek IOException");
    }
  }

  /**
   * Test void seek(long pos).
   *
   * @throws IOException
   */
  @Test
  public void seekTest() throws IOException {
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.NO_CACHE);
      if (k == 0) {
        Assert.assertTrue(is instanceof EmptyBlockInStream);
      } else {
        Assert.assertTrue(is instanceof RemoteBlockInStream);
      }

      Assert.assertEquals(0, is.read());
      is.seek(k / 3);
      Assert.assertEquals(k / 3, is.read());
      is.seek(k / 2);
      Assert.assertEquals(k / 2, is.read());
      is.seek(k / 4);
      Assert.assertEquals(k / 4, is.read());
      is.close();
    }
  }

  /**
   * Test long skip(long len).
   */
  @Test
  public void skipTest() throws IOException {
    for (int k = MIN_LEN + DELTA; k <= MAX_LEN; k += DELTA) {
      WriteType op = WriteType.THROUGH;
      int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);

      TachyonFile file = mTfs.getFile(fileId);
      InStream is = file.getInStream(ReadType.CACHE);
      Assert.assertTrue(is instanceof RemoteBlockInStream);
      Assert.assertEquals(k / 2, is.skip(k / 2));
      Assert.assertEquals(k / 2, is.read());
      is.close();
      Assert.assertFalse(file.isInMemory());

      if (k >= 3) {
        is = file.getInStream(ReadType.CACHE);
        Assert.assertTrue(is instanceof RemoteBlockInStream);
        int t = k / 3;
        Assert.assertEquals(t, is.skip(t));
        Assert.assertEquals(t, is.read());
        Assert.assertEquals(t, is.skip(t));
        Assert.assertEquals(2 * t + 1, is.read());
        is.close();
        Assert.assertFalse(file.isInMemory());
      }
    }
  }
}


text:
package org.apereo.portal.concurrency;

import org.apereo.portal.EntityIdentifier;

/**
 * Defines an api for acquiring lock objects, IEntityLocks, that can be used to control
 * concurrent access to portal entities. A lock is associated with a particular entity and has an
 * owner, a lockType and a service-controlled expirationTime.
 * Currently supported lock types are READ_LOCK and WRITE_LOCK.
 *
 *
If I want to lock an entity for update, I ask the service for a write lock:
 *
 *
int lockType = IEntityLockService.WRITE_LOCK;

 *       EntityIdentifier eid = myEntity.getEntityIdentifier();

 *       IEntityLock lock = svc.newLock(eid, lockType, lockOwner);
 *
 *
If there is no conflicting lock on the entity, the service responds with the requested lock.
 * If I acquire the lock, I know that no other client will get be able to get a conflicting lock.
 * From then on, I communicate with the service via the lock:
 *
 *

 *   lock.convert(int newType);

 *   lock.isValid();

 *   lock.release();

 *   lock.renew();

 *
 *
 *
A READ lock guarantees repeatable reads; other clients can get READ locks but not WRITE locks.
 * A WRITE lock guarantees exclusive access; no other clients can get either READ or WRITE locks on
 * the entity.
 *
 *
NB: since the locking service is not part of a transactional or object persistence framework,
 * it has no way to enforce its own use.
 *
 * @author Dan Ellentuck
 */
public interface IEntityLockService {

    // The different types of locks:
    public static int READ_LOCK = 0;
    public static int WRITE_LOCK = 1;

    /**
     * Attempts to change the lock's lockType to newType.
     *
     * @param lock IEntityLock
     * @param newType int
     * @exception LockingException
     */
    public void convert(IEntityLock lock, int newType) throws LockingException;
    /**
     * Attempts to change the lock's lockType to newType.
     *
     * @param lock IEntityLock
     * @param newType int
     * @param newDuration int
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public void convert(IEntityLock lock, int newType, int newDuration) throws LockingException;
    /**
     * Answer if this IEntityLock exists in the store.
     *
     * @return boolean
     * @param lock
     */
    public boolean existsInStore(IEntityLock lock) throws LockingException;
    /**
     * Answers if this IEntityLock represents a lock that is still good. To be valid, a
     * lock must exist in the underlying store and be unexpired and unreleased.
     *
     * @param lock IEntityLock
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public boolean isValid(IEntityLock lock) throws LockingException;
    /**
     * Returns a lock for the entity, lock type and owner.
     *
     * @return org.apereo.portal.concurrency.IEntityLock
     * @param entityType Class
     * @param entityKey String
     * @param lockType int
     * @param owner String
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public IEntityLock newLock(Class entityType, String entityKey, int lockType, String owner)
            throws LockingException;
    /**
     * Returns a lock for the entity, lock type and owner.
     *
     * @return org.apereo.portal.concurrency.IEntityLock
     * @param entityType Class
     * @param entityKey String
     * @param lockType int
     * @param owner String
     * @param durationSecs int
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public IEntityLock newLock(
            Class entityType, String entityKey, int lockType, String owner, int durationSecs)
            throws LockingException;
    /**
     * Returns a lock for the entity, lock type and owner.
     *
     * @return org.apereo.portal.concurrency.IEntityLock
     * @param entityID EntityIdentifier
     * @param lockType int
     * @param owner String
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public IEntityLock newLock(EntityIdentifier entityID, int lockType, String owner)
            throws LockingException;
    /**
     * Returns a lock for the entity, lock type and owner.
     *
     * @return org.apereo.portal.concurrency.IEntityLock
     * @param entityID EntityIdentifier
     * @param lockType int
     * @param owner String
     * @param durationSecs int
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public IEntityLock newLock(
            EntityIdentifier entityID, int lockType, String owner, int durationSecs)
            throws LockingException;

    /**
     * Releases the IEntityLock.
     *
     * @param lock IEntityLock
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public void release(IEntityLock lock) throws LockingException;

    /**
     * Extends the expiration time of the lock by the default increment.
     *
     * @param lock IEntityLock
     * @exception org.apereo.portal.concurrency.LockingException
     */
    public void renew(IEntityLock lock) throws LockingException;

    /**
     * Extends the expiration time of the lock by duration seconds.
     *
     * @param lock IEntityLock
     * @param duration
     * @exception LockingException
     */
    public void renew(IEntityLock lock, int duration) throws LockingException;
}


text: module.exports = require('./src/datetime-picker.vue');


text:
namespace LeelooFramework
{

AppFramework::AppFramework()
{
}
AppFramework::~AppFramework()
{
}
Leeloo::Ret AppFramework::Start(void)
{
    Leeloo::Global::SetRun();
    Leeloo::ConfigSingleton::Instance().ReadConfig("config.txt");
    Leeloo::LogSingleton::Instance();
    ;
	return Leeloo::SUCCESS;
}
Leeloo::Ret AppFramework::Run(void)
{
	std::string strInput;
	std::cout << "input q, exit program" << std::endl;
    while(Leeloo::Global::IsRun())
	{
		std::cin >> strInput;
		if(strInput.compare("q") == 0)
			break;
	}
	return Leeloo::SUCCESS;
}
Leeloo::Ret AppFramework::End(void)
{
    Leeloo::Global::SetStop();
	;
    Leeloo::LogSingleton::Deinstance();
    Leeloo::ConfigSingleton::Deinstance();
	return Leeloo::SUCCESS;
}

}


text:
package org.apache.kylin.rest.security;

import org.apache.kylin.common.persistence.RootPersistentEntity;
import org.apache.kylin.cube.CubeInstance;
import org.apache.kylin.job.JobInstance;
import org.apache.kylin.metadata.model.DataModelDesc;
import org.apache.kylin.metadata.project.ProjectInstance;

/**
 * @author xduo
 */
public class AclEntityFactory implements AclEntityType {

    public static RootPersistentEntity createAclEntity(String entityType, String uuid) {
        if (CUBE_INSTANCE.equals(entityType)) {
            CubeInstance cubeInstance = new CubeInstance();
            cubeInstance.setUuid(uuid);

            return cubeInstance;
        }

        if (DATA_MODEL_DESC.equals(entityType)) {
            DataModelDesc modelInstance = new DataModelDesc();
            modelInstance.setUuid(uuid);

            return modelInstance;
        }

        if (JOB_INSTANCE.equals(entityType)) {
            JobInstance jobInstance = new JobInstance();
            jobInstance.setUuid(uuid);

            return jobInstance;
        }

        if (PROJECT_INSTANCE.equals(entityType)) {
            ProjectInstance projectInstance = new ProjectInstance();
            projectInstance.setUuid(uuid);

            return projectInstance;
        }

        throw new RuntimeException("Unsupported entity type!");
    }
}


text:
from twisted.python import usage
from automatron.controller.controller import Controller

class Options(usage.Options):
    optParameters = [
        ['config', 'C', 'automatron.ini', 'Configuration file'],
    ]

def makeService(options):
    return Controller(options['config'])


text:
package com.sarality.app.datastore.query;

/**
 * Operator in a Where Clause of a {@link Query}.
 *
 * @author abhideep@ (Abhideep Singh)
 */
public enum Operator {
  EQUALS("="),
  NOT_EQUALS("!="),
  LESS_THAN("<"),
  GREATER_THAN(">"),
  IS_NULL("IS NULL"),
  IS_NOT_NULL("IS NOT NULL"),
  LIKE("LIKE"),
  IN("IN");

  private final String sqlString;

  private Operator(String sqlString) {
    this.sqlString = sqlString;
  }

  public String getSqlString() {
    return sqlString;
  }
}


text:
{{project.name}}

    <project-editor>Example Text</project-editor>


text:
	N/A

			{{ labelLogStats.calculated.estimatedMax | number:0 }}
			{{ labelLogStats.weight }} x {{ labelLogStats.reps }}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MysticReference.Forms
{
    public partial class CreateSpellBook : Form
    {
        public string BookName { get; private set; }

        public CreateSpellBook()
        {
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("Please enter a name for the new spell book.", "Invalid Name",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                DialogResult = DialogResult.OK;
                BookName = txtName.Text;
                Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}


text:
package org.apache.commons.imaging.formats.tiff.constants;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.imaging.formats.tiff.taginfos.TagInfo;
import org.apache.commons.imaging.formats.tiff.taginfos.TagInfoAscii;
import org.apache.commons.imaging.formats.tiff.taginfos.TagInfoDouble;
import org.apache.commons.imaging.formats.tiff.taginfos.TagInfoShort;

/**
 * Geo Tiff.
 * <BR>
 * http://www.remotesensing.org/geotiff/spec/contents.html
 */
public interface GeoTiffTagConstants {
    TagInfoDouble EXIF_TAG_MODEL_PIXEL_SCALE_TAG = new TagInfoDouble(
            "ModelPixelScaleTag", 0x830e, 3,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    TagInfoDouble EXIF_TAG_INTERGRAPH_MATRIX_TAG = new TagInfoDouble(
            "IntergraphMatrixTag", 0x8480, -1,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    TagInfoDouble EXIF_TAG_MODEL_TIEPOINT_TAG = new TagInfoDouble(
            "ModelTiepointTag", 0x8482, -1,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    TagInfoDouble EXIF_TAG_MODEL_TRANSFORMATION_TAG = new TagInfoDouble(
            "ModelTransformationTag", 0x85d8, 16,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    TagInfoShort EXIF_TAG_GEO_KEY_DIRECTORY_TAG = new TagInfoShort(
            "GeoKeyDirectoryTag", 0x87af, -1,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    TagInfoDouble EXIF_TAG_GEO_DOUBLE_PARAMS_TAG = new TagInfoDouble(
            "GeoDoubleParamsTag", 0x87b0, -1,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    TagInfoAscii EXIF_TAG_GEO_ASCII_PARAMS_TAG = new TagInfoAscii(
            "GeoAsciiParamsTag", 0x87b1, -1,
            TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN);

    List<TagInfo> ALL_GEO_TIFF_TAGS =
            Collections.unmodifiableList(Arrays.asList(
                    EXIF_TAG_MODEL_PIXEL_SCALE_TAG,
                    EXIF_TAG_INTERGRAPH_MATRIX_TAG,
                    EXIF_TAG_MODEL_TIEPOINT_TAG,
                    EXIF_TAG_MODEL_TRANSFORMATION_TAG,
                    EXIF_TAG_GEO_KEY_DIRECTORY_TAG,
                    EXIF_TAG_GEO_DOUBLE_PARAMS_TAG,
                    EXIF_TAG_GEO_ASCII_PARAMS_TAG));

}