text:
package local

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"os"
	"path"
	"strconv"
	"time"

	"github.com/nuclio/nuclio/pkg/cmdrunner"
	"github.com/nuclio/nuclio/pkg/common"
	"github.com/nuclio/nuclio/pkg/containerimagebuilderpusher"
	"github.com/nuclio/nuclio/pkg/dockerclient"
	"github.com/nuclio/nuclio/pkg/functionconfig"
	"github.com/nuclio/nuclio/pkg/opa"
	"github.com/nuclio/nuclio/pkg/platform"
	"github.com/nuclio/nuclio/pkg/platform/abstract"
	"github.com/nuclio/nuclio/pkg/platform/abstract/project"
	externalproject "github.com/nuclio/nuclio/pkg/platform/abstract/project/external"
	"github.com/nuclio/nuclio/pkg/platform/abstract/project/internalc/local"
	"github.com/nuclio/nuclio/pkg/platform/local/client"
	"github.com/nuclio/nuclio/pkg/platformconfig"
	"github.com/nuclio/nuclio/pkg/processor"

	"github.com/ghodss/yaml"
	"github.com/nuclio/errors"
	"github.com/nuclio/logger"
	"github.com/nuclio/nuclio-sdk-go"
	"github.com/nuclio/zap"
)

type Platform struct {
	*abstract.Platform
	cmdRunner      cmdrunner.CmdRunner
	dockerClient   dockerclient.Client
	localStore     *client.Store
	projectsClient project.Client
}

const Mib = 1048576
const FunctionProcessorContainerDirPath = "/etc/nuclio/config/processor"

func NewProjectsClient(platform *Platform, platformConfiguration *platformconfig.Config) (project.Client, error) {

	// create local projects client
	localProjectsClient, err := local.NewClient(platform.Logger, platform, platform.localStore)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create internal projects client (local)")
	}

	if platformConfiguration.ProjectsLeader != nil {

		// wrap external client around local projects client as internal client
		return externalproject.NewClient(platform.Logger, localProjectsClient, platformConfiguration)
	}

	return localProjectsClient, nil
}

// NewPlatform instantiates a new local platform
func NewPlatform(ctx context.Context,
	parentLogger logger.Logger,
	platformConfiguration *platformconfig.Config,
	defaultNamespace string) (*Platform, error) {
	newPlatform := &Platform{}

	// create base
	newAbstractPlatform, err := abstract.NewPlatform(parentLogger, newPlatform, platformConfiguration, defaultNamespace)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create an abstract platform")
	}

	// init platform
	newPlatform.Platform = newAbstractPlatform

	// create a command runner
	if newPlatform.cmdRunner, err = cmdrunner.NewShellRunner(newPlatform.Logger); err != nil {
		return nil, errors.Wrap(err, "Failed to create a command runner")
	}

	if newPlatform.ContainerBuilder, err = containerimagebuilderpusher.NewDocker(newPlatform.Logger,
		platformConfiguration.ContainerBuilderConfiguration); err != nil {
		return nil, errors.Wrap(err, "Failed to create containerimagebuilderpusher")
	}

	// create a docker client
	if newPlatform.dockerClient, err = dockerclient.NewShellClient(newPlatform.Logger, nil); err != nil {
		return nil, errors.Wrap(err, "Failed to create a Docker client")
	}

	// create a local store for configs and stuff
	if newPlatform.localStore, err = client.NewStore(parentLogger, newPlatform, newPlatform.dockerClient); err != nil {
		return nil, errors.Wrap(err, "Failed to create a local store")
	}

	// create projects client
	newPlatform.projectsClient, err = NewProjectsClient(newPlatform, platformConfiguration)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create projects client")
	}

	// ignite goroutine to check function container healthiness
	if newPlatform.Config.Local.FunctionContainersHealthinessEnabled {
		newPlatform.Logger.DebugWithCtx(ctx, "Igniting container healthiness validator")
		go func(newPlatform *Platform) {
			uptimeTicker := time.NewTicker(newPlatform.Config.Local.FunctionContainersHealthinessInterval)
			defer uptimeTicker.Stop()
			for range uptimeTicker.C {
				newPlatform.ValidateFunctionContainersHealthiness(ctx)
			}
		}(newPlatform)
	}
	return newPlatform, nil
}

func (p *Platform) Initialize(ctx context.Context) error {
	if err := p.projectsClient.Initialize(); err != nil {
		return errors.Wrap(err, "Failed to initialize projects client")
	}

	// ensure default project existence only when projects aren't managed by external leader
	if p.Config.ProjectsLeader == nil {
		if err := p.EnsureDefaultProjectExistence(ctx); err != nil {
			return errors.Wrap(err, "Failed to ensure default project existence")
		}
	}

	return nil
}

// CreateFunction will simply run a docker image
func (p *Platform) CreateFunction(ctx context.Context, createFunctionOptions *platform.CreateFunctionOptions) (
	*platform.CreateFunctionResult, error) {
	var err error
	var existingFunctionConfig *functionconfig.ConfigWithStatus

	if err := p.enrichAndValidateFunctionConfig(ctx, &createFunctionOptions.FunctionConfig); err != nil {
		return nil, errors.Wrap(err, "Failed to enrich and validate a function configuration")
	}

	// Check OPA permissions
	permissionOptions := createFunctionOptions.PermissionOptions
	permissionOptions.RaiseForbidden = true
	if _, err := p.QueryOPAFunctionPermissions(createFunctionOptions.FunctionConfig.Meta.Labels[common.NuclioResourceLabelKeyProjectName],
		createFunctionOptions.FunctionConfig.Meta.Name,
		opa.ActionCreate,
		&permissionOptions); err != nil {
		return nil, errors.Wrap(err, "Failed authorizing OPA permissions for resource")
	}

	// local currently doesn't support registries of any kind. remove push / run registry
	createFunctionOptions.FunctionConfig.Spec.RunRegistry = ""
	createFunctionOptions.FunctionConfig.Spec.Build.Registry = ""

	// it's possible to pass a function without specifying any meta in the request, in that case skip getting existing function
	if createFunctionOptions.FunctionConfig.Meta.Namespace != "" && createFunctionOptions.FunctionConfig.Meta.Name != "" {
		existingFunctions, err := p.localStore.GetFunctions(&createFunctionOptions.FunctionConfig.Meta)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to get existing functions")
		}

		if len(existingFunctions) == 0 {
			existingFunctionConfig = nil
		} else {

			// assume only one
			existingFunction := existingFunctions[0]

			// build function options
			existingFunctionConfig = &functionconfig.ConfigWithStatus{
				Config: *existingFunction.GetConfig(),
				Status: *existingFunction.GetStatus(),
			}
		}
	}

	// if function exists, perform some validation with new function create options
	if err := p.ValidateCreateFunctionOptionsAgainstExistingFunctionConfig(ctx,
		existingFunctionConfig,
		createFunctionOptions); err != nil {
		return nil, errors.Wrap(err, "Failed to validate a function configuration against an existing configuration")
	}

	// wrap logger
	logStream, err := abstract.NewLogStream("deployer", nucliozap.InfoLevel, createFunctionOptions.Logger)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create a log stream")
	}

	// save the log stream for the name
	p.DeployLogStreams.Store(createFunctionOptions.FunctionConfig.Meta.GetUniqueID(), logStream)

	// replace logger
	createFunctionOptions.Logger = logStream.GetLogger()

	reportCreationError := func(creationError error) error {
		createFunctionOptions.Logger.WarnWithCtx(ctx,
			"Failed to create a function; setting the function status",
			"err", creationError)

		errorStack := bytes.Buffer{}
		errors.PrintErrorStack(&errorStack, creationError, 20)

		// cut messages that are too big
		if errorStack.Len() >= 4*Mib {
			errorStack.Truncate(4 * Mib)
		}

		// post logs and error
		return p.localStore.CreateOrUpdateFunction(&functionconfig.ConfigWithStatus{
			Config: createFunctionOptions.FunctionConfig,
			Status: functionconfig.Status{
				State:   functionconfig.FunctionStateError,
				Message: errorStack.String(),
			},
		})
	}

	onAfterConfigUpdated := func() error {
		createFunctionOptions.Logger.DebugWithCtx(ctx,
			"Creating shadow function",
			"name", createFunctionOptions.FunctionConfig.Meta.Name)

		// enrich and validate again because it may not be valid after config was updated by external code entry type
		if err := p.enrichAndValidateFunctionConfig(ctx, &createFunctionOptions.FunctionConfig); err != nil {
			return errors.Wrap(err, "Failed to enrich and validate the updated function configuration")
		}

		// create the function in the store
		if err := p.localStore.CreateOrUpdateFunction(&functionconfig.ConfigWithStatus{
			Config: createFunctionOptions.FunctionConfig,
			Status: functionconfig.Status{
				State: functionconfig.FunctionStateBuilding,
			},
		}); err != nil {
			return errors.Wrap(err, "Failed to create a function")
		}

		// indicate that the creation state has been updated. local platform has no "building" state yet
		if createFunctionOptions.CreationStateUpdated != nil {
			createFunctionOptions.CreationStateUpdated <- true
		}

		return nil
	}

	onAfterBuild := func(buildResult *platform.CreateFunctionBuildResult, buildErr error) (*platform.CreateFunctionResult, error) {
		if buildErr != nil {
			reportCreationError(buildErr) // nolint: errcheck
			return nil, buildErr
		}

		skipFunctionDeploy := functionconfig.ShouldSkipDeploy(createFunctionOptions.FunctionConfig.Meta.Annotations)

		// after a function build (or skip-build) if the annotations FunctionAnnotationSkipBuild or FunctionAnnotationSkipDeploy
		// exist, they should be removed so next time, the build will happen.
		createFunctionOptions.FunctionConfig.Meta.RemoveSkipDeployAnnotation()
		createFunctionOptions.FunctionConfig.Meta.RemoveSkipBuildAnnotation()

		var createFunctionResult *platform.CreateFunctionResult
		var deployErr error
		var functionStatus functionconfig.Status

		// delete existing function containers
		previousHTTPPort, err := p.deleteOrStopFunctionContainers(createFunctionOptions)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to delete previous containers")
		}

		if !skipFunctionDeploy {
			createFunctionResult, deployErr = p.deployFunction(createFunctionOptions, previousHTTPPort)
			if deployErr != nil {
				reportCreationError(deployErr) // nolint: errcheck
				return nil, deployErr
			}

			functionStatus.HTTPPort = createFunctionResult.Port
			functionStatus.State = functionconfig.FunctionStateReady

			if err := p.populateFunctionInvocationStatus(&functionStatus, createFunctionResult); err != nil {
				return nil, errors.Wrap(err, "Failed to populate function invocation status")
			}
		} else {
			p.Logger.InfoCtx(ctx, "Skipping function deployment")
			functionStatus.State = functionconfig.FunctionStateImported
			createFunctionResult = &platform.CreateFunctionResult{
				CreateFunctionBuildResult: platform.CreateFunctionBuildResult{
					Image:                 createFunctionOptions.FunctionConfig.Spec.Image,
					UpdatedFunctionConfig: createFunctionOptions.FunctionConfig,
				},
			}
		}

		// update the function
		if err := p.localStore.CreateOrUpdateFunction(&functionconfig.ConfigWithStatus{
			Config: createFunctionOptions.FunctionConfig,
			Status: functionStatus,
		}); err != nil {
			return nil, errors.Wrap(err, "Failed to update a function with state")
		}

		createFunctionResult.FunctionStatus = functionStatus
		return createFunctionResult, nil
	}

	// If needed, load any docker image from archive into docker
	if createFunctionOptions.InputImageFile != "" {
		p.Logger.InfoWithCtx(ctx,
			"Loading docker image from archive",
			"input", createFunctionOptions.InputImageFile)
		if err := p.dockerClient.Load(createFunctionOptions.InputImageFile); err != nil {
			return nil, errors.Wrap(err, "Failed to load a Docker image from an archive")
		}
	}

	// wrap the deployer's deploy with the base HandleDeployFunction to provide lots of
	// common functionality
	return p.HandleDeployFunction(ctx, existingFunctionConfig, createFunctionOptions, onAfterConfigUpdated, onAfterBuild)
}

// GetFunctions will return deployed functions
func (p *Platform) GetFunctions(ctx context.Context,
	getFunctionsOptions *platform.GetFunctionsOptions) ([]platform.Function, error) {

	projectName, err := p.Platform.ResolveProjectNameFromLabelsStr(getFunctionsOptions.Labels)
	if err != nil {
		return nil, errors.Wrap(err, "")
	}

	if err := p.Platform.EnsureProjectRead(projectName, &getFunctionsOptions.PermissionOptions); err != nil {
		return nil, errors.Wrap(err, "Failed to ensure project read permission")
	}

	functions, err := p.localStore.GetProjectFunctions(getFunctionsOptions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to read functions from a local store")
	}

	functions, err = p.Platform.FilterFunctionsByPermissions(ctx, &getFunctionsOptions.PermissionOptions, functions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to filter functions by permissions")
	}

	// enrich with build logs
	p.EnrichFunctionsWithDeployLogStream(functions)

	return functions, nil
}

// UpdateFunction will update a previously deployed function
func (p *Platform) UpdateFunction(ctx context.Context, updateFunctionOptions *platform.UpdateFunctionOptions) error {
	return nil
}

// DeleteFunction will delete a previously deployed function
func (p *Platform) DeleteFunction(ctx context.Context, deleteFunctionOptions *platform.DeleteFunctionOptions) error {

	// pre delete validation
	functionToDelete, err := p.ValidateDeleteFunctionOptions(ctx, deleteFunctionOptions)
	if err != nil {
		return errors.Wrap(err, "Failed to validate function-deletion options")
	}

	// nothing to delete
	if functionToDelete == nil {
		return nil
	}

	// actual function and its resources deletion
	return p.delete(ctx, deleteFunctionOptions)
}

func (p *Platform) GetFunctionReplicaLogsStream(ctx context.Context,
	options *platform.GetFunctionReplicaLogsStreamOptions) (io.ReadCloser, error) {

	sinceDuration := ""
	if options.SinceSeconds != nil {
		sinceDuration = (time.Second * time.Duration(*options.SinceSeconds)).String()
	}

	tail := ""
	if options.TailLines != nil {
		tail = strconv.FormatInt(*options.TailLines, 10)
	}

	return p.dockerClient.GetContainerLogStream(ctx,
		options.Name,
		&dockerclient.ContainerLogsOptions{
			Follow: options.Follow,
			Since:  sinceDuration,
			Tail:   tail,
		})
}

func (p *Platform) GetFunctionReplicaNames(ctx context.Context,
	functionConfig *functionconfig.Config) ([]string, error) {
	return []string{
		p.GetFunctionContainerName(functionConfig),
	}, nil
}

// GetHealthCheckMode returns the healthcheck mode the platform requires
func (p *Platform) GetHealthCheckMode() platform.HealthCheckMode {

	// The internal client needs to perform the health check
	return platform.HealthCheckModeInternalClient
}

// GetName returns the platform name
func (p *Platform) GetName() string {
	return "local"
}

func (p *Platform) GetNodes() ([]platform.Node, error) {

	// just create a single node
	return []platform.Node{&node{}}, nil
}

// CreateProject will create a new project
func (p *Platform) CreateProject(ctx context.Context, createProjectOptions *platform.CreateProjectOptions) error {

	// enrich
	if err := p.EnrichCreateProjectConfig(createProjectOptions); err != nil {
		return errors.Wrap(err, "Failed to enrich a project configuration")
	}

	// validate
	if err := p.ValidateProjectConfig(createProjectOptions.ProjectConfig); err != nil {
		return errors.Wrap(err, "Failed to validate a project configuration")
	}

	// create
	if _, err := p.projectsClient.Create(ctx, createProjectOptions); err != nil {
		return errors.Wrap(err, "Failed to create project")
	}

	return nil
}

// UpdateProject will update an existing project
func (p *Platform) UpdateProject(ctx context.Context, updateProjectOptions *platform.UpdateProjectOptions) error {
	if err := p.ValidateProjectConfig(&updateProjectOptions.ProjectConfig); err != nil {
		return nuclio.WrapErrBadRequest(err)
	}

	if _, err := p.projectsClient.Update(ctx, updateProjectOptions); err != nil {
		return errors.Wrap(err, "Failed to update project")
	}

	return nil
}

// DeleteProject will delete an existing project
func (p *Platform) DeleteProject(ctx context.Context, deleteProjectOptions *platform.DeleteProjectOptions) error {
	if err := p.Platform.ValidateDeleteProjectOptions(ctx, deleteProjectOptions); err != nil {
		return errors.Wrap(err, "Failed to validate delete project options")
	}

	// check only, do not delete
	if deleteProjectOptions.Strategy == platform.DeleteProjectStrategyCheck {
		p.Logger.DebugWithCtx(ctx, "Project is ready for deletion", "projectMeta", deleteProjectOptions.Meta)
		return nil
	}

	if err := p.projectsClient.Delete(ctx, deleteProjectOptions); err != nil {
		return errors.Wrapf(err, "Failed to delete project")
	}

	return nil
}

// GetProjects will list existing projects
func (p *Platform) GetProjects(ctx context.Context, getProjectsOptions *platform.GetProjectsOptions) ([]platform.Project, error) {
	projects, err := p.projectsClient.Get(ctx, getProjectsOptions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed getting projects")
	}

	return p.Platform.FilterProjectsByPermissions(&getProjectsOptions.PermissionOptions, projects)
}

// CreateFunctionEvent will create a new function event that can later be used as a template from
// which to invoke functions
func (p *Platform) CreateFunctionEvent(ctx context.Context, createFunctionEventOptions *platform.CreateFunctionEventOptions) error {
	if err := p.Platform.EnrichFunctionEvent(ctx, &createFunctionEventOptions.FunctionEventConfig); err != nil {
		return errors.Wrap(err, "Failed to enrich function event")
	}

	functionName := createFunctionEventOptions.FunctionEventConfig.Meta.Labels[common.NuclioResourceLabelKeyFunctionName]
	projectName := createFunctionEventOptions.FunctionEventConfig.Meta.Labels[common.NuclioResourceLabelKeyProjectName]

	// Check OPA permissions
	permissionOptions := createFunctionEventOptions.PermissionOptions
	permissionOptions.RaiseForbidden = true
	if _, err := p.QueryOPAFunctionEventPermissions(projectName,
		functionName,
		createFunctionEventOptions.FunctionEventConfig.Meta.Name,
		opa.ActionCreate,
		&permissionOptions); err != nil {
		return errors.Wrap(err, "Failed authorizing OPA permissions for resource")
	}

	return p.localStore.CreateOrUpdateFunctionEvent(&createFunctionEventOptions.FunctionEventConfig)
}

// UpdateFunctionEvent will update a previously existing function event
func (p *Platform) UpdateFunctionEvent(ctx context.Context, updateFunctionEventOptions *platform.UpdateFunctionEventOptions) error {
	if err := p.Platform.EnrichFunctionEvent(ctx, &updateFunctionEventOptions.FunctionEventConfig); err != nil {
		return errors.Wrap(err, "Failed to enrich function event")
	}

	functionEvents, err := p.localStore.GetFunctionEvents(&platform.GetFunctionEventsOptions{
		Meta: updateFunctionEventOptions.FunctionEventConfig.Meta,
	})
	if err != nil {
		return errors.Wrap(err, "Failed to read function events from a local store")
	}
	functionEventToUpdate := functionEvents[0]

	functionName := updateFunctionEventOptions.FunctionEventConfig.Meta.Labels[common.NuclioResourceLabelKeyFunctionName]
	projectName := updateFunctionEventOptions.FunctionEventConfig.Meta.Labels[common.NuclioResourceLabelKeyProjectName]

	// Check OPA permissions
	permissionOptions := updateFunctionEventOptions.PermissionOptions
	permissionOptions.RaiseForbidden = true
	if _, err := p.QueryOPAFunctionEventPermissions(projectName,
		functionName,
		functionEventToUpdate.GetConfig().Meta.Name,
		opa.ActionUpdate,
		&permissionOptions); err != nil {
		return errors.Wrap(err, "Failed authorizing OPA permissions for resource")
	}

	return p.localStore.CreateOrUpdateFunctionEvent(&updateFunctionEventOptions.FunctionEventConfig)
}

// DeleteFunctionEvent will delete a previously existing function event
func (p *Platform) DeleteFunctionEvent(ctx context.Context, deleteFunctionEventOptions *platform.DeleteFunctionEventOptions) error {
	functionEvents, err := p.localStore.GetFunctionEvents(&platform.GetFunctionEventsOptions{
		Meta: deleteFunctionEventOptions.Meta,
	})
	if err != nil {
		return errors.Wrap(err, "Failed to read function events from a local store")
	}

	if len(functionEvents) > 0 {
		functionEventToDelete := functionEvents[0]
		functionName := functionEventToDelete.GetConfig().Meta.Labels[common.NuclioResourceLabelKeyFunctionName]
		projectName := functionEventToDelete.GetConfig().Meta.Labels[common.NuclioResourceLabelKeyProjectName]

		// Check OPA permissions
		permissionOptions := deleteFunctionEventOptions.PermissionOptions
		permissionOptions.RaiseForbidden = true
		if _, err := p.QueryOPAFunctionEventPermissions(projectName,
			functionName,
			functionEventToDelete.GetConfig().Meta.Name,
			opa.ActionDelete,
			&permissionOptions); err != nil {
			return errors.Wrap(err, "Failed authorizing OPA permissions for resource")
		}
	}

	return p.localStore.DeleteFunctionEvent(&deleteFunctionEventOptions.Meta)
}

// GetFunctionEvents will list existing function events
func (p *Platform) GetFunctionEvents(ctx context.Context, getFunctionEventsOptions *platform.GetFunctionEventsOptions) ([]platform.FunctionEvent, error) {
	functionEvents, err := p.localStore.GetFunctionEvents(getFunctionEventsOptions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to read function events from a local store")
	}

	return p.Platform.FilterFunctionEventsByPermissions(ctx,
		&getFunctionEventsOptions.PermissionOptions,
		functionEvents)
}

// GetAPIGateways not supported on this platform
func (p *Platform) GetAPIGateways(ctx context.Context, getAPIGatewaysOptions *platform.GetAPIGatewaysOptions) ([]platform.APIGateway, error) {
	return nil, nil
}

// GetExternalIPAddresses returns the external IP addresses invocations will use, if "via" is set to "external-ip".
// These addresses are either set through SetExternalIPAddresses or automatically discovered
func (p *Platform) GetExternalIPAddresses() ([]string, error) {

	// check if parent has addresses
	externalIPAddress, err := p.Platform.GetExternalIPAddresses()
	if err != nil {
		return nil, errors.Wrap(err, "Failed to get external IP addresses from parent")
	}

	// if the parent has something, use that
	if len(externalIPAddress) != 0 {
		return externalIPAddress, nil
	}

	// If the testing environment variable is set - use that
	if os.Getenv("NUCLIO_TEST_HOST") != "" {
		return []string{os.Getenv("NUCLIO_TEST_HOST")}, nil
	}

	if common.RunningInContainer() {
		return []string{"172.17.0.1"}, nil
	}

	// return an empty string to maintain backwards compatibility
	return []string{""}, nil
}

// ResolveDefaultNamespace returns the proper default resource namespace, given the current default namespace
func (p *Platform) ResolveDefaultNamespace(defaultNamespace string) string {

	// if no default namespace is chosen, use "nuclio"
	if defaultNamespace == "@nuclio.selfNamespace" || defaultNamespace == "" {
		return "nuclio"
	}

	return defaultNamespace
}

// GetNamespaces returns all the namespaces in the platform
func (p *Platform) GetNamespaces(ctx context.Context) ([]string, error) {
	return []string{"nuclio"}, nil
}

func (p *Platform) GetDefaultInvokeIPAddresses() ([]string, error) {
	addresses := []string{

		// default internal docker network
		"172.17.0.1",
	}

	if common.RunningInContainer() {

		// https://docs.docker.com/desktop/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
		dockerHostAddresses, err := net.LookupIP("host.docker.internal")
		if err == nil {
			for _, address := range dockerHostAddresses {
				addresses = append(addresses, address.String())
			}
		}

		containerID, err := common.RunningContainerHostname()
		if err != nil {
			return nil, errors.Wrap(err, "Failed to get running container ID")
		}

		networkSettings, err := p.dockerClient.GetContainerNetworkSettings(containerID)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to get container network settings")
		}

		// docker gateway, usually 172.17.0.1
		addresses = append(addresses, networkSettings.Gateway)

		// attach each network driver gateway
		for _, network := range networkSettings.Networks {
			addresses = append(addresses, network.Gateway)
		}

	}

	return common.RemoveDuplicatesFromSliceString(addresses), nil
}

func (p *Platform) SaveFunctionDeployLogs(ctx context.Context, functionName, namespace string) error {
	functions, err := p.GetFunctions(ctx,
		&platform.GetFunctionsOptions{
			Name:      functionName,
			Namespace: namespace,
		})
	if err != nil || len(functions) == 0 {
		return errors.Wrap(err, "Failed to get existing functions")
	}

	// enrich with build logs
	p.EnrichFunctionsWithDeployLogStream(functions)

	function := functions[0]

	return p.localStore.CreateOrUpdateFunction(&functionconfig.ConfigWithStatus{
		Config: *function.GetConfig(),
		Status: *function.GetStatus(),
	})
}

func (p *Platform) ValidateFunctionContainersHealthiness(ctx context.Context) {
	namespaces, err := p.GetNamespaces(ctx)
	if err != nil {
		p.Logger.WarnWith("Cannot not get namespaces", "err", err)
		return
	}

	for _, namespace := range namespaces {

		// get functions for that namespace
		functions, err := p.GetFunctions(ctx, &platform.GetFunctionsOptions{
			Namespace: namespace,
		})
		if err != nil {
			p.Logger.WarnWithCtx(ctx,
				"Failed to get namespaced functions",
				"namespace", namespace,
				"err", err)
			continue
		}

		// check each function container healthiness and update function's status correspondingly
		for _, function := range functions {
			functionConfig := function.GetConfig()
			functionStatus := function.GetStatus()
			functionName := functionConfig.Meta.Name

			functionIsReady := functionStatus.State == functionconfig.FunctionStateReady
			functionWasSetAsUnhealthy := functionconfig.FunctionStateInSlice(functionStatus.State,
				[]functionconfig.FunctionState{
					functionconfig.FunctionStateError,
					functionconfig.FunctionStateUnhealthy,
				}) && functionStatus.Message == string(common.FunctionStateMessageUnhealthy)

			if !(functionIsReady || functionWasSetAsUnhealthy) {

				// cannot be monitored
				continue
			}

			// get function container name
			containerName := p.GetFunctionContainerName(&functionconfig.Config{
				Meta: functionconfig.Meta{
					Name:      functionName,
					Namespace: namespace,
				},
			})

			// get function container by name
			containers, err := p.dockerClient.GetContainers(&dockerclient.GetContainerOptions{
				Name: containerName,
			})
			if err != nil {
				p.Logger.WarnWithCtx(ctx, "Failed to get containers by name",
					"err", err,
					"containerName", containerName)
				continue
			}

			// if function container does not exists, mark as unhealthy
			if len(containers) == 0 {
				p.Logger.WarnWithCtx(ctx, "No containers were found", "functionName", functionName)

				// no running containers were found for function, set function unhealthy
				if err := p.setFunctionUnhealthy(function); err != nil {
					p.Logger.ErrorWithCtx(ctx, "Failed to mark a function as unhealthy",
						"err", err,
						"functionName", functionName,
						"namespace", namespace)
				}
				continue
			}

			container := containers[0]

			// check ready function to ensure its container is healthy
			if functionIsReady {
				if err := p.checkAndSetFunctionUnhealthy(container.ID, function); err != nil {
					p.Logger.ErrorWithCtx(ctx, "Failed to check a function's health and mark it as unhealthy if necessary",
						"err", err,
						"functionName", functionName,
						"namespace", namespace)
				}
			}

			// check unhealthy function to see if its container id is healthy again
			if functionWasSetAsUnhealthy {
				if err := p.checkAndSetFunctionHealthy(container.ID, function); err != nil {
					p.Logger.ErrorWithCtx(ctx, "Failed to check a function's health and mark it as unhealthy if necessary",
						"err", err,
						"functionName", functionName,
						"namespace", namespace)
				}
			}
		}
	}
}

func (p *Platform) GetFunctionContainerName(functionConfig *functionconfig.Config) string {
	return fmt.Sprintf("nuclio-%s-%s",
		functionConfig.Meta.Namespace,
		functionConfig.Meta.Name)
}

func (p *Platform) GetFunctionVolumeMountName(functionConfig *functionconfig.Config) string {
	return fmt.Sprintf("nuclio-%s-%s",
		functionConfig.Meta.Namespace,
		functionConfig.Meta.Name)
}

func (p *Platform) deployFunction(createFunctionOptions *platform.CreateFunctionOptions,
	previousHTTPPort int) (*platform.CreateFunctionResult, error) {

	mountPoints, err := p.resolveAndCreateFunctionMounts(createFunctionOptions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to resolve and create function mounts")
	}

	network, err := p.resolveFunctionNetwork(createFunctionOptions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to resolve function network")
	}

	restartPolicy, err := p.resolveFunctionRestartPolicy(createFunctionOptions)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to resolve function network")
	}

	labels := p.compileDeployFunctionLabels(createFunctionOptions)
	envMap := p.compileDeployFunctionEnvMap(createFunctionOptions)

	// get function port - either from configuration, from the previous deployment or from a free port
	functionExternalHTTPPort, err := p.getFunctionHTTPPort(createFunctionOptions, previousHTTPPort)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to get a function's HTTP port")
	}

	gpus := ""
	if createFunctionOptions.FunctionConfig.Spec.PositiveGPUResourceLimit() {

		// TODO: allow user specify the exact gpu index/uuid & capabilities
		// https://docs.docker.com/config/containers/resource_constraints/#access-an-nvidia-gpu
		gpus = "all"
	}

	functionSecurityContext := createFunctionOptions.FunctionConfig.Spec.SecurityContext

	// run the docker image
	runContainerOptions := &dockerclient.RunOptions{
		ContainerName: p.GetFunctionContainerName(&createFunctionOptions.FunctionConfig),
		Ports: map[int]int{
			functionExternalHTTPPort: abstract.FunctionContainerHTTPPort,
		},
		Env:           envMap,
		Labels:        labels,
		Network:       network,
		RestartPolicy: restartPolicy,
		GPUs:          gpus,
		MountPoints:   mountPoints,
		RunAsUser:     functionSecurityContext.RunAsUser,
		RunAsGroup:    functionSecurityContext.RunAsGroup,
		FSGroup:       functionSecurityContext.FSGroup,
	}

	containerID := p.GetFunctionContainerName(&createFunctionOptions.FunctionConfig)
	if !createFunctionOptions.FunctionConfig.Spec.Disable {
		containerID, err = p.dockerClient.RunContainer(createFunctionOptions.FunctionConfig.Spec.Image,
			runContainerOptions)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to run a Docker container")
		}

		if err := p.waitForContainer(containerID,
			createFunctionOptions.FunctionConfig.Spec.ReadinessTimeoutSeconds); err != nil {
			return nil, err
		}

		functionExternalHTTPPort, err = p.resolveDeployedFunctionHTTPPort(containerID)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to resolve a deployed function's HTTP port")
		}
	}

	return &platform.CreateFunctionResult{
		CreateFunctionBuildResult: platform.CreateFunctionBuildResult{
			Image:                 createFunctionOptions.FunctionConfig.Spec.Image,
			UpdatedFunctionConfig: createFunctionOptions.FunctionConfig,
		},
		Port:        functionExternalHTTPPort,
		ContainerID: containerID,
	}, nil
}

func (p *Platform) delete(ctx context.Context, deleteFunctionOptions *platform.DeleteFunctionOptions) error {

	// delete the function from the local store
	if err := p.localStore.DeleteFunction(ctx, &deleteFunctionOptions.FunctionConfig.Meta); err != nil &&
		err != nuclio.ErrNotFound {
		p.Logger.WarnWithCtx(ctx, "Failed to delete a function from the local store", "err", err.Error())
	}

	getContainerOptions := &dockerclient.GetContainerOptions{
		Stopped: true,
		Labels: map[string]string{
			"nuclio.io/platform":                      "local",
			"nuclio.io/namespace":                     deleteFunctionOptions.FunctionConfig.Meta.Namespace,
			common.NuclioResourceLabelKeyFunctionName: deleteFunctionOptions.FunctionConfig.Meta.Name,
		},
	}

	containersInfo, err := p.dockerClient.GetContainers(getContainerOptions)
	if err != nil {
		return errors.Wrap(err, "Failed to get containers")
	}

	p.Logger.DebugWithCtx(ctx, "Got function containers", "containersInfoLength", len(containersInfo))

	// iterate over contains and delete them. It's possible that under some weird circumstances
	// there are a few instances of this function in the namespace
	for _, containerInfo := range containersInfo {
		p.Logger.DebugWithCtx(ctx, "Removing function container", "containerName", containerInfo.Name)
		if err := p.dockerClient.RemoveContainer(containerInfo.ID); err != nil {
			return errors.Wrapf(err, "Failed to remove container %s", containerInfo.ID)
		}
	}

	// delete function volume mount after containers are deleted
	functionVolumeMountName := p.GetFunctionVolumeMountName(&deleteFunctionOptions.FunctionConfig)
	p.Logger.DebugWithCtx(ctx, "Removing function volume", "functionVolumeMountName", functionVolumeMountName)
	if err := p.dockerClient.DeleteVolume(functionVolumeMountName); err != nil {
		return errors.Wrapf(err, "Failed to delete a function volume %s", functionVolumeMountName)
	}

	p.Logger.InfoWithCtx(ctx, "Successfully deleted function",
		"name", deleteFunctionOptions.FunctionConfig.Meta.Name)
	return nil
}

func (p *Platform) resolveAndCreateFunctionMounts(
	createFunctionOptions *platform.CreateFunctionOptions) ([]dockerclient.MountPoint, error) {

	if err := p.prepareFunctionVolumeMount(createFunctionOptions); err != nil {
		return nil, errors.Wrap(err, "Failed to prepare a function's volume mount")
	}

	// add processor mount
	mountPoints := []dockerclient.MountPoint{
		{
			Source:      p.GetFunctionVolumeMountName(&createFunctionOptions.FunctionConfig),
			Destination: FunctionProcessorContainerDirPath,

			// read only mode
			RW:   false,
			Type: "volume",
		},
	}

	for _, functionVolume := range createFunctionOptions.FunctionConfig.Spec.Volumes {

		// add only host path
		if functionVolume.Volume.HostPath != nil {
			mountPoints = append(mountPoints, dockerclient.MountPoint{
				Source:      functionVolume.Volume.HostPath.Path,
				Destination: functionVolume.VolumeMount.MountPath,
				RW:          !functionVolume.VolumeMount.ReadOnly,
				Type:        "bind",
			})
		}
	}

	return mountPoints, nil
}

func (p *Platform) encodeFunctionSpec(spec *functionconfig.Spec) string {
	encodedFunctionSpec, _ := json.Marshal(spec)

	return string(encodedFunctionSpec)
}

func (p *Platform) getFunctionHTTPPort(createFunctionOptions *platform.CreateFunctionOptions,
	previousHTTPPort int) (int, error) {

	// if the configuration specified an HTTP port - use that
	if createFunctionOptions.FunctionConfig.Spec.GetHTTPPort() != 0 {
		p.Logger.DebugWith("Configuration specified HTTP port",
			"port",
			createFunctionOptions.FunctionConfig.Spec.GetHTTPPort())

		return createFunctionOptions.FunctionConfig.Spec.GetHTTPPort(), nil
	}

	// if there was a previous deployment and no configuration - use that
	if previousHTTPPort != 0 {
		createFunctionOptions.Logger.DebugWith("Using previous deployment HTTP port ",
			"previousHTTPPort", previousHTTPPort)
		return previousHTTPPort, nil
	}

	return dockerclient.RunOptionsNoPort, nil
}

func (p *Platform) resolveDeployedFunctionHTTPPort(containerID string) (int, error) {
	containers, err := p.dockerClient.GetContainers(&dockerclient.GetContainerOptions{
		ID: containerID,
	})
	if err != nil || len(containers) == 0 {
		return 0, errors.Wrap(err, "Failed to get a container")
	}
	return p.getContainerHTTPTriggerPort(&containers[0])
}

func (p *Platform) getContainerHTTPTriggerPort(container *dockerclient.Container) (int, error) {
	return p.dockerClient.GetContainerPort(container, abstract.FunctionContainerHTTPPort)
}

func (p *Platform) marshallAnnotations(annotations map[string]string) []byte {
	if annotations == nil {
		return nil
	}

	marshalledAnnotations, err := json.Marshal(annotations)
	if err != nil {
		return nil
	}

	// convert to string and return address
	return marshalledAnnotations
}

func (p *Platform) deleteOrStopFunctionContainers(createFunctionOptions *platform.CreateFunctionOptions) (int, error) {
	var previousHTTPPort int

	createFunctionOptions.Logger.InfoWith("Cleaning up before deployment",
		"functionName", createFunctionOptions.FunctionConfig.Meta.Name)

	// get function containers
	containers, err := p.dockerClient.GetContainers(&dockerclient.GetContainerOptions{
		Name:    p.GetFunctionContainerName(&createFunctionOptions.FunctionConfig),
		Stopped: true,
	})
	if err != nil {
		return 0, errors.Wrap(err, "Failed to get function containers")
	}

	if createFunctionOptions.FunctionConfig.Spec.Disable {
		createFunctionOptions.Logger.InfoWith("Disabling function",
			"functionName", createFunctionOptions.FunctionConfig.Meta.Name)

		// if function is disabled, stop all containers
		for _, container := range containers {
			createFunctionOptions.Logger.DebugWith("Stop function container",
				"functionName", createFunctionOptions.FunctionConfig.Meta.Name,
				"containerID", container.ID)
			if err := p.dockerClient.StopContainer(container.ID); err != nil {
				return 0, errors.Wrap(err, "Failed to stop a container")
			}
		}
		return 0, nil
	}

	// if the function exists, delete it
	if len(containers) > 0 {
		createFunctionOptions.Logger.InfoWith("Function already exists, deleting function containers",
			"functionName", createFunctionOptions.FunctionConfig.Meta.Name)
	}

	// iterate over containers and delete
	for _, container := range containers {
		createFunctionOptions.Logger.DebugWith("Deleting function container",
			"functionName", createFunctionOptions.FunctionConfig.Meta.Name,
			"containerName", container.Name)
		previousHTTPPort, err = p.getContainerHTTPTriggerPort(&container)
		if err != nil {
			return 0, errors.Wrap(err, "Failed to get a container's HTTP-trigger port")
		}

		if err := p.dockerClient.RemoveContainer(container.ID); err != nil {
			return 0, errors.Wrap(err, "Failed to delete a function container")
		}
	}

	return previousHTTPPort, nil
}

func (p *Platform) checkAndSetFunctionUnhealthy(containerID string, function platform.Function) error {
	if err := p.dockerClient.AwaitContainerHealth(containerID,
		&p.Config.Local.FunctionContainersHealthinessTimeout); err != nil {
		return p.setFunctionUnhealthy(function)
	}
	return nil
}

func (p *Platform) setFunctionUnhealthy(function platform.Function) error {
	functionStatus := function.GetStatus()

	// set function state to error
	functionStatus.State = functionconfig.FunctionStateUnhealthy

	// set unhealthy error message
	functionStatus.Message = string(common.FunctionStateMessageUnhealthy)

	p.Logger.WarnWith("Setting function state as unhealthy",
		"functionName", function.GetConfig().Meta.Name,
		"functionStatus", functionStatus)

	// function container is not healthy or missing, set function state as error
	return p.localStore.CreateOrUpdateFunction(&functionconfig.ConfigWithStatus{
		Config: *function.GetConfig(),
		Status: *functionStatus,
	})
}

func (p *Platform) checkAndSetFunctionHealthy(containerID string, function platform.Function) error {
	if err := p.dockerClient.AwaitContainerHealth(containerID,
		&p.Config.Local.FunctionContainersHealthinessTimeout); err != nil {
		return errors.Wrapf(err, "Failed to ensure the health of container ID %s", containerID)
	}
	functionStatus := function.GetStatus()

	// set function as ready
	functionStatus.State = functionconfig.FunctionStateReady

	// unset error message
	functionStatus.Message = ""

	p.Logger.InfoWith("Setting function state as ready",
		"functionName", function.GetConfig().Meta.Name,
		"functionStatus", functionStatus)

	// function container is not healthy or missing, set function state as error
	return p.localStore.CreateOrUpdateFunction(&functionconfig.ConfigWithStatus{
		Config: *function.GetConfig(),
		Status: *functionStatus,
	})
}

func (p *Platform) waitForContainer(containerID string, timeout int) error {
	p.Logger.InfoWith("Waiting for function to be ready",
		"timeout", timeout)

	readinessTimeout := time.Duration(timeout) * time.Second
	if timeout == 0 {
		readinessTimeout = p.Config.GetDefaultFunctionReadinessTimeout()
	}

	if err := p.dockerClient.AwaitContainerHealth(containerID, &readinessTimeout); err != nil {
		var errMessage string

		// try to get error logs
		containerLogs, getContainerLogsErr := p.dockerClient.GetContainerLogs(containerID)
		if getContainerLogsErr == nil {
			errMessage = fmt.Sprintf("Function wasn't ready in time. Logs:\n%s", containerLogs)
		} else {
			errMessage = fmt.Sprintf("Function wasn't ready in time (couldn't fetch logs: %s)", getContainerLogsErr.Error())
		}

		return errors.Wrap(err, errMessage)
	}
	return nil
}

func (p *Platform) prepareFunctionVolumeMount(createFunctionOptions *platform.CreateFunctionOptions) error {

	// create docker volume
	if err := p.dockerClient.CreateVolume(&dockerclient.CreateVolumeOptions{
		Name: p.GetFunctionVolumeMountName(&createFunctionOptions.FunctionConfig),
	}); err != nil {
		return errors.Wrapf(err, "Failed to create a volume for function %s",
			createFunctionOptions.FunctionConfig.Meta.Name)
	}

	// marshaling processor config
	processorConfigBody, err := yaml.Marshal(&processor.Configuration{
		Config: createFunctionOptions.FunctionConfig,
	})
	if err != nil {
		return errors.Wrap(err, "Failed to marshal a processor configuration")
	}

	// dumping contents to volume's processor path
	if _, err := p.dockerClient.RunContainer("gcr.io/iguazio/alpine:3.15",
		&dockerclient.RunOptions{
			Remove:           true,
			ImageMayNotExist: true,
			MountPoints: []dockerclient.MountPoint{
				{
					Source:      p.GetFunctionVolumeMountName(&createFunctionOptions.FunctionConfig),
					Destination: FunctionProcessorContainerDirPath,
					RW:          true,
				},
			},
			Command: fmt.Sprintf(`sh -c 'echo "%s" | base64 -d | install -m 777 /dev/stdin %s'`,
				base64.StdEncoding.EncodeToString(processorConfigBody),
				path.Join(FunctionProcessorContainerDirPath, "processor.yaml")),
		}); err != nil {
		return errors.Wrap(err, "Failed to write a processor configuration to a volume")
	}
	return nil
}

func (p *Platform) compileDeployFunctionEnvMap(createFunctionOptions *platform.CreateFunctionOptions) map[string]string {
	envMap := map[string]string{}
	for _, env := range createFunctionOptions.FunctionConfig.Spec.Env {
		envMap[env.Name] = env.Value
	}
	return envMap
}

func (p *Platform) compileDeployFunctionLabels(createFunctionOptions *platform.CreateFunctionOptions) map[string]string {
	labels := map[string]string{
		"nuclio.io/platform":                      "local",
		"nuclio.io/namespace":                     createFunctionOptions.FunctionConfig.Meta.Namespace,
		common.NuclioResourceLabelKeyFunctionName: createFunctionOptions.FunctionConfig.Meta.Name,
		"nuclio.io/function-spec":                 p.encodeFunctionSpec(&createFunctionOptions.FunctionConfig.Spec),
	}

	for labelName, labelValue := range createFunctionOptions.FunctionConfig.Meta.Labels {
		labels[labelName] = labelValue
	}

	marshalledAnnotations := p.marshallAnnotations(createFunctionOptions.FunctionConfig.Meta.Annotations)
	if marshalledAnnotations != nil {
		labels["nuclio.io/annotations"] = string(marshalledAnnotations)
	}
	return labels
}

func (p *Platform) enrichAndValidateFunctionConfig(ctx context.Context, functionConfig *functionconfig.Config) error {
	if len(functionConfig.Spec.Volumes) == 0 {
		functionConfig.Spec.Volumes = p.Config.Local.DefaultFunctionVolumes
	}

	if err := p.EnrichFunctionConfig(ctx, functionConfig); err != nil {
		return errors.Wrap(err, "Failed to enrich a function configuration")
	}

	if err := p.ValidateFunctionConfig(ctx, functionConfig); err != nil {
		return errors.Wrap(err, "Failed to validate a function configuration")
	}

	return nil
}

func (p *Platform) populateFunctionInvocationStatus(functionInvocation *functionconfig.Status,
	createFunctionResults *platform.CreateFunctionResult) error {

	externalIPAddresses, err := p.GetExternalIPAddresses()
	if err != nil {
		return err
	}

	addresses, err := p.dockerClient.GetContainerIPAddresses(createFunctionResults.ContainerID)
	if err != nil {
		return errors.Wrap(err, "Failed to get container network addresses")
	}

	// enrich address with function's container port
	var addressesWithFunctionPort []string
	for _, address := range addresses {
		addressesWithFunctionPort = append(addressesWithFunctionPort,
			fmt.Sprintf("%s:%d", address, abstract.FunctionContainerHTTPPort))
	}

	functionInvocation.InternalInvocationURLs = addressesWithFunctionPort
	functionInvocation.ExternalInvocationURLs = []string{}
	for _, externalIPAddress := range externalIPAddresses {
		switch externalIPAddress {

		// skip if empty or assumes running in docker
		case "", "172.17.0.1":
			continue
		default:
			functionInvocation.ExternalInvocationURLs = append(functionInvocation.ExternalInvocationURLs,
				fmt.Sprintf("%s:%d", externalIPAddress, createFunctionResults.Port))
		}
	}
	return nil
}

func (p *Platform) resolveFunctionNetwork(createFunctionOptions *platform.CreateFunctionOptions) (string, error) {

	// get function platform-specific configuration
	functionPlatformConfiguration, err := newFunctionPlatformConfiguration(&createFunctionOptions.FunctionConfig)
	if err != nil {
		return "", errors.Wrap(err, "Failed to create a function's platform configuration")
	}
	if functionPlatformConfiguration.Network != "" {
		return functionPlatformConfiguration.Network, nil
	}

	return p.Config.Local.DefaultFunctionContainerNetworkName, nil
}

func (p *Platform) resolveFunctionRestartPolicy(createFunctionOptions *platform.CreateFunctionOptions) (*dockerclient.RestartPolicy, error) {

	// get function platform-specific configuration
	functionPlatformConfiguration, err := newFunctionPlatformConfiguration(&createFunctionOptions.FunctionConfig)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create a function's platform configuration")
	}
	if functionPlatformConfiguration.RestartPolicy != nil {
		return functionPlatformConfiguration.RestartPolicy, nil
	}

	return p.Config.Local.DefaultFunctionRestartPolicy, nil
}


text:
package ca.ualberta.physics.cssdp.util;

import java.io.IOException;

import ca.ualberta.physics.cssdp.model.Mnemonic;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

/**
 * Marshals LocalDates back and forth between String and LocalDate
 * representations.
 */
public class JSONMnemonicSerializer extends StdSerializer<Mnemonic> {

	public JSONMnemonicSerializer() {
		super(Mnemonic.class, false);
	}

	@Override
	public void serialize(Mnemonic value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		jgen.writeString(value.getValue());
	}

}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react'
import { Link } from 'react-router'
import Table from './Table'

export default class Student extends Component {

  constructor (props) {
    super(props)

    this.loadStudentInfo(props)
  }

  loadStudentInfo (props) {
    fetch('http://discrete-eltech.eurodir.ru:8888/s/' + props.params.studentID + '/info')
      .then(response => response.json())
      .then(student => {
        this.setState({
          ...this.state,
          student : student,
        })
      })

    fetch('http://discrete-eltech.eurodir.ru:8888/s/' + props.params.studentID + '/tests')
      .then(response => response.json())
      .then(tests => {
        console.log({
          ...this.state,
          tests : tests,
        })
        this.setState({
          ...this.state,
          tests : tests,
        })
      })
  }

  componentWillReceiveProps(nextProps) {
    this.loadStudentInfo(nextProps)
  }

  render () {
    return (

        {this.state && 'student' in this.state ?

{this.state.student.first_name} {this.state.student.last_name}

                  Группа
                   <Link to={'/group/' + this.state.student.group}>{this.state.student.group}</Link>

                  {this.state.student.email}

                {this.state.student.website ?

                    Google сайт

                  : null
                }

              {'tests' in this.state ?
                this.state.tests.count > 0 ?

Тесты

                      {this.state.tests.tests.map(test => {
                      return (

                        {test.finished ?

                            {test.testName} - пройден - время {Math.floor(test.duration / 60)}мин {Math.floor(test.duration) % 60}с

Решение студента

Входные данные

{test.object.input.join(', ')}

                            {test.object.table ?

Таблица

 row.map(col =>

{col}

                                ))}/>

                              : null
                            }

Ответ

{JSON.stringify(test.object.output)}

                        : null}

)
                      })}

                :
Нет решенных тестов

              : null}

        : null}

    )
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('deployments', '0003_auto_20170905_0947'),
    ]

    operations = [
        migrations.AddField(
            model_name='deployment',
            name='prediction',
            field=models.TextField(blank=True, null=True),
        ),
    ]


text:
from django.contrib.auth.models import User
from django.utils.timezone import get_current_timezone
from django.utils.importlib import import_module
from django.conf import settings
from taggit.models import Tag
from datetime import datetime

def view_filter(**kwargs):
    """
    Filters blog posts by year/month/day, category, tag or author
    """

    from bambu_blog.models import Post, Category
    posts = Post.objects.select_related().live()

    if 'year' in kwargs:
        posts = posts.filter(
            date__year = int(kwargs['year'])
        )

        if 'month' in kwargs:
            posts = posts.filter(
                date__month = int(kwargs['month'])
            )

            if 'day' in kwargs:
                posts = posts.filter(
                    date__day = int(kwargs['day'])
                )

    if 'category' in kwargs:
        posts = posts.filter(categories__slug = kwargs['category'])
    elif 'tag' in kwargs:
        posts = posts.filter(tags__slug = kwargs['tag'])
    elif 'username' in kwargs:
        posts = posts.filter(author__username = kwargs['username'])

    return posts

def title_parts(**kwargs):
    """
    Returns a tuple of strings that can be used to build the ``<title>`` tag for an HTML
    template
    """
    from bambu_blog.models import Category

    title_parts = [u'Blog']
    if 'year' in kwargs:
        if 'month' in kwargs:
            if 'day' in kwargs:
                title_parts.insert(0,
                    datetime(
                        int(kwargs['year']),
                        int(kwargs['month']),
                        int(kwargs['day'])
                    ).replace(tzinfo = get_current_timezone()).strftime('%B %d, %Y')
                )
            else:
                title_parts.insert(0,
                    datetime(
                        int(kwargs['year']),
                        int(kwargs['month']),
                        1
                    ).replace(tzinfo = get_current_timezone()).strftime('%B %Y')
                )
        else:
            title_parts.insert(0, kwargs['year'])

    if 'category' in kwargs:
        category = Category.objects.get(slug = kwargs['category'])
        title_parts.insert(0, category.name)
    elif 'tag' in kwargs:
        tag = Tag.objects.get(slug = kwargs['tag'])
        title_parts.insert(0, tag.name)
    elif 'username' in kwargs:
        author = User.objects.get(username = kwargs['username'])
        title_parts.insert(0, author.get_full_name() or author.username)

    return title_parts

def get_post_image(post):
    """
    Gets the first attachment matching common 'image' MIME types
    """

    image_types = (
        'image/bmp', 'image/x-windows-bmp', 'image/gif',
        'image/jpeg', 'image/pjpeg', 'image/png', 'image/tiff'
    )

    images = post.attachments.filter(mimetype__in = image_types)[:1]
    if images.exists():
        try:
            url = images[0].file.url
            if url.startswith('/'):
                url = settings.MEDIA_URL[:-1] + url

            return url
        except:
            pass

    return ''

def get_comments_form():
    """
    Gets the class of the form used to post comments to a blog post
    (``bambu_comments.forms.CommentForm`` by default)
    """

    klass = getattr(settings, 'BLOG_COMMENTS_FORM',
        'bambu_comments.forms.CommentForm'
    )

    module, dot, klass = klass.rpartition('.')
    module = import_module(module)
    klass = getattr(module, klass)

    return klass


text:
<?php

namespace Tests\Component\Stopwatch;

use Accelleratii\Component\Stopwatch\Stopwatch;

/**
 * StopwatchTest
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class StopwatchTest extends \PHPUnit_Framework_TestCase
{
    const DELTA = 20;

    public function testStart()
    {
        $stopwatch = new Stopwatch();
        $event = $stopwatch->start('foo', 'cat');

        $this->assertInstanceof('Accelleratii\Component\Stopwatch\StopwatchEvent', $event);
        $this->assertEquals('cat', $event->getCategory());
        $this->assertSame($event, $stopwatch->getEvent('foo'));
    }

    public function testIsStarted()
    {
        $stopwatch = new Stopwatch();
        $stopwatch->start('foo', 'cat');

        $this->assertTrue($stopwatch->isStarted('foo'));
    }

    public function testIsNotStarted()
    {
        $stopwatch = new Stopwatch();

        $this->assertFalse($stopwatch->isStarted('foo'));
    }

    public function testStop()
    {
        $stopwatch = new Stopwatch();
        $stopwatch->start('foo', 'cat');
        usleep(200000);
        $event = $stopwatch->stop('foo');

        $this->assertInstanceof('Accelleratii\Component\Stopwatch\StopwatchEvent', $event);
        $this->assertEquals(200, $event->getDuration(), null, self::DELTA);
    }

    /**
     * @expectedException \LogicException
     */
    public function testUnknownEvent()
    {
        $stopwatch = new Stopwatch();
        $stopwatch->getEvent('foo');
    }

    /**
     * @expectedException \LogicException
     */
    public function testStopWithoutStart()
    {
        $stopwatch = new Stopwatch();
        $stopwatch->stop('foo');
    }

    /**
     * @expectedException \LogicException
     */
    public function testReopenANewSectionShouldThrowAnException()
    {
        $stopwatch = new Stopwatch();
        $stopwatch->openSection('section');
    }
}


text:
namespace UnityEditor.ShaderGraph
{
    interface IGeneratesFunction
    {
        void GenerateNodeFunction(FunctionRegistry registry, GraphContext graphContext, GenerationMode generationMode);
    }
}


text:
package i5.las2peer.services.ocd.utils;

import java.util.Map;

/**
 * A common interface for all factories using descriptor objects to produce instances of different classes.
 * A descriptor defines the class to instantiate although some descriptors may not correspond to a class instantiatable by the factory.
 * @author Sebastian
 *
 * @param <T> The common superclass type implementing the Parameterizable interface of the classes to instantiate.
 * @param <D> The type of the descriptor objects which define the subclass to instantiate.
 */
public interface ConditionalParameterizableFactory<T extends Parameterizable, D> {

	/**
	 * States whether a descriptor object defines an instantiatable subclass of T.
	 * @param descriptor The descriptor object.
	 * @return TRUE, if the object corresponds to an instantiatable subclass, otherwise FALSE.
	 */
	public boolean isInstantiatable(D descriptor);

	/**
	 * Produces a new object instance.
	 * @param descriptor The descriptor defining the subclass to instantiate.
	 * @param parameters The parameters to pass to the created object.
	 * @return The created object.
	 * @throws InstantiationException if instantiation failed
	 * @throws IllegalAccessException if an illegal access of the instance occured
	 */
	public T getInstance(D descriptor, Map<String, String> parameters) throws InstantiationException, IllegalAccessException;

}


text:
namespace content {

// A circular buffer allocator.
//
// We keep track of the starting offset (alloc_start_) and the ending offset
// (alloc_end_).  There are two layouts to keep in mind:
//
// #1:
//    ------------[XXXXXXXXXXXXXXXXXXXXXXX]----
//                ^                        ^
//                start                    end
//
// #2:
//    XXXXXXXXXX]---------------------[XXXXXXXX
//               ^                    ^
//               end                  start
//
// If end <= start, then we have the buffer wraparound case (depicted second).
// If the buffer is empty, then start and end will be set to -1.
//
// Allocations are always contiguous.

ResourceBuffer::ResourceBuffer()
    : buf_size_(0),
      min_alloc_size_(0),
      max_alloc_size_(0),
      alloc_start_(-1),
      alloc_end_(-1) {
}

ResourceBuffer::~ResourceBuffer() {
}

bool ResourceBuffer::Initialize(int buffer_size,
                                int min_allocation_size,
                                int max_allocation_size) {
  DCHECK(!IsInitialized());

  // It would be wasteful if these are not multiples of min_allocation_size.
  DCHECK_EQ(0, buffer_size % min_allocation_size);
  DCHECK_EQ(0, max_allocation_size % min_allocation_size);

  buf_size_ = buffer_size;
  min_alloc_size_ = min_allocation_size;
  max_alloc_size_ = max_allocation_size;

  return shared_mem_.CreateAndMapAnonymous(buf_size_);
}

bool ResourceBuffer::IsInitialized() const {
  return shared_mem_.memory() != NULL;
}

bool ResourceBuffer::ShareToProcess(
    base::ProcessHandle process_handle,
    base::SharedMemoryHandle* shared_memory_handle,
    int* shared_memory_size) {
  DCHECK(IsInitialized());

  if (!shared_mem_.ShareToProcess(process_handle, shared_memory_handle))
    return false;

  *shared_memory_size = buf_size_;
  return true;
}

bool ResourceBuffer::CanAllocate() const {
  DCHECK(IsInitialized());

  if (alloc_start_ == -1)
    return true;

  int diff = alloc_end_ - alloc_start_;
  if (diff > 0)
    return (buf_size_ - diff) >= min_alloc_size_;

  return -diff >= min_alloc_size_;
}

char* ResourceBuffer::Allocate(int* size) {
  DCHECK(CanAllocate());

  int alloc_offset = 0;
  int alloc_size;

  if (alloc_start_ == -1) {
    // This is the first allocation.
    alloc_start_ = 0;
    alloc_end_ = buf_size_;
    alloc_size = buf_size_;
  } else if (alloc_start_ < alloc_end_) {
    // Append the next allocation if it fits.  Otherwise, wraparound.
    //
    // NOTE: We could look to see if a larger allocation is possible by
    // wrapping around sooner, but instead we just look to fill the space at
    // the end of the buffer provided that meets the min_alloc_size_
    // requirement.
    //
    if ((buf_size_ - alloc_end_) >= min_alloc_size_) {
      alloc_offset = alloc_end_;
      alloc_size = buf_size_ - alloc_end_;
      alloc_end_ = buf_size_;
    } else {
      // It must be possible to allocate a least min_alloc_size_.
      DCHECK(alloc_start_ >= min_alloc_size_);
      alloc_size = alloc_start_;
      alloc_end_ = alloc_start_;
    }
  } else {
    // This is the wraparound case.
    DCHECK(alloc_end_ < alloc_start_);
    alloc_offset = alloc_end_;
    alloc_size = alloc_start_ - alloc_end_;
    alloc_end_ = alloc_start_;
  }

  // Make sure alloc_size does not exceed max_alloc_size_.  We store the
  // current value of alloc_size, so that we can use ShrinkLastAllocation to
  // trim it back.  This allows us to reuse the alloc_end_ adjustment logic.

  alloc_sizes_.push(alloc_size);

  if (alloc_size > max_alloc_size_) {
    alloc_size = max_alloc_size_;
    ShrinkLastAllocation(alloc_size);
  }

  *size = alloc_size;
  return static_cast<char*>(shared_mem_.memory()) + alloc_offset;
}

int ResourceBuffer::GetLastAllocationOffset() const {
  DCHECK(!alloc_sizes_.empty());
  DCHECK(alloc_end_ >= alloc_sizes_.back());
  return alloc_end_ - alloc_sizes_.back();
}

void ResourceBuffer::ShrinkLastAllocation(int new_size) {
  DCHECK(!alloc_sizes_.empty());

  int aligned_size = (new_size / min_alloc_size_) * min_alloc_size_;
  if (aligned_size < new_size)
    aligned_size += min_alloc_size_;

  DCHECK_LE(new_size, aligned_size);
  DCHECK_GE(alloc_sizes_.back(), aligned_size);

  int* last_allocation_size = &alloc_sizes_.back();
  alloc_end_ -= (*last_allocation_size - aligned_size);
  *last_allocation_size = aligned_size;
}

void ResourceBuffer::RecycleLeastRecentlyAllocated() {
  DCHECK(!alloc_sizes_.empty());
  int allocation_size = alloc_sizes_.front();
  alloc_sizes_.pop();

  alloc_start_ += allocation_size;
  DCHECK(alloc_start_ <= buf_size_);

  if (alloc_start_ == alloc_end_) {
    DCHECK(alloc_sizes_.empty());
    alloc_start_ = -1;
    alloc_end_ = -1;
  } else if (alloc_start_ == buf_size_) {
    DCHECK(!alloc_sizes_.empty());
    alloc_start_ = 0;
  }
}

}  // namespace content


text:
using Leaf.Nodes;

namespace Leaf.Serialization
{
    /// <summary>
    /// Redirection to latest node serializer.
    /// This interface is used so that nodes can reference this interface instead of the latest,
    /// which would change every time there's a new version.
    /// </summary>
    internal interface INodeWriter : IVersion1NodeWriter
    {
        /// <summary>
        /// Redirects to the correct serialization method.
        /// </summary>
        /// <param name="node">Node type to serialize.</param>
        void WriteNode(Node node);
    }
}


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { KnockoutTemplateReactComponent, registerReactControl } from 'dotvvm-jscomponent-react';
import { LineChart, XAxis, Tooltip, CartesianGrid, Line, Dot } from 'recharts';

// react component
function RechartComponent(props: any) {
    return (
        <LineChart
            width={400}
            height={400}
            data={props.data}
            margin={{ top: 5, right: 20, left: 10, bottom: 5 }} >
            <XAxis dataKey="name" />
            <Tooltip />
            <CartesianGrid stroke="#f5f5f5" />
            {
                Object.keys(props.data[0]).slice(1).map((s, i) =>
                    <Line type="monotone"
                        dataKey={s}
                        stroke={"#" + (i * 4).toString() + "87908"}
                        yAxisId={i}
                        onMouseEnter={(_) => props.onMouse(s)} />)
            }
        </LineChart>
    );
}

function TemplateSelector(props) {
    return <div>
        <KnockoutTemplateReactComponent
            wrapperTag="p"
            templateName={props.condition ? props.template1 : props.template2}
            getChildContext={c => c.extend({ $kokos: 1 })} />
    </div>
}

const Button = ({ text, click, dataUI }) =>
    <button onClick={e => click()} data-ui={dataUI}>{text}</button>

// DotVVM Context importer
export default (context) => ({
    $controls: {
        recharts: registerReactControl(RechartComponent, { context, onMouse() { /* default empty method */ } }),
        TemplateSelector: registerReactControl(TemplateSelector),
        Button: registerReactControl(Button)
    }
})


text:
static NSCharacterSet *_emailCharacterSet;

@implementation NSString (NSString_Util)
+(NSString*)makeString:(id)object withKeys:(NSArray*)keys andSeparator:(NSString*)separator{
    NSMutableString *rv = [NSMutableString string];
    for (NSString *k in keys) {
        id v = [object valueForKey:k];
        if (v) {
            if (separator && [rv length] > 0) {
                [rv appendString:separator];
            }
            [rv appendString:[v description]];
        }
    }
    return rv;
}

-(NSString*)withCharactersRemovedInSet:(NSCharacterSet*)characterSet {
    if ([self length]) {
        NSMutableString *rv = [NSMutableString stringWithString:self];
        NSRange r = [rv rangeOfCharacterFromSet:characterSet];
        while (r.location != NSNotFound) {
            [rv deleteCharactersInRange:r];
            r = [rv rangeOfCharacterFromSet:characterSet];
        }
        return [NSString stringWithString:rv];
    }
    return self;
}

-(NSString*)numericOnly {
    return [self withCharactersRemovedInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
}

-(NSString*)stringByStrippingLeadingOccurancesOf:(NSString*)string {
    NSMutableString *rv = [NSMutableString stringWithString:self];
    NSRange r = [rv rangeOfString:string];
    while (r.location == 0) {
        [rv deleteCharactersInRange:r];
        r = [rv rangeOfString:string];
    }
    return [NSString stringWithString:rv];
}

-(BOOL)isEmptyOrWhitespace {
    NSString *t = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return [t length] == 0;
}

-(NSString *)emailCharactersString {
    if (_emailCharacterSet == nil) {
        NSMutableCharacterSet *mcs = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
        [mcs addCharactersInString:@"-_.@"];
        _emailCharacterSet = [mcs copy];
        [mcs release];
    }

    return [self stringByTrimmingCharactersInSet:[_emailCharacterSet invertedSet]];
}

-(NSString*)alphaNumericString {
    return [self stringByTrimmingCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
}

-(BOOL)existsInArrayByValue:(NSArray *)a {
    for (id v in a) {
        if ([v isKindOfClass:[NSString class]] && [v isEqualToString:self]) {
            return true;
        }
    }
    return false;
}

@end


text:
import PelagosClient from 'lib/pelagosClient';
import pull from 'lodash/pull';
import uniq from 'lodash/uniq';
import sumBy from 'lodash/sumBy';

import {
  PLAYBACK_PRECISION,
  VESSELS_HEATMAP_STYLE_ZOOM_THRESHOLD,
  VESSELS_MINIMUM_RADIUS_FACTOR,
  VESSELS_MINIMUM_OPACITY,
  VESSEL_CLICK_TOLERANCE_PX,
  TIMELINE_OVERALL_START_DATE_OFFSET
} from 'config';

/**
 * From a timestamp in ms returns a time with the precision set in Constants.
 * @param timestamp
 */
export const getTimeAtPrecision = timestamp =>
  Math.floor(timestamp / PLAYBACK_PRECISION);

/**
 * From a timestamp in ms returns a time with the precision set in Constants, offseted at the
 * beginning of available time (outerStart)
 * @param timestamp
 */
export const getOffsetedTimeAtPrecision = timestamp =>
  Math.max(0, getTimeAtPrecision(timestamp) - TIMELINE_OVERALL_START_DATE_OFFSET);

/**
 * Generates the URLs to load vessel track data for a tile
 *
 * @param {string} tilesetUrl       the tileset base URL
 * @param {array} temporalExtents   all tileset temporal extents
 * @param {object} params           - seriesgroup: a seriesgroup id, used for tracks loading
 *                                  - tileCoordinates: this tiles tile coordinates (zoom, x, y). Will default to 0,0,0
 *                                  - temporalExtentsIndices: restrict to these temporalExtents indices
 * @returns {Array}                 an array of URLs for this tile
 */
const getTemporalTileURLs = (tilesetUrl, temporalExtents, params) => {
  const urls = [];
  (temporalExtents || [null]).forEach((extent, index) => {
    let url = `${tilesetUrl}/`;
    if (params.seriesgroup) {
      url += `sub/seriesgroup=${params.seriesgroup}/`;
    }
    if (extent !== null && params.temporalExtentsLess !== true) {
      const start = new Date(extent[0]).toISOString();
      const end = new Date(extent[1]).toISOString();
      url += `${start},${end};`;
    }
    if (params.tileCoordinates) {
      url += `${params.tileCoordinates.zoom},${params.tileCoordinates.x},${params.tileCoordinates.y}`;
    } else {
      // meh.
      url += '0,0,0';
    }
    if (!params.temporalExtentsIndices || params.temporalExtentsIndices.indexOf(index) > -1) {
      urls.push(url);
    }
  });
  return urls;
};

/**
 * See getTemporalTileURLs.
 */
export const getTilePelagosPromises = (tilesetUrl, token, temporalExtents, params) => {
  const promises = [];
  const urls = getTemporalTileURLs(
    tilesetUrl,
    temporalExtents,
    params
  );
  for (let urlIndex = 0, length = urls.length; urlIndex < length; urlIndex++) {
    promises.push(new PelagosClient().obtainTile(urls[urlIndex], token));
  }

  return promises;
};

export const getCleanVectorArrays = rawTileData => rawTileData.filter(vectorArray => vectorArray !== null);

/**
 * As data will come in multiple arrays (1 per API query/year basically), they need to be merged here
 *
 * @param cleanVectorArrays an array of objects containing a Float32Array for each vessel param (lat, lon, weight...)
 * @param columns the keys to pick on the vectorArrays (lat, lon, weight, etc)
 * @returns an object containing a Float32Array for each API_RETURNED_KEY (lat, lon, weight, etc)
 */
export const groupData = (cleanVectorArrays, columns) => {
  const data = {};

  const totalVectorArraysLength = sumBy(cleanVectorArrays, a => a.longitude.length);

  const filteredColumns = columns.filter((column) => {
    if (cleanVectorArrays[0] && cleanVectorArrays[0][column] === undefined) {
      console.warn(`column ${column} is present in layerHeader.colsByName but not in tile data`);
      return false;
    }
    return true;
  });

  filteredColumns.forEach((key) => {
    data[key] = new Float32Array(totalVectorArraysLength);
  });

  let currentArray;
  let cumulatedOffsets = 0;

  const appendValues = (key) => {
    data[key].set(currentArray[key], cumulatedOffsets);
  };

  for (let index = 0, length = cleanVectorArrays.length; index < length; index++) {
    currentArray = cleanVectorArrays[index];
    filteredColumns.forEach(appendValues);
    cumulatedOffsets += currentArray.longitude.length;
  }
  return data;
};

/**
 * Add projected lat/long values transformed as tile-relative x/y coordinates
 * @param vectorArray typed arrays, including latitude and longitude
 * @param map a reference to the original Google Map
 */
export const addWorldCoordinates = (vectorArray, map) => {
  const data = vectorArray;
  const proj = map.getProjection();
  data.worldX = new Float32Array(data.latitude.length);
  data.worldY = new Float32Array(data.longitude.length);
  for (let index = 0, length = data.latitude.length; index < length; index++) {
    const worldPoint = proj.fromLatLngToPoint(new google.maps.LatLng(data.latitude[index], data.longitude[index]));
    data.worldX[index] = worldPoint.x;
    data.worldY[index] = worldPoint.y;
  }
  return data;
};

const _getZoomFactorRadiusRenderingMode = zoom => ((zoom < VESSELS_HEATMAP_STYLE_ZOOM_THRESHOLD) ? 0.3 : 0.15);
const _getZoomFactorRadius = zoom => (zoom - 1) ** 2.5;
const _getRadius = (sigma, zoomFactorRadiusRenderingMode, zoomFactorRadius) => {
  let radius = zoomFactorRadiusRenderingMode * Math.max(0.8, 2 + Math.log(sigma * zoomFactorRadius));
  radius = Math.max(VESSELS_MINIMUM_RADIUS_FACTOR, radius);
  return radius;
};

/**
 * Converts Vector Array data to Playback format and stores it locally
 *
 * @param zoom the current zoom, used in radius calculations
 * @param vectorArray the source data before indexing by day
 * @param columns the columns present on the dataset, determined by tileset headers
 * @param prevPlaybackData an optional previously loaded tilePlaybackData array (when adding time range)
 */
export const getTilePlaybackData = (zoom, vectorArray, columns, prevPlaybackData) => {
  const tilePlaybackData = (prevPlaybackData === undefined) ? [] : prevPlaybackData;

  const zoomFactorRadius = _getZoomFactorRadius(zoom);
  const zoomFactorRadiusRenderingMode = _getZoomFactorRadiusRenderingMode(zoom);

  const zoomFactorOpacity = ((zoom - 1) ** 3.5) / 1000;

  // columns specified by header columns, remove a set of mandatory columns, remove unneeded columns
  let extraColumns = [].concat(columns);
  pull(extraColumns, 'x', 'y', 'weight', 'sigma', 'radius', 'opacity');  // those are mandatory thus manually added
  pull(extraColumns, 'latitude', 'longitude', 'datetime'); // we only need projected coordinates, ie x/y
  extraColumns = uniq(extraColumns);

  for (let index = 0, length = vectorArray.latitude.length; index < length; index++) {
    const datetime = vectorArray.datetime[index];

    const timeIndex = getOffsetedTimeAtPrecision(datetime);
    const worldX = vectorArray.worldX[index];
    const worldY = vectorArray.worldY[index];
    const weight = vectorArray.weight[index];
    const sigma = vectorArray.sigma[index];
    const radius = _getRadius(sigma, zoomFactorRadiusRenderingMode, zoomFactorRadius);
    let opacity = 3 + Math.log(weight * zoomFactorOpacity);
    // TODO quick hack to avoid negative values, check why that happens
    opacity = Math.max(0, opacity);
    opacity = 3 + Math.log(opacity);
    opacity = 0.1 + (0.2 * opacity);
    opacity = Math.min(1, Math.max(VESSELS_MINIMUM_OPACITY, opacity));

    if (!tilePlaybackData[timeIndex]) {
      const frame = {
        worldX: [worldX],
        worldY: [worldY],
        radius: [radius],
        opacity: [opacity]
      };
      extraColumns.forEach((column) => {
        frame[column] = [vectorArray[column][index]];
      });
      tilePlaybackData[timeIndex] = frame;
      continue;
    }
    const frame = tilePlaybackData[timeIndex];
    frame.worldX.push(worldX);
    frame.worldY.push(worldY);
    frame.radius.push(radius);
    frame.opacity.push(opacity);
    extraColumns.forEach((column) => {
      frame[column].push(vectorArray[column][index]);
    });
  }
  return tilePlaybackData;
};

export const addTracksPointsRenderingData = (data) => {
  data.hasFishing = [];

  for (let index = 0, length = data.weight.length; index < length; index++) {
    data.hasFishing[index] = data.weight[index] > 0;
  }
  return data;
};

/**
 * A simplified version of getTilePlaybackData for tracks
 * Converts Vector Array data to Playback format (organized by days) and stores it locally
 * @param vectorArray the source data before indexing by day
 */
export const getTracksPlaybackData = (vectorArray) => {
  const playbackData = [];

  for (let index = 0, length = vectorArray.series.length; index < length; index++) {
    const datetime = vectorArray.datetime[index];
    const timeIndex = getOffsetedTimeAtPrecision(datetime);

    if (!playbackData[timeIndex]) {
      const frame = {
        worldX: [vectorArray.worldX[index]],
        worldY: [vectorArray.worldY[index]],
        series: [vectorArray.series[index]],
        hasFishing: [vectorArray.hasFishing[index]]
      };
      playbackData[timeIndex] = frame;
      continue;
    }
    const frame = playbackData[timeIndex];
    frame.worldX.push(vectorArray.worldX[index]);
    frame.worldY.push(vectorArray.worldY[index]);
    frame.series.push(vectorArray.series[index]);
    frame.hasFishing.push(vectorArray.hasFishing[index]);
  }
  return playbackData;
};

export const vesselSatisfiesFilters = (frame, index, filterValues) => {
  const satisfiesFilters = Object.keys(filterValues).every((field) => {
    if (frame[field] === undefined) {
      // this field is not available on this layer. This can happen in an edge case described
      // here: https://github.com/Vizzuality/GlobalFishingWatch/issues/661#issuecomment-334496469
      return false;
    }
    return filterValues[field].indexOf(frame[field][index]) > -1;
  });
  return satisfiesFilters;
};

const vesselSatisfiesAllFilters = (frame, index, filters) => {
  const satisfiesAllFilters = filters
    .filter(f => f.pass !== true)
    .some(filter => vesselSatisfiesFilters(frame, index, filter.filterValues));
  return satisfiesAllFilters;
};

export const selectVesselsAt = (tileData, currentZoom, worldX, worldY, startIndex, endIndex, currentFilters) => {
  const vessels = [];

  // convert px tolerance/radius to world units
  const scale = 2 ** currentZoom;
  const vesselClickToleranceWorld = VESSEL_CLICK_TOLERANCE_PX / scale;

  for (let f = startIndex; f < endIndex; f++) {
    const frame = tileData[f];
    if (frame === undefined) continue;
    for (let i = 0; i < frame.worldX.length; i++) {
      const wx = frame.worldX[i];
      const wy = frame.worldY[i];

      if ((!currentFilters.length || vesselSatisfiesAllFilters(frame, i, currentFilters)) &&
          wx >= worldX - vesselClickToleranceWorld && wx <= worldX + vesselClickToleranceWorld &&
          wy >= worldY - vesselClickToleranceWorld && wy <= worldY + vesselClickToleranceWorld) {
        const vessel = {
          series: frame.series[i],
          seriesgroup: frame.seriesgroup[i]
        };

        vessels.push(vessel);
      }
    }
  }
  return vessels;
};

/*
export const getHistogram = (tiles, propName = 'weight') => {
  let data = tiles
    .filter(tile => tile.ready)
    .map(tile => tile.data
      .map(frame => frame[propName]));
  data = flattenDeep(data);
  if (data.length) {
    const bins = d3.histogram().thresholds(d3.thresholdScott)(data);
    const x = d3.scaleLinear().domain([0, d3.max(bins, d => d.length)]).range([0, 50]);
    console.table(bins.filter(bin => bin.length).map((bin) => {
      const binMin = d3.min(bin).toLocaleString({ maximumFractionDigits: 2 });
      const binMax = d3.max(bin).toLocaleString({ maximumFractionDigits: 2 });
      return {
        range: [binMin, binMax].join('﹣'),
        bars: Array(Math.round(x(bin.length))).join('█'),
        num: bin.length
      };
    }));
  }
};
*/


text:
package io.grpc.examples.helloworld;
import io.grpc.ServerImpl;
import io.grpc.stub.StreamObserver;
import io.grpc.transport.netty.NettyServerBuilder;

import java.util.logging.Logger;

/**
 * Server that manages startup/shutdown of a {@code Greeter} server.
 */
public class PollServer {
  private static final Logger logger = Logger.getLogger(PollServer.class.getName());

  /* The port on which the server should run */
  private int port = 50051;
  private ServerImpl server;

  private void start() throws Exception {
    server = NettyServerBuilder.forPort(port)
        .addService(PollServiceGrpc.bindService(new PollServiceImpl()))
        .build().start();
    logger.info("Server started, listening on " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        // Use stderr here since the logger may have been reset by its JVM shutdown hook.
        System.err.println("*** shutting down gRPC server since JVM is shutting down");
        PollServer.this.stop();
        System.err.println("*** server shut down");
      }
    });
  }

  private void stop() {
    if (server != null) {
      server.shutdown();
    }
  }

  /**
   * Main launches the server from the command line.
   */
  public static void main(String[] args) throws Exception {
    final PollServer server = new PollServer();
    server.start();
  }

  private class PollServiceImpl implements PollServiceGrpc.PollService {

private String moderatorId;

    @Override
    public void createPoll(PollRequest req, StreamObserver<PollResponse> responseObserver) {
      logger.info("Moderator ID from request is : " + req.getModeratorId());
      PollResponse reply = PollResponse.newBuilder().setId("Xyzzy").build();
      responseObserver.onValue(reply);
      responseObserver.onCompleted();
    }
  }
}


text:
package nineclue.md2blogger

import org.markdown4j.{Markdown4jProcessor, Plugin}
import io.Source._
import java.nio.file.Files

object Md2Blogger {
  def main(args:Array[String]) {
    Dir.loadOrInit
    val sArgs = args.map(_.toLowerCase)
    if (args.size > 1 && (args(0) == "rm" || args(0) == "del")) {
      val deletions = args.tail.filter(Dir.contains(_))
      println("unmanaging files : " + deletions.mkString(", "))
      Dir.removeFiles(deletions)
    } else {
      BlogAPI.loadOrInit
      val updates = Dir.updates
      Dir.printUpdates(updates)
      if (updates.size > 0) {
        var answer:String = ""
        do {
          print("Proceed to updates blogger (Y/n) : ")
          answer = System.console.readLine.stripLineEnd.toLowerCase
        } while (answer != "" && answer != "y" && answer != "n")
        if (answer == "" || answer == "y")
          BlogAPI.updatePosts(updates)
      }
    }
  }
}


text:
layout: post
unique_id: trx
title: TRX
categories: []
locations:
---

YESTERDAY:
* woke up a bit groggy
* checked mail and they did indeed give me a new wallet!
  * leggings arrived, they look hella tiny!
  * also got an extra case for my phone which I think is a messup?
* set up a tire lecture for the team today
  * then gave my own presentation on our Goodyear collaboration
* super productive, cranked out flash logging and fixed a bug
* took almost an hour worth of naps today since throat was sore
* congee for lunch which was just right
* left work around 7 and found a TRX class at PG Belmont
  * instructor was pretty friendly and motivating, might come back to this one
* panda for dinner
* 10:30 pm sync with Michael
* bit of guitar afterwards

TODAY:
* morning syncs withe everybody
* quick lunch
* back to work
* flee down to San Jose
  * discussion took longer than expected
* worked out of a Starbucks until 6 pm ish
* late night sync with hardware engineer
* got home in time for dinner with parents

LEARNINGS:
* what it's like running around with the co-founder


text:
package com.jtbdevelopment.games.state;

import com.jtbdevelopment.games.players.Player;
import java.beans.Transient;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * Date: 12/31/2014 Time: 4:56 PM
 */
public interface Game<ID extends Serializable, TIMESTAMP, FEATURES> {

  ID getId();

  void setId(final ID id);

  @Transient
  String getIdAsString();

  Integer getVersion();

  void setVersion(final Integer version);

  ID getPreviousId();

  void setPreviousId(final ID previousID);

  @Transient
  String getPreviousIdAsString();

  int getRound();

  void setRound(final int round);

  TIMESTAMP getCreated();

  void setCreated(final TIMESTAMP created);

  TIMESTAMP getLastUpdate();

  void setLastUpdate(final TIMESTAMP lastUpdate);

  TIMESTAMP getCompletedTimestamp();

  void setCompletedTimestamp(final TIMESTAMP completed);

  Set<FEATURES> getFeatures();

  void setFeatures(final Set<FEATURES> features);

  GamePhase getGamePhase();

  void setGamePhase(final GamePhase gamePhase);

  List<Player<ID>> getAllPlayers();
}


text:
import os

_resources_dir = os.path.join(
    os.path.realpath(os.path.dirname(__file__)),
    'resources'
)

def get_pcap_path(capture_file):
    return os.path.join(_resources_dir, '%s.pcap' % (capture_file))

def get_log_path(log_file):
    return os.path.join(_resources_dir, '%s.logfile' % (log_file))

def get_thrift_path(thrift_file):
    return os.path.join(_resources_dir, '%s.thrift' % (thrift_file))


text:
<?php
//class start
class NM_addCustomButton_filemanager {

public $btn_arr;
public $js_file;
/*
 * call the constructor and set class variables
 * From the constructor call the functions via wordpress action/filter
*/
function __construct($seperator, $btn_name,$javascrip_location){
  $this->btn_arr = array("Seperator"=>$seperator,"Name"=>$btn_name);
  $this->js_file = $javascrip_location;
  add_action('init', array(&$this,'addTinyMCEButton'));
  add_filter( 'tiny_mce_version', array(&$this,'refreshMCEVersion'));

}
/*
 * create the buttons only if the user has editing privs.
 * If so we create the button and add it to the tinymce button array
*/
function addTinyMCEButton() {
   if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
     return;
   if ( get_user_option('rich_editing') == 'true') {
     //the function that adds the javascript
     add_filter('mce_external_plugins', array(&$this,'addNewTinyMCEPlugin'));
	 //adds the button to the tinymce button array
     add_filter('mce_buttons', array(&$this,'registerNewButton'));
   }
}
/*
 * add the new button to the tinymce array
*/
function registerNewButton($buttons) {
   array_push($buttons, $this->btn_arr["Seperator"],$this->btn_arr["Name"]);
   return $buttons;
}
/*
 * Call the javascript file that loads the
 * instructions for the new button
*/
function addNewTinyMCEPlugin($plugin_array) {
   $plugin_array[$this->btn_arr['Name']] = $this->js_file;
   return $plugin_array;
}
/*
 * This function tricks tinymce in thinking
 * it needs to refresh the buttons
*/
function refreshMCEVersion($ver) {
  $ver += 3;
  return $ver;
}

}//class end
?>


text:
package protocol

import (
	"io"

	mssql "github.com/denisenkom/go-mssqldb"
)

func readUcs2(r io.Reader, numchars int) (string, error) {
	buf := make([]byte, numchars)
	_, err := io.ReadFull(r, buf)
	if err != nil {
		return "", err
	}
	return mssql.ParseUCS2String(buf)
}


text:
package org.apache.rocketmq.store.schedule;

import java.util.concurrent.ConcurrentHashMap;
import org.apache.rocketmq.remoting.protocol.RemotingSerializable;

public class DelayOffsetSerializeWrapper extends RemotingSerializable {
    private ConcurrentHashMap<Integer /* level */, Long/* offset */> offsetTable =
        new ConcurrentHashMap<Integer, Long>(32);

    public ConcurrentHashMap<Integer, Long> getOffsetTable() {
        return offsetTable;
    }

    public void setOffsetTable(ConcurrentHashMap<Integer, Long> offsetTable) {
        this.offsetTable = offsetTable;
    }
}


text:
.include <bsd.own.mk>

.if ${MKDOC} != "no"						# {

BINDIR=	${PFIX_HTMLDIR}

DIST=	${NETBSDSRCDIR}/external/ibm-public/postfix/dist/html
.PATH:	${DIST}

PFX_DAEMONS= anvil.8.html bounce.8.html cleanup.8.html discard.8.html \
	dnsblog.8.html error.8.html flush.8.html lmtp.8.html local.8.html \
	master.8.html oqmgr.8.html pickup.8.html pipe.8.html \
	postscreen.8.html proxymap.8.html qmgr.8.html scache.8.html \
	showq.8.html smtp.8.html smtpd.8.html spawn.8.html tlsmgr.8.html \
	tlsproxy.8.html trivial-rewrite.8.html verify.8.html virtual.8.html
PFX_COMMANDS= postalias.1.html postcat.1.html \
	postconf.1.html postdrop.1.html postfix.1.html postkick.1.html \
	postlock.1.html postlog.1.html postmap.1.html postqueue.1.html \
	postsuper.1.html qshape.1.html sendmail.1.html smtp-sink.1.html \
	smtp-source.1.html postmulti.1.html posttls-finger.1.html
PFX_CONFIG= access.5.html aliases.5.html canonical.5.html cidr_table.5.html \
	generic.5.html header_checks.5.html ldap_table.5.html \
	master.5.html mysql_table.5.html nisplus_table.5.html \
	pcre_table.5.html pgsql_table.5.html postconf.5.html \
	regexp_table.5.html relocated.5.html sqlite_table.5.html \
	transport.5.html virtual.5.html postfix-wrapper.5.html \
	postfix-manuals.html memcache_table.5.html

.include "../readme.mk"
.for PFX_README in ${PFIX_README_FILES}
PFX_READMES+=	${PFX_README}.html
.endfor

FILES=	$(PFX_DAEMONS) $(PFX_COMMANDS) $(PFX_CONFIG) $(PFX_READMES) \
	index.html postconf.5.html OVERVIEW.html postfix-logo.jpg

SYMLINKS= bounce.8.html ${BINDIR}/defer.8.html
SYMLINKS+=bounce.8.html ${BINDIR}/trace.8.html
SYMLINKS+=sendmail.1.html ${BINDIR}/mailq.1.html
SYMLINKS+=sendmail.1.html ${BINDIR}/newaliases.1.html

.endif								# }

.include <bsd.prog.mk>


text:
module BikesHelper

  def print_val(key, val)
    return nil if val.blank?
    case key
    when 'color'
      val.respond_to?(:name) ? val.name.capitalize : ColorNameI18n::Color.new(val).name.capitalize
    when 'seat_tube_height'
      "#{round_units(val, 'inch')} (#{round_units(val, 'cm')})"
    when 'top_tube_length'
      "#{round_units(val, 'inch')} (#{round_units(val, 'cm')})"
    when 'wheel_size'
      "#{val} mm"
    when 'bike_model_id'
      BikeModel.where(:id => val.to_i ).first.to_s
    when 'quality'
      val.capitalize
    when 'condition'
      val.capitalize
    when 'value'
      sprintf("$%.2f", val)
    when 'number_record'
      val
    end
  end # def changeset_val

  def filter_link_class(key)
    key_default = params[:status].blank? && key.to_s == 'all'
    key_active = key.to_s == params[:status]
    return (key_default || key_active) ? 'active' : 'option'
  end

end # module BikesHelper


text:
static inline uint32 ConvertAdcCountsToPicovolts(uint32 counts);
static inline uint16 ConvertPicovoltsToMillivolts(uint32 picovolts);

//
// PUBLIC METHODS
//

void Adc_StartTemperatureSensorConversion(void)
{
  AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
}

bool Adc_TemperatureSensorSampleReady(void)
{
  return ((AT91C_BASE_ADC->ADC_SR & AT91C_ADC_EOC4) == AT91C_ADC_EOC4);
}

uint16 Adc_ReadTemperatureSensor(void)
{
  uint32 picovolts = ConvertAdcCountsToPicovolts(AT91C_BASE_ADC->ADC_CDR4);
  return ConvertPicovoltsToMillivolts(picovolts);
}

//
// PRIVATE HELPERS
//

static inline uint32 ConvertAdcCountsToPicovolts(uint32 counts)
{
  // ADC bit weight at 10-bit resolution with 3.0V reference = 2.9296875 mV/LSB
  uint32 picovoltsPerAdcCount = 2929688;

  // Shift decimal point by 6 places to preserve accuracy in fixed-point math
  return counts * picovoltsPerAdcCount;
}

static inline uint16 ConvertPicovoltsToMillivolts(uint32 picovolts)
{
  const uint32 halfMillivoltInPicovolts = 500000;
  const uint32 picovoltsPerMillivolt = 1000000;

  // Add 0.5 mV to result so that truncation yields properly rounded result
  picovolts += halfMillivoltInPicovolts;

  // Divide appropriately to convert to millivolts
  return (uint16)(picovolts / picovoltsPerMillivolt);
}


text:
package org.kuali.kfs.fp.document;

import java.math.BigDecimal;

import org.kuali.kfs.coa.businessobject.IndirectCostRecoveryAccount;
import org.kuali.kfs.fp.document.validation.impl.IndirectCostAdjustmentDocumentRuleConstants;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySourceDetail;
import org.kuali.kfs.sys.businessobject.SourceAccountingLine;
import org.kuali.kfs.sys.businessobject.TargetAccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocumentBase;
import org.kuali.kfs.sys.document.AmountTotaling;
import org.kuali.kfs.sys.document.Correctable;
import org.kuali.kfs.sys.document.service.DebitDeterminerService;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.krad.document.Copyable;
import org.kuali.rice.krad.exception.InfrastructureException;

public class IndirectCostAdjustmentDocument extends AccountingDocumentBase implements Copyable, Correctable, AmountTotaling {

    /**
     * Constructs a IndirectCostAdjustmentDocument.java.
     */
    public IndirectCostAdjustmentDocument() {
        super();
    }

    /**
     * @see org.kuali.kfs.sys.document.AccountingDocument#getSourceAccountingLinesSectionTitle()
     */
    @Override
    public String getSourceAccountingLinesSectionTitle() {
        return KFSConstants.GRANT;
    }

    /**
     * @see org.kuali.kfs.sys.document.AccountingDocument#getTargetAccountingLinesSectionTitle()
     */
    @Override
    public String getTargetAccountingLinesSectionTitle() {
        return KFSConstants.ICR;
    }

    /**
     * per ICA specs, adds a target(receipt) line when an source(grant) line is added using the following logic to populate the
     * target line.
     *

     *
receipt line's chart = chart from grant line
     *
receipt line's account = ICR account for the account entered on the grant line
     *
receipt line's object code = Financial System Parameter APC for the document global receipt line object code (see APC
     * setion below)
     *
receipt line's amount = amount from grant line
     *

     *
     * @see org.kuali.kfs.sys.document.AccountingDocumentBase#addSourceAccountingLine(SourceAccountingLine)
     */
    @Override
    public void addSourceAccountingLine(SourceAccountingLine line) {
        // add source
        super.addSourceAccountingLine(line);

        for (IndirectCostRecoveryAccount icrAccount : line.getAccount().getActiveIndirectCostRecoveryAccounts()){

            KualiDecimal percentDecimal = new KualiDecimal(icrAccount.getAccountLinePercent().divide(new BigDecimal(100)));

            // create and populate target line
            TargetAccountingLine targetAccountingLine = null;
            try {
                targetAccountingLine = (TargetAccountingLine) getTargetAccountingLineClass().newInstance();
            }
            catch (Exception e) {
                throw new InfrastructureException("unable to create a target accounting line", e);
            }
            // get apc object code value
            String objectCode = SpringContext.getBean(ParameterService.class).getParameterValueAsString(IndirectCostAdjustmentDocument.class, IndirectCostAdjustmentDocumentRuleConstants.RECEIPT_OBJECT_CODE);
            targetAccountingLine.setFinancialObjectCode(objectCode);
            targetAccountingLine.setAccountNumber(icrAccount.getIndirectCostRecoveryAccountNumber());
            targetAccountingLine.setChartOfAccountsCode(icrAccount.getIndirectCostRecoveryFinCoaCode());
            targetAccountingLine.setDocumentNumber(line.getDocumentNumber());
            targetAccountingLine.setPostingYear(line.getPostingYear());
            targetAccountingLine.setAmount(line.getAmount().multiply(percentDecimal));
            // refresh reference objects

            targetAccountingLine.refresh();
            // add target line
            addTargetAccountingLine(targetAccountingLine);
        }
    }

    /**
     * Same logic as IsDebitUtils#isDebitConsideringType(FinancialDocumentRuleBase, FinancialDocument, AccountingLine)
     * but has the following accounting line restrictions:
     *
     * for grant lines(source):
     *

     *
only allow expense object type codes
     *

     * for receipt lines(target):
     *

     *
only allow income object type codes
     *

     *
     * @param transactionDocument The document associated with the accounting line being reviewed to determine if it's a debit.
     * @param accountingLine The accounting line being reviewed to determine if it's a debit line.
     * @return True if the accounting line is a debit.  See IsDebitUtils.isDebitConsideringType().
     * @throws IllegalStateException Thrown if the accounting line given is a source accounting line representing an expense
     * or is a target accounting line representing an income.
     *
     * @see IsDebitUtils#isDebitConsideringType(FinancialDocumentRuleBase, FinancialDocument, AccountingLine)
     * @see org.kuali.rice.krad.rule.AccountingLineRule#isDebit(org.kuali.rice.krad.document.FinancialDocument,
     *      org.kuali.rice.krad.bo.AccountingLine)
     */
    public boolean isDebit(GeneralLedgerPendingEntrySourceDetail postable) throws IllegalStateException {
        AccountingLine accountingLine = (AccountingLine)postable;
        DebitDeterminerService isDebitUtils = SpringContext.getBean(DebitDeterminerService.class);
        if (!(accountingLine.isSourceAccountingLine() && isDebitUtils.isExpense(accountingLine)) && !(accountingLine.isTargetAccountingLine() && isDebitUtils.isIncome(accountingLine))) {
            throw new IllegalStateException(isDebitUtils.getDebitCalculationIllegalStateExceptionMessage());
        }

        return isDebitUtils.isDebitConsideringType(this, accountingLine);
    }
}


text:
package com.xiaoleilu.hutool.bloomFilter.bitMap;

public interface BitMap {

	public final int MACHINE32 = 32;
	public final int MACHINE64 = 64;

	public void add(long i);

	public boolean contains(long i);

	public void remove(long i);
}


text:
<?xml version='1.0' encoding='utf-8'?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:id="PrL-0982">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Private Letter: 1897 January 24: to de Lisle</title>
            <author>
               <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/9614/">William Colenso</name>
            </author>
         </titleStmt>
         <publicationStmt>

         </publicationStmt>
         <sourceDesc>

MTG HB m64/14, m67/37, 57844.

         </sourceDesc>
      </fileDesc>
      <profileDesc>
         <correspDesc>

               <correspAction type="received">
                  <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/75171/">de Lisle</name>
               </correspAction>
            </correspDesc>
         <creation xmlns:tei="http://www.tei-c.org/ns/1.0">
            <date when="1897-01-24">1897 January 24</date>
         </creation>
      </profileDesc>
   </teiHeader>
   <text>
      <front>

1897 January 24: to de Lisle<note xml:id="ftn3-810" place="foot" n="810"> MTG HB m64/14, m67/37, 57844.</note>

      </front>

Sunday night,<lb/>Jany. 24<hi rend="sup">th</hi>./ 97.

My dear Dr. de Lisle

I was not a little upset yesterday in seeing in the <hi rend="italic">Herald</hi> of your severe accident:—it being under the heading of "Hastings" news. I did <hi rend="italic">not </hi>see it <hi rend="italic">early</hi>, so waited for the <hi rend="italic">Evg</hi>. paper, supposing that <hi rend="italic">there</hi> I should find the full account, but was disappointed,—and then began to hope that your own injuries were magnified: and further intended, that in my going to Cathedral <hi rend="italic">this mg.</hi> I would call and learn: but I did not go out, (I have not been down for <hi rend="italic">all</hi>
            <hi rend="italic">last</hi> week,)—and I shall send this by my man in the morning, that he may <hi rend="italic">enquire</hi>, and bring me back a reply.—I sincerely hope that <hi rend="italic">you have not </hi>any <hi rend="italic">broken </hi>bones. <hi rend="italic">One item</hi>—even in that sad local—that served to cheer me, was, that Mrs. de Lisle & baby had received <hi rend="underline italic">no</hi> injury; I hope this is true—though I fear <hi rend="italic">somewhat</hi>.——

I duly received your kind note, and will be <hi rend="italic">sure </hi>to call on you: some early morning when I go to town.—

With kind regards and best wishes, and <hi rend="italic">good hopes</hi>.

         Believe me,

                         Yours faithy.

                                         W. Colenso.

   </text>
</TEI>