text:
package org.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.impl;

import java.util.Collections;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.Collectors;

import javax.enterprise.context.Dependent;

import org.drools.workbench.models.guided.dtable.shared.model.ActionCol52;
import org.drools.workbench.models.guided.dtable.shared.model.ActionInsertFactCol52;
import org.drools.workbench.models.guided.dtable.shared.model.ActionWorkItemInsertFactCol52;
import org.drools.workbench.models.guided.dtable.shared.model.BaseColumn;
import org.drools.workbench.models.guided.dtable.shared.model.BaseColumnFieldDiff;
import org.drools.workbench.models.guided.dtable.shared.model.BaseColumnFieldDiffImpl;
import org.drools.workbench.models.guided.dtable.shared.model.LimitedEntryCol;
import org.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.ModelSynchronizer;
import org.drools.workbench.screens.guided.dtable.client.widget.table.model.synchronizers.ModelSynchronizer.VetoException;

@Dependent
public class ActionInsertFactColumnSynchronizer extends ActionColumnSynchronizer {

    @Override
    public int priority() {
        return 1;
    }

    @Override
    public boolean handlesAppend(final MetaData metaData) throws VetoException {
        return handlesUpdate(metaData);
    }

    @Override
    public void append(final ColumnMetaData metaData) throws VetoException {
        if (!handlesAppend(metaData)) {
            return;
        }

        final ActionInsertFactCol52 column = (ActionInsertFactCol52) metaData.getColumn();
        final OptionalInt targetIndex = findLastIndexOfActionInsertFactColumn(column);
        if (targetIndex.isPresent()) {
            model.getActionCols().add(targetIndex.getAsInt() + 1,
                                      column);
            synchroniseAppendColumn(column);
        } else {
            model.getActionCols().add(column);
            synchroniseAppendColumn(column);
        }
    }

    @Override
    public boolean handlesUpdate(final MetaData metaData) throws VetoException {
        if (!(metaData instanceof ColumnMetaData)) {
            return false;
        }
        return ((ColumnMetaData) metaData).getColumn() instanceof ActionInsertFactCol52;
    }

    @Override
    public List<BaseColumnFieldDiff> update(final ColumnMetaData originalMetaData,
                                            final ColumnMetaData editedMetaData) throws VetoException {
        //Check operation is supported
        if (!(handlesUpdate(originalMetaData) && handlesUpdate(editedMetaData))) {
            return Collections.emptyList();
        }

        //Get differences between original and edited column
        final ActionInsertFactCol52 originalColumn = (ActionInsertFactCol52) originalMetaData.getColumn();
        final ActionInsertFactCol52 editedColumn = (ActionInsertFactCol52) editedMetaData.getColumn();

        final List<BaseColumnFieldDiff> diffs = originalColumn.diff(editedColumn);

        update(originalColumn,
               editedColumn);

        final boolean isHideUpdated = BaseColumnFieldDiffImpl.hasChanged(ActionInsertFactCol52.FIELD_HIDE_COLUMN,
                                                                         diffs);
        final boolean isHeaderUpdated = BaseColumnFieldDiffImpl.hasChanged(ActionInsertFactCol52.FIELD_HEADER,
                                                                           diffs);
        final boolean isBoundNameUpdated = BaseColumnFieldDiffImpl.hasChanged(ActionInsertFactCol52.FIELD_BOUND_NAME,
                                                                              diffs);
        final boolean isFactTypeUpdated = BaseColumnFieldDiffImpl.hasChanged(ActionInsertFactCol52.FIELD_FACT_TYPE,
                                                                             diffs);
        final boolean isFactFieldUpdated = BaseColumnFieldDiffImpl.hasChanged(ActionInsertFactCol52.FIELD_FACT_FIELD,
                                                                              diffs);

        if (isBoundNameUpdated || isFactTypeUpdated || isFactFieldUpdated) {
            clearColumnData(originalColumn);
        } else {
            cleanColumnData(originalColumn,
                            editedColumn,
                            diffs);
        }

        synchroniseUpdateColumn(originalColumn);

        if (isHideUpdated) {
            setColumnVisibility(originalColumn,
                                originalColumn.isHideColumn());
        }
        if (isHeaderUpdated) {
            setColumnHeader(originalColumn,
                            originalColumn.getHeader());
        }

        return diffs;
    }

    private void cleanColumnData(final ActionInsertFactCol52 originalColumn,
                                 final ActionInsertFactCol52 editedColumn,
                                 final List<BaseColumnFieldDiff> diffs) {
        final boolean isValueListUpdated = BaseColumnFieldDiffImpl.hasChanged(ActionInsertFactCol52.FIELD_VALUE_LIST,
                                                                              diffs);

        // Update column's cell content if the Optional Value list has changed
        if (isValueListUpdated) {
            updateCellsForOptionValueList(originalColumn,
                                          editedColumn);
        }
    }

    private void update(final ActionInsertFactCol52 originalColumn,
                        final ActionInsertFactCol52 editedColumn) {
        originalColumn.setBoundName(editedColumn.getBoundName());
        originalColumn.setType(editedColumn.getType());
        originalColumn.setFactField(editedColumn.getFactField());
        originalColumn.setHeader(editedColumn.getHeader());
        originalColumn.setValueList(editedColumn.getValueList());
        originalColumn.setDefaultValue(editedColumn.getDefaultValue());
        originalColumn.setHideColumn(editedColumn.isHideColumn());
        originalColumn.setFactType(editedColumn.getFactType());
        originalColumn.setInsertLogical(editedColumn.isInsertLogical());
        if (originalColumn instanceof LimitedEntryCol && editedColumn instanceof LimitedEntryCol) {
            ((LimitedEntryCol) originalColumn).setValue(((LimitedEntryCol) editedColumn).getValue());
        }
    }

    @Override
    public boolean handlesMoveColumnsTo(final List<? extends MetaData> metaData) throws ModelSynchronizer.MoveVetoException {
        final boolean isActionInsetFactFragment = isActionInsertFactFragment(metaData);
        if (!isActionInsetFactFragment) {
            return false;
        }

        final List<ActionCol52> columnsToMove = metaData.stream()
                .map(c -> (MoveColumnToMetaData) c)
                .map(MoveColumnToMetaData::getColumn)
                .map(c -> (ActionInsertFactCol52) c)
                .collect(Collectors.toList());

        final String binding = ((ActionInsertFactCol52) columnsToMove.get(0)).getBoundName();
        final int tgtIndex = ((MoveColumnToMetaData) metaData.get(0)).getTargetColumnIndex();
        final List<BaseColumn> modelColumns = model.getExpandedColumns();

        //Cannot move "Insert and Set field" to before the Facts creation by WID
        return model.getActionCols().stream()
                .filter(c -> !columnsToMove.contains(c))
                .filter(c -> c instanceof ActionWorkItemInsertFactCol52)
                .map(c -> (ActionWorkItemInsertFactCol52) c)
                .filter(c -> c.getBoundName().equals(binding))
                .map(modelColumns::indexOf)
                .noneMatch(i -> i >= tgtIndex);
    }

    private boolean isActionInsertFactFragment(final List<? extends MetaData> metaData) {
        if (!metaData.stream().allMatch((c) -> (c instanceof MoveColumnToMetaData))) {
            return false;
        }
        if (!metaData.stream().map(c -> (MoveColumnToMetaData) c).allMatch(c -> c.getColumn() instanceof ActionInsertFactCol52)) {
            return false;
        }
        final int lastMetaDataIndex = metaData.size() - 1;
        final BaseColumn firstColumnInFragment = ((MoveColumnToMetaData) metaData.get(0)).getColumn();
        final BaseColumn lastColumnInFragment = ((MoveColumnToMetaData) metaData.get(lastMetaDataIndex)).getColumn();
        final int firstColumnIndex = model.getExpandedColumns().indexOf(firstColumnInFragment);
        final int lastColumnIndex = model.getExpandedColumns().indexOf(lastColumnInFragment);
        return lastColumnIndex - firstColumnIndex == lastMetaDataIndex;
    }

    @Override
    protected void setColumnHeader(final BaseColumn modelColumn,
                                   final String header) {
        modelColumn.setHeader(header);
        final int iModelColumn = model.getExpandedColumns().indexOf(modelColumn);
        uiModel.getColumns().get(iModelColumn).getHeaderMetaData().get(1).setTitle(header);
    }
}


text:
namespace Merchello.Core.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using Events;
    using Models;
    using Persistence;
    using Persistence.Querying;
    using Persistence.UnitOfWork;
    using Umbraco.Core;
    using Umbraco.Core.Events;
    using Umbraco.Core.Logging;

    /// <summary>
    /// Represents a warehouse catalog service.
    /// </summary>
    internal class WarehouseCatalogService : MerchelloRepositoryService, IWarehouseCatalogService
    {
        #region Fields

        /// <summary>
        /// The locker.
        /// </summary>
        private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

        /// <summary>
        /// The product variant service.
        /// </summary>
        private readonly IProductVariantService _productVariantService;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="WarehouseCatalogService"/> class.
        /// </summary>
        internal WarehouseCatalogService()
            : this(LoggerResolver.Current.Logger)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="WarehouseCatalogService"/> class.
        /// </summary>
        /// <param name="logger">
        /// The logger.
        /// </param>
        internal WarehouseCatalogService(ILogger logger)
            : this(new RepositoryFactory(), logger, new ProductVariantService(logger))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="WarehouseCatalogService"/> class.
        /// </summary>
        /// <param name="repositoryFactory">
        /// The repository factory.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="productVariantService">
        /// The product Variant Service.
        /// </param>
        internal WarehouseCatalogService(RepositoryFactory repositoryFactory, ILogger logger, IProductVariantService productVariantService)
            : this(new PetaPocoUnitOfWorkProvider(logger), repositoryFactory, logger, productVariantService)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="WarehouseCatalogService"/> class.
        /// </summary>
        /// <param name="provider">
        /// The provider.
        /// </param>
        /// <param name="repositoryFactory">
        /// The repository factory.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="productVariantService">
        /// The product Variant Service.
        /// </param>
        internal WarehouseCatalogService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IProductVariantService productVariantService)
            : this(provider, repositoryFactory, logger, new TransientMessageFactory(), productVariantService)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="WarehouseCatalogService"/> class.
        /// </summary>
        /// <param name="provider">
        /// The provider.
        /// </param>
        /// <param name="repositoryFactory">
        /// The repository factory.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="eventMessagesFactory">
        /// The event messages factory.
        /// </param>
        /// <param name="productVariantService">
        /// The product variant service.
        /// </param>
        internal WarehouseCatalogService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IProductVariantService productVariantService)
            : base(provider, repositoryFactory, logger, eventMessagesFactory)
        {
            Mandate.ParameterNotNull(productVariantService, "productVariantService");
            _productVariantService = productVariantService;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Occurs after Create
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, Events.NewEventArgs<IWarehouseCatalog>> Creating;

        /// <summary>
        /// Occurs after Create
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, Events.NewEventArgs<IWarehouseCatalog>> Created;

        /// <summary>
        /// Occurs before Save
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, SaveEventArgs<IWarehouseCatalog>> Saving;

        /// <summary>
        /// Occurs after Save
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, SaveEventArgs<IWarehouseCatalog>> Saved;

        /// <summary>
        /// Occurs before an invoice status has changed
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, StatusChangeEventArgs<IWarehouseCatalog>> StatusChanging;

        /// <summary>
        /// Occurs after an invoice status has changed
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, StatusChangeEventArgs<IWarehouseCatalog>> StatusChanged;

        /// <summary>
        /// Occurs before Delete
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, DeleteEventArgs<IWarehouseCatalog>> Deleting;

        /// <summary>
        /// Occurs after Delete
        /// </summary>
        public static event TypedEventHandler<IWarehouseCatalogService, DeleteEventArgs<IWarehouseCatalog>> Deleted;

        #endregion

        /// <summary>
        /// Creates warehouse catalog and persists it to the database.
        /// </summary>
        /// <param name="warehouseKey">
        /// The warehouse key.
        /// </param>
        /// <param name="name">
        /// The name.
        /// </param>
        /// <param name="description">
        /// The description.
        /// </param>
        /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param>
        /// <returns>
        /// The <see cref="IWarehouseCatalog"/>.
        /// </returns>
        public IWarehouseCatalog CreateWarehouseCatalogWithKey(
            Guid warehouseKey,
            string name,
            string description = "",
            bool raiseEvents = true)
        {
            Mandate.ParameterCondition(!warehouseKey.Equals(Guid.Empty), "warehouseKey");

            var catalog = new WarehouseCatalog(warehouseKey) { Name = name, Description = description };

            if (raiseEvents)
            if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs<IWarehouseCatalog>(catalog), this))
            {
                catalog.WasCancelled = true;
                return catalog;
            }

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(uow))
                {
                    repository.AddOrUpdate(catalog);
                    uow.Commit();
                }
            }

            if (raiseEvents) Created.RaiseEvent(new Events.NewEventArgs<IWarehouseCatalog>(catalog), this);

            return catalog;
        }

        /// <summary>
        /// Saves a single <see cref="IWarehouseCatalog"/>.
        /// </summary>
        /// <param name="warehouseCatalog">
        /// The warehouse catalog.
        /// </param>
        /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param>
        public void Save(IWarehouseCatalog warehouseCatalog, bool raiseEvents = true)
        {
            if (raiseEvents)
            if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IWarehouseCatalog>(warehouseCatalog), this))
            {
                ((WarehouseCatalog)warehouseCatalog).WasCancelled = true;
                return;
            }

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(uow))
                {
                    repository.AddOrUpdate(warehouseCatalog);
                    uow.Commit();
                }
            }

            if (raiseEvents) Saved.RaiseEvent(new SaveEventArgs<IWarehouseCatalog>(warehouseCatalog), this);
        }

        /// <summary>
        /// Saves a collection of <see cref="IWarehouseCatalog"/>.
        /// </summary>
        /// <param name="warehouseCatalogs">
        /// The warehouse catalogs.
        /// </param>
        /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param>
        public void Save(IEnumerable<IWarehouseCatalog> warehouseCatalogs, bool raiseEvents = true)
        {
            var catalogsArray = warehouseCatalogs as IWarehouseCatalog[] ?? warehouseCatalogs.ToArray();
            if (raiseEvents)
            Saving.RaiseEvent(new SaveEventArgs<IWarehouseCatalog>(catalogsArray), this);

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(uow))
                {
                    foreach (var catalog in catalogsArray)
                    {
                        repository.AddOrUpdate(catalog);
                    }

                    uow.Commit();
                }
            }

            if (raiseEvents) Saved.RaiseEvent(new SaveEventArgs<IWarehouseCatalog>(catalogsArray), this);
        }

        /// <summary>
        /// Deletes a single instance of a <see cref="IWarehouseCatalog"/>.
        /// </summary>
        /// <param name="warehouseCatalog">
        /// The warehouse catalog.
        /// </param>
        /// <param name="raiseEvents">
        /// The raise events.
        /// </param>
        public void Delete(IWarehouseCatalog warehouseCatalog, bool raiseEvents = true)
        {
            if (warehouseCatalog.Key == Core.Constants.Warehouse.DefaultWarehouseCatalogKey) return;

            if (raiseEvents)
            if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IWarehouseCatalog>(warehouseCatalog), this))
            {
                ((WarehouseCatalog)warehouseCatalog).WasCancelled = true;
                return;
            }

            RemoveVariantsFromCatalogInventoryBeforeDeleting(warehouseCatalog);

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(uow))
                {
                    repository.Delete(warehouseCatalog);
                    uow.Commit();
                }
            }

            if (raiseEvents)
            Deleted.RaiseEvent(new DeleteEventArgs<IWarehouseCatalog>(warehouseCatalog), this);
        }

        /// <summary>
        /// Deletes a collection of <see cref="IWarehouseCatalog"/>
        /// </summary>
        /// <param name="warehouseCatalogs">
        /// The warehouse catalogs.
        /// </param>
        /// <param name="raiseEvents">
        /// The raise events.
        /// </param>
        public void Delete(IEnumerable<IWarehouseCatalog> warehouseCatalogs, bool raiseEvents = true)
        {
            var catalogs = warehouseCatalogs.Where(x => x.Key != Core.Constants.Warehouse.DefaultWarehouseCatalogKey).ToArray();
            if (!catalogs.Any()) return;

            if (raiseEvents)
            Deleting.RaiseEvent(new DeleteEventArgs<IWarehouseCatalog>(catalogs), this);

            foreach (var catalog in catalogs)
            {
                RemoveVariantsFromCatalogInventoryBeforeDeleting(catalog);
            }

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(uow))
                {
                    foreach (var catalog in catalogs)
                    {
                        repository.Delete(catalog);
                    }

                    uow.Commit();
                }
            }

            if (raiseEvents)
            Deleted.RaiseEvent(new DeleteEventArgs<IWarehouseCatalog>(catalogs), this);
        }

        /// <summary>
        /// Gets a <see cref="IWarehouseCatalog"/> by its key.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="IWarehouseCatalog"/>.
        /// </returns>
        public IWarehouseCatalog GetByKey(Guid key)
        {
            using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(UowProvider.GetUnitOfWork()))
            {
                return repository.Get(key);
            }
        }

        /// <summary>
        /// Gets a collection of all <see cref="IWarehouseCatalog"/>.
        /// </summary>
        /// <returns>
        /// The collection of <see cref="IWarehouseCatalog"/>.
        /// </returns>
        public IEnumerable<IWarehouseCatalog> GetAll()
        {
            using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(UowProvider.GetUnitOfWork()))
            {
                return repository.GetAll();
            }
        }

        /// <summary>
        /// Gets a collection of <see cref="IWarehouseCatalog"/> for a given <see cref="IWarehouse"/>.
        /// </summary>
        /// <param name="warehouseKey">
        /// The warehouse key.
        /// </param>
        /// <returns>
        /// The collection of <see cref="IWarehouseCatalog"/>.
        /// </returns>
        public IEnumerable<IWarehouseCatalog> GetByWarehouseKey(Guid warehouseKey)
        {
            using (var repository = RepositoryFactory.CreateWarehouseCatalogRepository(UowProvider.GetUnitOfWork()))
            {
                return repository.GetWarehouseCatalogsByWarehouseKey(warehouseKey);
            }
        }

        /// <summary>
        /// Removes variants from catalog inventory.
        /// </summary>
        /// <param name="catalog">
        /// The catalog.
        /// </param>
        private void RemoveVariantsFromCatalogInventoryBeforeDeleting(IWarehouseCatalog catalog)
        {
            var variants =
                _productVariantService.GetByWarehouseKey(catalog.WarehouseKey)
                    .Where(pv => pv.CatalogInventories.Any(inv => inv.CatalogKey == catalog.Key)).ToArray();

            if (!variants.Any()) return;

            foreach (var variant in variants)
            {
                variant.RemoveFromCatalogInventory(catalog);
            }

            _productVariantService.Save(variants);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package singularity

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/opentable/go-singularity/dtos"
	"github.com/opentable/sous/ext/docker"
	"github.com/opentable/sous/lib"
	"github.com/opentable/sous/util/firsterr"
	"github.com/opentable/sous/util/logging"
	"github.com/opentable/sous/util/logging/messages"
	"github.com/pkg/errors"
)

type (
	deploymentBuilder struct {
		clusters  sous.Clusters
		Target    sous.DeployState
		imageName string
		depMarker sDepMarker
		history   sHistory
		deploy    sDeploy
		request   sRequest
		req       SingReq
		registry  sous.ImageLabeller
		reqID     string
		log       logging.LogSink
	}

	canRetryRequest struct {
		cause error
		req   SingReq
	}

	malformedResponse struct {
		message string
	}

	nonSousError struct {
	}

	notThisClusterError struct {
		foundClusterName        string
		responsibleClusterNames []string
	}
)

func (ntc notThisClusterError) Error() string {
	return fmt.Sprintf("%s does not belong to this Sous server %#v.",
		ntc.foundClusterName, ntc.responsibleClusterNames)
}

func (nsd nonSousError) Error() string {
	return "Not a Sous SingularityDeploy."
}

func ignorableDeploy(log logging.LogSink, err error) bool {
	switch errors.Cause(err).(type) {
	case nonSousError, notThisClusterError:
		return true
	}
	return false
}

func (mr malformedResponse) Error() string {
	return mr.message
}

func isMalformed(err error) bool {
	err = errors.Cause(err)
	_, isMal := err.(malformedResponse)
	_, isUMT := err.(*json.UnmarshalTypeError)
	_, isUST := err.(*json.UnsupportedTypeError)
	_, isUSV := err.(*json.UnsupportedValueError)
	return isMal || isUMT || isUST || isUSV
}

func (cr *canRetryRequest) Error() string {
	return fmt.Sprintf("%s: %s", cr.cause, cr.name())
}

func (cr *canRetryRequest) name() string {
	return fmt.Sprintf("%s:%s", cr.req.SourceURL, cr.req.ReqParent.Request.Id)
}

func (db *deploymentBuilder) canRetry(err error) error {
	if err == nil || !db.isRetryable(err) {
		return err
	}
	return &canRetryRequest{err, db.req}
}

func (db *deploymentBuilder) isRetryable(err error) bool {
	return !isMalformed(err) &&
		!ignorableDeploy(db.log, err) &&
		db.req.SourceURL != "" &&

		db.req.ReqParent != nil &&
		db.req.ReqParent.Request != nil &&
		db.req.ReqParent.Request.Id != ""
}

// BuildDeployment does all the work to collect the data for a Deployment
// from Singularity based on the initial SingularityRequest.
func BuildDeployment(reg sous.ImageLabeller, clusters sous.Clusters, req SingReq, log logging.LogSink) (sous.DeployState, error) {
	messages.ReportLogFieldsMessage("Build Deployment", logging.ExtraDebug1Level, log, req.ReqParent)
	db := deploymentBuilder{registry: reg, clusters: clusters, req: req, log: log}
	return db.Target, db.canRetry(db.completeConstruction())
}

func (db *deploymentBuilder) completeConstruction() error {
	wrapError := func(fn func() error, msgStr string) func() error {
		return func() error {
			return errors.Wrap(fn(), msgStr)
		}
	}
	return firsterr.Returned(
		wrapError(db.basics, "Failed to extract basic information from original request."),
		wrapError(db.getFullRequestParent, "Failed to retrieve full RequestParent DTO."),
		wrapError(db.determineDeployStatus, "Failed to determine deploy status."),
		wrapError(db.retrieveDeployHistory, "Failed to retrieve SingularityDeployHistory from SingularityRequestParent."),
		wrapError(db.extractDeployFromDeployHistory, "Failed to extract SingularityDeploy from SingularityDeployHistory."),
		wrapError(db.sousDeployCheck, "Could not determine if the SingularityDeploy is controlled by Sous"),
		wrapError(db.determineStatus, "Could not determine current status of SingularityDeploy"),
		wrapError(db.extractArtifactName, "Could not extract ArtifactName (Docker image name) from SingularityDeploy."),
		wrapError(db.retrieveImageLabels, "Could not retrieve ImageLabels (Docker image labels) from sous.Registry."),
		wrapError(db.restoreFromMetadata, "Could not determine cluster name based on SingularityDeploy Metadata."),
		wrapError(db.unpackDeployConfig, "Could not convert data from a SingularityDeploy to a sous.Deployment."),
		wrapError(db.determineManifestKind, "Could not determine SingularityRequestType."),
		wrapError(db.extractSchedule, "Could not determine Singularity schedule."),
	)
}

func reqID(rp *dtos.SingularityRequestParent) (id string) {
	// defer func() { recover() }() because we explicitly do not care if this
	// panics. It is only used in certain low-level logs, and we don't mind
	// if we get some garbage data there. There is a fear that some race
	// condition between asserting that rp and rp.Request are not nil and
	// accessing their members may cause panics here. Please do not remove
	// this line before asserting somehow that this race condition does not
	// exist.
	defer func() { recover() }()
	id = "singularity.reqID() panicked"
	if rp == nil {
		return "<null RequestParent>"
	}
	if rp.Request == nil {
		return "<null Request>"
	}
	return rp.Request.Id
}

func (db *deploymentBuilder) basics() error {
	db.Target.Cluster = &sous.Cluster{BaseURL: db.req.SourceURL}
	db.Target.ExecutorData = &singularityTaskData{requestID: reqID(db.req.ReqParent)}
	messages.ReportLogFieldsMessage("Recording as requestID for instance.", logging.ExtraDebug1Level, db.log, db.Target.ExecutorData)
	db.request = db.req.ReqParent.Request
	db.reqID = reqID(db.req.ReqParent)
	db.Target.SingularityRequestID = db.reqID
	return nil
}

func (db *deploymentBuilder) getFullRequestParent() error {
	if db.req.ReqParent.ActiveDeploy != nil || db.req.ReqParent.PendingDeploy != nil {
		// already have useful info
		return nil
	}

	rp, err := db.req.Sing.GetRequest(db.reqID, false)
	if err != nil {
		return err
	}
	db.req.ReqParent = rp
	return nil
}

// If there is a Pending deploy, as far as Sous is concerned, that's "to
// come" - we optimistically assume it will become Active, and that's the
// Deployment we should consider live.
func (db *deploymentBuilder) determineDeployStatus() error {
	rp := db.req.ReqParent
	if rp == nil {
		return malformedResponse{fmt.Sprintf("Singularity response didn't include a request parent. %v", db.req)}
	}

	rds := rp.RequestDeployState

	if rds == nil {
		return malformedResponse{"Singularity response didn't include a deploy state. ReqId: " + reqID(rp)}
	}

	switch {
	default:
		db.Target.Status = sous.DeployStatusAny
	case rp.State != dtos.SingularityRequestParentRequestStateACTIVE &&
		rp.State != dtos.SingularityRequestParentRequestStateDEPLOYING_TO_UNPAUSE:
		db.Target.Status = sous.DeployStatusAny
	case rds.PendingDeploy != nil:
		db.Target.Status = sous.DeployStatusPending
		db.depMarker = rds.PendingDeploy
		db.deploy = rp.PendingDeploy
		/*
			XXX(jdl) This doesn't work, because as of 0.19, S9y Request responses
			don't include enough information to distinguish successfully deployed
			requests from fallbacks. There are promising fields in 0.20, so we
			should revisit.

			case rds.ActiveDeploy != nil:
				db.Target.Status = sous.DeployStatusActive
				db.depMarker = rds.ActiveDeploy
				db.deploy = rp.ActiveDeploy
		*/
	}
	return nil
}

func (db *deploymentBuilder) retrieveDeployHistory() error {
	if db.depMarker == nil {
		return db.retrieveHistoricDeploy()
	}
	messages.ReportLogFieldsMessage("Getting deploy based on Pending marker.", logging.ExtraDebug1Level, db.log, db.reqID)
	return db.retrieveLiveDeploy()
}

func (db *deploymentBuilder) retrieveHistoricDeploy() error {
	messages.ReportLogFieldsMessage("Getting deploy from history", logging.ExtraDebug1Level, db.log, db.reqID)
	// !!! makes HTTP req
	if db.request == nil {
		return malformedResponse{"Singularity request parent had no request."}
	}
	sing := db.req.Sing
	depHistList, err := sing.GetDeploys(db.request.Id, 1, 1)
	messages.ReportLogFieldsMessage("Got history from Singularity with items.", logging.ExtraDebug1Level, db.log, db.reqID, len(depHistList))
	if err != nil {
		return errors.Wrap(err, "GetDeploys")
	}

	if len(depHistList) == 0 {
		return malformedResponse{"Singularity deploy history list was empty."}
	}

	partialHistory := depHistList[0]

	messages.ReportLogFieldsMessage("Partial history.", logging.ExtraDebug1Level, db.log, db.reqID, partialHistory)
	if partialHistory.DeployMarker == nil {
		return malformedResponse{"Singularity deploy history had no deploy marker."}
	}

	messages.ReportLogFieldsMessage("Partial history DeployMarker.", logging.ExtraDebug1Level, db.log, db.reqID, partialHistory.DeployMarker)
	db.depMarker = partialHistory.DeployMarker
	return db.retrieveLiveDeploy()
}

func (db *deploymentBuilder) retrieveLiveDeploy() error {
	if db.deploy != nil {
		// handled already
		return nil
	}
	// !!! makes HTTP req
	sing := db.req.Sing
	dh, err := sing.GetDeploy(db.depMarker.RequestId, db.depMarker.DeployId)
	if err != nil {
		messages.ReportLogFieldsMessage("Received error retrieving history entry for deploy marker.", logging.ExtraDebug1Level, db.log, db.reqID, db.depMarker, err)
		return errors.Wrapf(err, "%q %#v", db.reqID, db.depMarker)
	}

	messages.ReportLogFieldsMessage("Deploy history entry retrieved.", logging.ExtraDebug1Level, db.log, db.reqID, dh)
	db.history = dh

	return nil
}

func (db *deploymentBuilder) extractDeployFromDeployHistory() error {
	if db.deploy != nil {
		// have a deploy already from the request
		return nil
	}
	db.deploy = db.history.Deploy
	if db.deploy == nil {
		return malformedResponse{"Singularity deploy history included no deploy"}
	}

	return nil
}

func (db *deploymentBuilder) sousDeployCheck() error {
	if cnl, ok := db.deploy.Metadata[sous.ClusterNameLabel]; ok {
		for _, cn := range db.clusters.Names() {
			if cnl == cn {
				messages.ReportLogFieldsMessage("Deploy cluster found in clusters.", logging.ExtraDebug1Level, db.log, cnl, db.clusters)
				return nil
			}
		}
		return notThisClusterError{cnl, db.clusters.Names()}
	}
	return nonSousError{}
}

func (db *deploymentBuilder) determineStatus() error {
	if db.Target.Status != sous.DeployStatusAny {
		// handled already
		return nil
	}
	if db.history.DeployResult == nil {
		db.Target.Status = sous.DeployStatusPending
		return nil
	}
	if db.history.DeployResult.DeployState == dtos.SingularityDeployResultDeployStateSUCCEEDED {
		db.Target.Status = sous.DeployStatusActive
	} else {
		msg := db.history.DeployResult.Message
		if len(db.history.DeployResult.DeployFailures) > 0 {
			msgs := []string{}
			for _, df := range db.history.DeployResult.DeployFailures {
				msgs = append(msgs, df.Message)
			}
			msg = strings.Join(msgs, ", ")
		}

		db.Target.ExecutorMessage = fmt.Sprintf("Deploy failure: %q %s/request/%s/deploy/%s",
			msg,
			db.req.SourceURL,
			db.history.Deploy.RequestId,
			db.history.Deploy.Id,
		)
		db.Target.Status = sous.DeployStatusFailed
	}

	return nil
}

func (db *deploymentBuilder) extractArtifactName() error {
	ci := db.deploy.ContainerInfo
	if ci == nil {
		return malformedResponse{"Blank container info"}
	}

	if ci.Type != dtos.SingularityContainerInfoSingularityContainerTypeDOCKER {
		return malformedResponse{"Singularity container isn't a docker container"}
	}
	dkr := ci.Docker
	if dkr == nil {
		return malformedResponse{"Singularity deploy didn't include a docker info"}
	}

	db.imageName = dkr.Image
	return nil
}

func (db *deploymentBuilder) retrieveImageLabels() error {
	// XXX coupled to Docker registry as ImageMapper
	// !!! HTTP request
	// XXX for unlabelled images, we need to handle this somehow...
	labels, err := db.registry.ImageLabels(db.imageName)
	if err != nil {
		return malformedResponse{err.Error()}
	}

	messages.ReportLogFieldsMessage("Labels", logging.ExtraDebug1Level, db.log, db.reqID, labels)
	db.Target.SourceID, err = docker.SourceIDFromLabels(labels)
	if err != nil {
		return errors.Wrapf(malformedResponse{err.Error()}, "For reqID: %s", reqID(db.req.ReqParent))
	}

	return nil
}

func getMetadataField(field string, md map[string]string) (val string, err error) {
	var ok bool
	val, ok = md[field]
	if !ok {
		err = malformedResponse{fmt.Sprintf("Deploy Metadata did not include a %s", field)}
	}
	return
}

func (db *deploymentBuilder) restoreFromMetadata() error {
	var err error
	db.Target.ClusterName, err = getMetadataField(sous.ClusterNameLabel, db.deploy.Metadata)
	if err != nil {
		return err
	}

	// An absent flavor from the metadata is unseemly, but probably means that
	// the deploy predates flavor metadata handling
	// perhaps it's worth logging about this, or erroring on this and clobbering
	// old requests.
	//  - if you're debugging a deploy issue related to flavor, let's enforce
	//  this more strictly, and we'll deal with the fallout then -jdl
	db.Target.Flavor, _ = getMetadataField(sous.FlavorLabel, db.deploy.Metadata)
	return nil
}

func (db *deploymentBuilder) unpackDeployConfig() error {
	db.Target.Env = db.deploy.Env
	messages.ReportLogFieldsMessage("UnpackDeployConfig", logging.ExtraDebug1Level, db.log, db.reqID, db.deploy.Env)
	if db.Target.Env == nil {
		db.Target.Env = make(map[string]string)
	}

	singRez := db.deploy.Resources
	if singRez == nil {
		return malformedResponse{"Deploy object lacks resources field"}
	}
	db.Target.Resources = make(sous.Resources)
	db.Target.Resources["cpus"] = fmt.Sprintf("%f", singRez.Cpus)
	db.Target.Resources["memory"] = fmt.Sprintf("%f", singRez.MemoryMb)
	db.Target.Resources["ports"] = fmt.Sprintf("%d", singRez.NumPorts)

	db.Target.NumInstances = int(db.request.Instances)
	db.Target.Owners = make(sous.OwnerSet)
	for _, o := range db.request.Owners {
		db.Target.Owners.Add(o)
	}

	for _, v := range db.deploy.ContainerInfo.Volumes {
		db.Target.DeployConfig.Volumes = append(db.Target.DeployConfig.Volumes,
			&sous.Volume{
				Host:      v.HostPath,
				Container: v.ContainerPath,
				Mode:      sous.VolumeMode(v.Mode),
			})
	}
	messages.ReportLogFieldsMessage("Volumes", logging.ExtraDebug1Level, db.log, db.reqID, db.Target.DeployConfig.Volumes)
	if len(db.Target.DeployConfig.Volumes) > 0 {
		messages.ReportLogFieldsMessage("UnpackDeployConfig volume 0", logging.DebugLevel, db.log, db.reqID, db.Target.DeployConfig.Volumes[0])
	}

	if db.deploy.Healthcheck != nil {
		db.Target.Startup.ConnectDelay = int(db.deploy.Healthcheck.StartupDelaySeconds)
		db.Target.Startup.Timeout = int(db.deploy.Healthcheck.StartupTimeoutSeconds)
		db.Target.Startup.ConnectInterval = int(db.deploy.Healthcheck.StartupIntervalSeconds)
		db.Target.Startup.CheckReadyProtocol = string(db.deploy.Healthcheck.Protocol)
		db.Target.Startup.CheckReadyURIPath = string(db.deploy.Healthcheck.Uri)
		db.Target.Startup.CheckReadyPortIndex = int(db.deploy.Healthcheck.PortIndex)
		db.Target.Startup.CheckReadyURITimeout = int(db.deploy.Healthcheck.ResponseTimeoutSeconds)
		db.Target.Startup.CheckReadyInterval = int(db.deploy.Healthcheck.IntervalSeconds)
		db.Target.Startup.CheckReadyRetries = int(db.deploy.Healthcheck.MaxRetries)

		db.Target.Startup.CheckReadyFailureStatuses = make([]int, len(db.deploy.Healthcheck.FailureStatusCodes))
		for n, code := range db.deploy.Healthcheck.FailureStatusCodes {
			db.Target.Startup.CheckReadyFailureStatuses[n] = int(code)
		}
	} else {
		db.Target.Startup.SkipCheck = true
	}

	return nil
}

func (db *deploymentBuilder) determineManifestKind() error {
	kind, ok := MapRequestTypeToManifestKind(string(db.request.RequestType))
	if !ok {
		return fmt.Errorf("Unrecognized request type returned by Singularity: %v", db.request.RequestType)
	}
	db.Target.Kind = kind
	return nil
}

// MapRequestTypeToManifestKind returns the ManifestKind and true if the mapping
// is possible; an indefined value and false otherwise.
func MapRequestTypeToManifestKind(requestType string) (sous.ManifestKind, bool) {
	var k sous.ManifestKind
	switch dtos.SingularityRequestRequestType(requestType) {
	default:
		return k, false
	case dtos.SingularityRequestRequestTypeSERVICE:
		return sous.ManifestKindService, true
	case dtos.SingularityRequestRequestTypeWORKER:
		return sous.ManifestKindWorker, true
	case dtos.SingularityRequestRequestTypeON_DEMAND:
		return sous.ManifestKindOnDemand, true
	case dtos.SingularityRequestRequestTypeSCHEDULED:
		return sous.ManifestKindScheduled, true
	case dtos.SingularityRequestRequestTypeRUN_ONCE:
		return sous.ManifestKindOnce, true
	}
}

func (db *deploymentBuilder) extractSchedule() error {
	if db.Target.Kind == sous.ManifestKindScheduled {
		if db.request == nil {
			return fmt.Errorf("request is nil")
		}
		db.Target.DeployConfig.Schedule = db.request.Schedule
	}
	return nil
}


text:
var LightSource = function(radius, instensity, distance, color){
	this.radius = Math.PI / 2;
	this.instensity = 1;
	this.distance = 200;
	this.color = 0xffffff;

	if(radius !== undefined)
	{
		this.radius = radius;
	}
	if(instensity !== undefined)
	{
		this.instensity = instensity;
	}
	if(distance !== undefined)
	{
		this.distance = distance;
	}
	if(color !== undefined)
	{
		this.color = color;
	}
};

LightSource.prototype.create = function(x, y, z, targetX, targetY, targetZ) {
	this.ambient = new THREE.AmbientLight(0x111111);
	this.light = new THREE.SpotLight( this.color, this.instensity, this.distance, this.radius, 100);

	this.light.position.set(x, y, z);
	this.light.target.position.set(targetX, targetY, targetZ);

	this.light.castShadow = true;

	this.light.shadowMapBias = 0.05;
	this.light.shadowDarkness = 0.8;

	this.light.shadowCameraNear = 1;
	this.light.shadowCameraFar = 5000;
	this.light.shadowCameraFov = 50;

	this.light.shadowMapWidth = 4096;
	this.light.shadowMapHeight = 4096;
};

LightSource.prototype.toggleDebug = function()
{
	this.light.shadowCameraVisible = !this.light.shadowCameraVisible;
}

LightSource.prototype.setTarget = function(x, y, z)
{
	this.light.target.position.set(x, y, z);
	this.light.updateMatrix();
	this.light.updateMatrixWorld();
};

LightSource.prototype.setPosition = function(x, y, z)
{
	this.light.position.set(x, y, z);
	this.light.updateMatrix();
	this.light.updateMatrixWorld();
};

LightSource.prototype.move = function(x, y, z)
{
	this.light.position.x += x;
	this.light.position.y += y;
	this.light.position.z += z;
	this.light.updateMatrix();
	this.light.updateMatrixWorld();
};

LightSource.prototype.add = function()
{
	scene.add(this.light);
	scene.add(this.ambient);
};

LightSource.prototype.remove = function()
{
	scene.remove(this.light);
	scene.remove(this.ambient);
};

LightSource.prototype.light = function()
{
	return this.light;
};


text:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:dd="http://rice.kuali.org/dd" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://rice.kuali.org/dd http://rice.kuali.org/dd/dd.xsd">
<!--
 Copyright 2008-2009 The Kuali Foundation

 Licensed under the Educational Community License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.opensource.org/licenses/ecl2.php

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

  <bean id="AssetRetirementGlobal" parent="AssetRetirementGlobal-parentBean"/>

  <bean id="AssetRetirementGlobal-parentBean" abstract="true" parent="BusinessObjectEntry">
    <property name="businessObjectClass" value="org.kuali.kfs.module.cam.businessobject.AssetRetirementGlobal"/>
    <property name="inquiryDefinition">
      <ref bean="AssetRetirementGlobal-inquiryDefinition"/>
    </property>
    <property name="lookupDefinition">
      <ref bean="AssetRetirementGlobal-lookupDefinition"/>
    </property>
    <property name="objectLabel" value="Asset Retirement Global"/>
    <property name="attributes">
      <list>
        <ref bean="AssetRetirementGlobal-documentNumber"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAssetNumber"/>
        <ref bean="AssetRetirementGlobal-retirementDate"/>
        <ref bean="AssetRetirementGlobal-retirementReasonCode"/>

		<ref bean="AssetRetirementGlobal-mergedTargetCapitalAssetDescription"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAsset.organizationOwnerAccount.organizationCode"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetDescription"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetTypeCode"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAsset.createDate"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetInServiceDate"/>
        <ref bean="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetType.depreciableLifeLimit"/>

        <ref bean="AssetRetirementGlobal-retirementChartOfAccountsCode"/>
        <ref bean="AssetRetirementGlobal-retirementAccountNumber"/>
        <ref bean="AssetRetirementGlobal-retirementContactName"/>
        <ref bean="AssetRetirementGlobal-retirementInstitutionName"/>
        <ref bean="AssetRetirementGlobal-retirementStreetAddress"/>
        <ref bean="AssetRetirementGlobal-retirementCityName"/>
        <ref bean="AssetRetirementGlobal-retirementStateCode"/>
        <ref bean="AssetRetirementGlobal-retirementZipCode"/>
        <ref bean="AssetRetirementGlobal-retirementCountryCode"/>
        <ref bean="AssetRetirementGlobal-retirementPhoneNumber"/>
        <ref bean="AssetRetirementGlobal-estimatedSellingPrice"/>
        <ref bean="AssetRetirementGlobal-salePrice"/>
        <ref bean="AssetRetirementGlobal-cashReceiptFinancialDocumentNumber"/>
        <ref bean="AssetRetirementGlobal-handlingFeeAmount"/>
        <ref bean="AssetRetirementGlobal-preventiveMaintenanceAmount"/>
        <ref bean="AssetRetirementGlobal-calculatedTotal"/>
        <ref bean="AssetRetirementGlobal-buyerDescription"/>
        <ref bean="AssetRetirementGlobal-paidCaseNumber"/>
        <ref bean="AssetRetirementGlobal-accountingPeriodCompositeString" />
      </list>
    </property>

    <property name="relationships">
      <list>
        <dd:relationship objectAttribute="postalZipCode">
            <dd:primitiveAttribute source="retirementZipCode" target="code"/>
            <dd:primitiveAttribute source="retirementCountryCode" target="countryCode"/>
        </dd:relationship>
        <dd:relationship objectAttribute="retirementState">
            <dd:primitiveAttribute source="retirementCountryCode" target="countryCode"/>
            <dd:primitiveAttribute source="retirementStateCode" target="code"/>
        </dd:relationship>
        <dd:relationship objectAttribute="retirementCountry">
            <dd:primitiveAttribute source="retirementCountryCode" target="code"/>
        </dd:relationship>
      </list>
    </property>
  </bean>

<!-- Attribute Definitions -->
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAssetDescription" parent="AssetRetirementGlobal-mergedTargetCapitalAssetDescription-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAssetDescription-parentBean" abstract="true" parent="Asset-capitalAssetDescription">
    <property name="name" value="mergedTargetCapitalAssetDescription"/>
    <property name="label" value="Asset Description"/>
    <property name="attributeSecurity">
        <bean parent="AttributeSecurity">
           <property name="readOnly" value="false"/>
       </bean>
	</property>
  </bean>

  <bean id="AssetRetirementGlobal-documentNumber" parent="AssetRetirementGlobal-documentNumber-parentBean"/>
  <bean id="AssetRetirementGlobal-documentNumber-parentBean" abstract="true" parent="FinancialSystemDocumentHeader-documentNumber">
    <property name="label" value="Document Number"/>
    <property name="shortLabel" value="Number"/>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAssetNumber" parent="AssetRetirementGlobal-mergedTargetCapitalAssetNumber-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAssetNumber-parentBean" abstract="true" parent="Asset-capitalAssetNumber">
    <property name="name" value="mergedTargetCapitalAssetNumber"/>
    <property name="label" value="Merged Target Asset Number"/>
    <property name="shortLabel" value="Number"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementDate" parent="AssetRetirementGlobal-retirementDate-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementDate-parentBean" abstract="true" parent="GenericAttributes-genericDate">
    <property name="name" value="retirementDate"/>
    <property name="label" value="Retirement Date"/>
    <property name="shortLabel" value="Date"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementReasonCode" parent="AssetRetirementGlobal-retirementReasonCode-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementReasonCode-parentBean" abstract="true" parent="AssetRetirementReason-retirementReasonCode">
    <property name="control">
      <bean parent="SelectControlDefinition" p:businessObjectClass="org.kuali.kfs.module.cam.businessobject.AssetRetirementReason" p:valuesFinderClass=" org.kuali.rice.krad.keyvalues.PersistableBusinessObjectValuesFinder" p:includeKeyInLabel="true" p:includeBlankRow="true" p:keyAttribute="retirementReasonCode" p:labelAttribute="retirementReasonName"/>
    </property>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.organizationOwnerAccount.organizationCode" parent="AssetRetirementGlobal-mergedTargetCapitalAsset.organizationOwnerAccount.organizationCode-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.organizationOwnerAccount.organizationCode-parentBean" abstract="true" parent="Asset-organizationOwnerAccount.organizationCode">
    <property name="name" value="mergedTargetCapitalAsset.organizationOwnerAccount.organizationCode"/>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetDescription" parent="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetDescription-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetDescription-parentBean" abstract="true" parent="Asset-capitalAssetDescription">
    <property name="name" value="mergedTargetCapitalAsset.capitalAssetDescription"/>
    <property name="attributeSecurity">
        <bean parent="AttributeSecurity">
           <property name="readOnly" value="false"/>
       </bean>
	</property>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetTypeCode" parent="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetTypeCode-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetTypeCode-parentBean" abstract="true" parent="Asset-capitalAssetTypeCode">
    <property name="name" value="mergedTargetCapitalAsset.capitalAssetTypeCode"/>
    <property name="attributeSecurity">
        <bean parent="AttributeSecurity">
           <property name="readOnly" value="false"/>
       </bean>
	</property>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetType.depreciableLifeLimit" parent="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetType.depreciableLifeLimit-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetType.depreciableLifeLimit-parentBean" abstract="true" parent="AssetType-depreciableLifeLimit">
    <property name="name" value="mergedTargetCapitalAsset.capitalAssetType.depreciableLifeLimit"/>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.createDate" parent="AssetRetirementGlobal-mergedTargetCapitalAsset.createDate-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.createDate-parentBean" abstract="true" parent="Asset-createDate">
    <property name="name" value="mergedTargetCapitalAsset.createDate"/>
  </bean>

  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetInServiceDate" parent="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetInServiceDate-parentBean"/>
  <bean id="AssetRetirementGlobal-mergedTargetCapitalAsset.capitalAssetInServiceDate-parentBean" abstract="true" parent="Asset-capitalAssetInServiceDate">
    <property name="name" value="mergedTargetCapitalAsset.capitalAssetInServiceDate"/>
    <property name="attributeSecurity">
        <bean parent="AttributeSecurity">
           <property name="readOnly" value="false"/>
       </bean>
    </property>
  </bean>

  <bean id="AssetRetirementGlobal-retirementChartOfAccountsCode" parent="AssetRetirementGlobal-retirementChartOfAccountsCode-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementChartOfAccountsCode-parentBean" abstract="true" parent="Asset-retirementChartOfAccountsCode">
    <property name="label" value="Cash Receipt Chart of Accounts Code "/>
    <property name="shortLabel" value="Code"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementAccountNumber" parent="AssetRetirementGlobal-retirementAccountNumber-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementAccountNumber-parentBean" abstract="true" parent="Asset-retirementAccountNumber">
    <property name="label" value="Cash Receipt Account Number "/>
    <property name="shortLabel" value="Number"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementContactName" parent="AssetRetirementGlobal-retirementContactName-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementContactName-parentBean" abstract="true" parent="AssetLocation-assetLocationContactName">
    <property name="name" value="retirementContactName"/>
    <property name="label" value="Contact Name"/>
    <property name="shortLabel" value="Name"/>
    <property name="maxLength" value="123" />
  </bean>

  <bean id="AssetRetirementGlobal-retirementInstitutionName" parent="AssetRetirementGlobal-retirementInstitutionName-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementInstitutionName-parentBean" abstract="true" parent="AssetLocation-assetLocationInstitutionName">
    <property name="name" value="retirementInstitutionName"/>
    <property name="label" value="Institution Name"/>
    <property name="shortLabel" value="Name"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementStreetAddress" parent="AssetRetirementGlobal-retirementStreetAddress-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementStreetAddress-parentBean" abstract="true" parent="AssetLocation-assetLocationStreetAddress">
    <property name="name" value="retirementStreetAddress"/>
    <property name="label" value="Street Address"/>
    <property name="shortLabel" value="Address"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementCityName" parent="AssetRetirementGlobal-retirementCityName-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementCityName-parentBean" abstract="true" parent="AssetLocation-assetLocationCityName">
    <property name="name" value="retirementCityName"/>
    <property name="label" value="City Name"/>
    <property name="shortLabel" value="Name"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementStateCode" parent="AssetRetirementGlobal-retirementStateCode-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementStateCode-parentBean" abstract="true" parent="AssetLocation-assetLocationStateCode">
    <property name="name" value="retirementStateCode"/>
    <property name="label" value="State Code"/>
    <property name="shortLabel" value="Code"/>
    <property name="control">
      <bean parent="SelectControlDefinition" p:valuesFinderClass="org.kuali.rice.location.framework.state.StateValuesFinder"/>
    </property>
  </bean>

  <bean id="AssetRetirementGlobal-retirementZipCode" parent="AssetRetirementGlobal-retirementZipCode-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementZipCode-parentBean" abstract="true" parent="AssetLocation-assetLocationZipCode">
    <property name="name" value="retirementZipCode"/>
    <property name="label" value="Postal Code"/>
    <property name="shortLabel" value="Postal Code"/>
  </bean>

  <bean id="AssetRetirementGlobal-retirementCountryCode" parent="AssetRetirementGlobal-retirementCountryCode-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementCountryCode-parentBean" abstract="true" parent="AssetLocation-assetLocationCountryCode">
    <property name="name" value="retirementCountryCode"/>
    <property name="label" value="Country Code"/>
    <property name="control">
      <bean parent="SelectControlDefinition" p:valuesFinderClass="org.kuali.rice.location.framework.country.CountryValuesFinder"/>
    </property>
  </bean>

  <bean id="AssetRetirementGlobal-retirementPhoneNumber" parent="AssetRetirementGlobal-retirementPhoneNumber-parentBean"/>
  <bean id="AssetRetirementGlobal-retirementPhoneNumber-parentBean" abstract="true" parent="AssetLocation-assetLocationPhoneNumber">
    <property name="name" value="retirementPhoneNumber"/>
    <property name="label" value="Phone Number"/>
  </bean>

  <bean id="AssetRetirementGlobal-estimatedSellingPrice" parent="AssetRetirementGlobal-estimatedSellingPrice-parentBean"/>
  <bean id="AssetRetirementGlobal-estimatedSellingPrice-parentBean" abstract="true" parent="GenericAttributes-genericAmount">
    <property name="name" value="estimatedSellingPrice"/>
    <property name="label" value="Estimated Selling Price"/>
    <property name="shortLabel" value="Price"/>
    <property name="formatterClass" value="org.kuali.rice.core.web.format.CurrencyFormatter"/>
  </bean>

  <bean id="AssetRetirementGlobal-salePrice" parent="AssetRetirementGlobal-salePrice-parentBean"/>
  <bean id="AssetRetirementGlobal-salePrice-parentBean" abstract="true" parent="GenericAttributes-genericAmount">
    <property name="name" value="salePrice"/>
    <property name="label" value="Sale Price"/>
    <property name="shortLabel" value="Price"/>
    <property name="formatterClass" value="org.kuali.rice.core.web.format.CurrencyFormatter"/>
  </bean>

  <bean id="AssetRetirementGlobal-cashReceiptFinancialDocumentNumber" parent="AssetRetirementGlobal-cashReceiptFinancialDocumentNumber-parentBean"/>
  <bean id="AssetRetirementGlobal-cashReceiptFinancialDocumentNumber-parentBean" abstract="true" parent="FinancialSystemDocumentHeader-documentNumber">
    <property name="name" value="cashReceiptFinancialDocumentNumber"/>
    <property name="label" value="Cash Receipt Financial Document Number"/>
    <property name="shortLabel" value="Number"/>
  </bean>

  <bean id="AssetRetirementGlobal-handlingFeeAmount" parent="AssetRetirementGlobal-handlingFeeAmount-parentBean"/>
  <bean id="AssetRetirementGlobal-handlingFeeAmount-parentBean" abstract="true" parent="GenericAttributes-genericAmount">
    <property name="name" value="handlingFeeAmount"/>
    <property name="label" value="Handling Fee Amount"/>
    <property name="shortLabel" value="Amount"/>
    <property name="formatterClass" value="org.kuali.rice.core.web.format.CurrencyFormatter"/>
  </bean>

  <bean id="AssetRetirementGlobal-preventiveMaintenanceAmount" parent="AssetRetirementGlobal-preventiveMaintenanceAmount-parentBean"/>
  <bean id="AssetRetirementGlobal-preventiveMaintenanceAmount-parentBean" abstract="true" parent="GenericAttributes-genericAmount">
    <property name="name" value="preventiveMaintenanceAmount"/>
    <property name="label" value="Preventive Maintenance Amount"/>
    <property name="shortLabel" value="Amount"/>
    <property name="formatterClass" value="org.kuali.rice.core.web.format.CurrencyFormatter"/>
  </bean>

  <bean id="AssetRetirementGlobal-calculatedTotal" parent="AssetRetirementGlobal-calculatedTotal-parentBean"/>
  <bean id="AssetRetirementGlobal-calculatedTotal-parentBean" abstract="true" parent="GenericAttributes-genericAmount">
    <property name="name" value="calculatedTotal"/>
    <property name="label" value="Calculated Total"/>
    <property name="shortLabel" value="Amount"/>
    <property name="formatterClass" value="org.kuali.rice.core.web.format.CurrencyFormatter"/>
  </bean>

  <bean id="AssetRetirementGlobal-buyerDescription" parent="AssetRetirementGlobal-buyerDescription-parentBean"/>
  <bean id="AssetRetirementGlobal-buyerDescription-parentBean" abstract="true" parent="AttributeDefinition">
    <property name="name" value="buyerDescription"/>
    <property name="forceUppercase" value="false"/>
    <property name="label" value="Buyer Description"/>
    <property name="shortLabel" value="Description"/>
    <property name="maxLength" value="25"/>
    <property name="validationPattern">
      <ref bean="AnyCharacterWithWhitespaceValidation" />
    </property>
    <property name="control">
      <bean parent="TextControlDefinition" p:size="27"/>
    </property>
  </bean>

  <bean id="AssetRetirementGlobal-paidCaseNumber" parent="AssetRetirementGlobal-paidCaseNumber-parentBean"/>
  <bean id="AssetRetirementGlobal-paidCaseNumber-parentBean" abstract="true" parent="Asset-campusPoliceDepartmentCaseNumber">
    <property name="name" value="paidCaseNumber"/>
  </bean>

<!-- Business Object Inquiry Definition -->

  <bean id="AssetRetirementGlobal-inquiryDefinition" parent="AssetRetirementGlobal-inquiryDefinition-parentBean"/>
  <bean id="AssetRetirementGlobal-inquiryDefinition-parentBean" abstract="true" parent="InquiryDefinition">
    <property name="title" value="Asset Retirement Global Inquiry"/>
    <property name="inquirySections">
      <list>
        <bean parent="InquirySectionDefinition">
          <property name="title" value=""/>
          <property name="numberOfColumns" value="1"/>
          <property name="inquiryFields">
            <list>
              <bean parent="FieldDefinition" p:attributeName="documentNumber"/>
              <bean parent="FieldDefinition" p:attributeName="mergedTargetCapitalAssetNumber"/>
              <bean parent="FieldDefinition" p:attributeName="retirementDate"/>
              <bean parent="FieldDefinition" p:attributeName="retirementReasonCode"/>
              <bean parent="FieldDefinition" p:attributeName="retirementContactName"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementInstitutionName"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementStreetAddress"/>
              <bean parent="FieldDefinition" p:attributeName="retirementCityName"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementStateCode"/>
              <bean parent="FieldDefinition" p:attributeName="retirementZipCode"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementCountryCode"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementPhoneNumber"/>
			  <bean parent="FieldDefinition" p:attributeName="handlingFeeAmount"/>
              <bean parent="FieldDefinition" p:attributeName="preventiveMaintenanceAmount"/>
			  <bean parent="FieldDefinition" p:attributeName="buyerDescription"/>
			  <bean parent="FieldDefinition" p:attributeName="salePrice"/>
              <bean parent="FieldDefinition" p:attributeName="estimatedSellingPrice"/>
              <bean parent="FieldDefinition" p:attributeName="cashReceiptFinancialDocumentNumber"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementChartOfAccountsCode"/>
			  <bean parent="FieldDefinition" p:attributeName="retirementAccountNumber"/>
			  <bean parent="FieldDefinition" p:attributeName="paidCaseNumber"/>
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>

<!-- Business Object Lookup Definition -->

  <bean id="AssetRetirementGlobal-lookupDefinition" parent="AssetRetirementGlobal-lookupDefinition-parentBean"/>
  <bean id="AssetRetirementGlobal-lookupDefinition-parentBean" abstract="true" parent="LookupDefinition">
    <property name="title" value="Asset Retirement Global Lookup"/>

    <property name="defaultSort">
      <bean parent="SortDefinition">
      </bean>
    </property>
    <property name="lookupFields">
      <list>
        <bean parent="FieldDefinition" p:attributeName="documentNumber"/>
        <bean parent="FieldDefinition" p:attributeName="mergedTargetCapitalAssetNumber"/>
        <bean parent="FieldDefinition" p:attributeName="retirementDate"/>
        <bean parent="FieldDefinition" p:attributeName="retirementReasonCode"/>
      </list>
    </property>
    <property name="resultFields">
      <list>
        <bean parent="FieldDefinition" p:attributeName="documentNumber"/>
        <bean parent="FieldDefinition" p:attributeName="mergedTargetCapitalAssetNumber"/>
        <bean parent="FieldDefinition" p:attributeName="retirementDate"/>
        <bean parent="FieldDefinition" p:attributeName="retirementReasonCode"/>
      </list>
    </property>
  </bean>

  <bean id="AssetRetirementGlobal-accountingPeriodCompositeString" parent="AssetRetirementGlobal-accountingPeriodCompositeString-parentBean"/>
  <bean id="AssetRetirementGlobal-accountingPeriodCompositeString-parentBean" abstract="true" parent="AttributeDefinition">
    <property name="name" value="accountingPeriodCompositeString"/>
    <property name="forceUppercase" value="false"/>
    <property name="label" value="Accounting Period"/>
    <property name="shortLabel" value="Acct. Prd."/>
    <property name="maxLength" value="50"/>
    <property name="validationPattern">
      <ref bean="AnyCharacterValidation" />
    </property>
    <property name="required" value="false"/>
    <property name="control">
      <bean parent="SelectControlDefinition" p:valuesFinderClass="org.kuali.kfs.module.cam.businessobject.options.CamsYearEndAccountingPeriodValuesFinder" p:includeKeyInLabel="false"/>
    </property>
  </bean>

</beans>


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var User = new Schema ({
    first_name : String,
    last_name : String,
    email : String,
    password : String,
    confirm_password : String,
    admin : Number
});
module.exports = mongoose.model('User', User);


text:
<?php
namespace Phargs\Argument;

class Orchestrator {
  protected $parsed = false;
  protected $parser;
  protected $rawArgv = array();
  protected $argv = array();
  protected $params = array();
  protected $flags = array();

  public function __construct(Parser $parser, Array $argv){
    $this->parser  = $parser;
    $this->argv    = $argv;
    $this->rawArgv = $argv;
  }

  protected function ensureParsed(){
    if (!$this->parsed){
      $this->commandName = array_shift($this->argv);
      $this->parser->parse($this->argv);
      $this->parsed = true;
    }
    return true;
  }

  public function getCommandName(){
    $this->ensureParsed();
    return $this->commandName;
  }

  public function getArgCount(){
    $this->ensureParsed();
    return sizeOf($this->argv);
  }

  public function expectFlag($flag, $description = '', $required = false){
    $this->flags[$flag] = (object) array(
      'description' => $description,
      'required'    => (bool) $required,
      'aliases'     => array()
    );
    $this->parser->addFlag($flag);
    return true;
  }

  public function addFlagAlias($flag, $alias){
    if ($this->parser->addFlagAlias($flag, $alias)){
      $this->flags[$flag]->aliases[] = $alias;
      return true;
    }
    return false;
  }

  public function flagIsSet($flag){
    $this->ensureParsed();
    return $this->parser->flagIsSet($flag);
  }

  public function expectParam($param, $description = '', $required = false){
    $this->params[$param] = (object) array(
      'description' => $description,
      'required'    => (bool) $required,
      'aliases'     => array()
    );
    $this->parser->addParam($param);
    return true;
  }

  public function requireParam($param, $description = ''){
    return $this->expectParam($param, $description, true);
  }

  public function addParamAlias($param, $alias){
    if ($this->parser->addParamAlias($param, $alias)){
      $this->params[$param]->aliases[] = $alias;
      return true;
    }
    return false;
  }

  public function paramIsSet($param){
    $this->ensureParsed();
    return $this->parser->paramIsSet($param);
  }

  public function getParamValue($param){
    $this->ensureParsed();
    return $this->parser->getParamValue($param);
  }

  public function requirementsAreMet(){
    $this->ensureParsed();
    foreach ($this->flags as $flag => $props){
      if (!$props->required) continue;
      if (!$this->parser->flagIsSet($flag)){
        return false;
      }
    }

    foreach ($this->params as $param => $props){
      if (!$props->required) continue;
      if (!$this->parser->paramIsSet($param)){
        return false;
      }
    }
    return true;
  }

  public function getRawArgv(){
    return $this->rawArgv;
  }

  public function getExpectedFlags(){
    return $this->flags;
  }

  public function getExpectedParams(){
    return $this->params;
  }

  public function getResidualArgs($offset = 0, $count = null){
    $this->ensureParsed();
    return $this->parser->getResidualArgs($offset, $count);
  }

  public function getResidualArg($index){
    $this->ensureParsed();
    return $this->parser->getResidualArg($index);
  }

}


text:
/*AGENT_SHEET*/@namespace url(http://www.w3.org/1999/xhtml);
@namespace url(http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul);

/** Fixes the panel height **/
#PanelUI-popup .panelUI-grid.customization-target {
    max-height: unset !important;
}

/** Shrinks the icon Size **
#PanelUI-contents toolbarbutton .toolbarbutton-icon,
#customization-panel-container toolbarpaletteitem .toolbarbutton-icon {
    transform: scale(1.0) !important;
}

/** Hides the sync button **
#PanelUI-fxa-status {
    display: none !important;
} **/

/** Shrinks the button box and font size **/
#customization-panel-container .panel-arrowcontent :-moz-any(.toolbarbutton-1.chromeclass-toolbar-additional,.toolbarbutton-1),
#PanelUI-popup :-moz-any(.toolbarbutton-1.chromeclass-toolbar-additional,.toolbarbutton-1),
#PanelUI-popup toolbaritem[cui-areatype="menu-panel"][sdkstylewidget="true"]:not(.panel-wide-item) {
    font-size: 90% !important;
    margin: 0.25em !important;
    padding: 0em !important;
}
/** Corrects font size from previous setting **/
#customization-panel-container toolbarpaletteitem toolbarbutton:not(.panel-combined-button) :-moz-any(.toolbarbutton-text,.toolbarbutton-multiline-text),
#PanelUI-contents toolbarbutton:not(.panel-combined-button) :-moz-any(.toolbarbutton-text,.toolbarbutton-multiline-text) {
    margin:  0em -.2em -.5em -.2em !important;
    font-size: 110% !important;
}


text:
namespace Google.Cloud.BinaryAuthorization.V1.Snippets
{
    // [START binaryauthorization_v1_generated_BinauthzManagementServiceV1_CreateAttestor_async_flattened_resourceNames]
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.BinaryAuthorization.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedBinauthzManagementServiceV1ClientSnippets
    {
        /// <summary>Snippet for CreateAttestorAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateAttestorResourceNamesAsync()
        {
            // Create client
            BinauthzManagementServiceV1Client binauthzManagementServiceV1Client = await BinauthzManagementServiceV1Client.CreateAsync();
            // Initialize request argument(s)
            ProjectName parent = ProjectName.FromProject("[PROJECT]");
            string attestorId = "";
            Attestor attestor = new Attestor();
            // Make the request
            Attestor response = await binauthzManagementServiceV1Client.CreateAttestorAsync(parent, attestorId, attestor);
        }
    }
    // [END binaryauthorization_v1_generated_BinauthzManagementServiceV1_CreateAttestor_async_flattened_resourceNames]
}


text:
define([
    'jquery',
    'underscore',
    'backbone',
    './CollectionRecordsItemView',
    'text!templates/CollectionRecordsView.html'
], function($, _, Backbone, CollectionRecordsItemView, CollectionRecordsTemplate) {

    var CollectionRecordsListView = Backbone.View.extend({

        initialize: function(params) {
            this.dataset = params.dataset;
            this.collectionName = params.collectionName;
            this.container = $("#content");
            this.render();
        },

        events: {
            'click .prevPage': 'prevPage',
            'click .nextPage': 'nextPage'
        },

        template: _.template(CollectionRecordsTemplate),

        prevPage: function() {
            if (this.page > 1) {
                this.page--;
                this.setCollection();
            }
        },

        nextPage: function() {
            this.page++;
            this.setCollection();
        },

        page: 1, //current page

        pageSize: 50, //items to show for each page

        render: function() {
            var self = this;
            $(this.el).html(self.template({
                collectionName: self.collectionName
            }));

            this.setCollection();
            this.container.html(self.el);

            return this;
        },
        setPage: function() {
            this.$el.find('.page').html('Page ' + this.page);
        },
        setCollection: function() {
            var self = this;
            this.setPage();
            var Coll = Backbone.Collection.extend({
                url: '/record?dataset=' + this.dataset + '&datatype=' + this.collectionName + '&pagesize=' + this.pageSize + '&page=' + this.page
            });
            var coll = new Coll();
            coll.fetch({
                success: function() {
                    var len = coll.models.length;
                    self.showHideNexPrePage(len);
                    $('.thumbnails').html('');
                    for (var i = 0; i < len; i++) {
                        coll.models[i].set('collectionName', self.collectionName);
                        $('.thumbnails', self.el).append(new CollectionRecordsItemView({
                            dataset: self.dataset,
                            model: coll.models[i]
                        }).render().el);
                    }
                }
            });
        },
        showHideNexPrePage: function(len) {
            var self = this;
            if (len < self.pageSize) {
                self.$el.find('.nextPage').hide();
            } else {
                self.$el.find('.nextPage').show();
            }

            if(self.page == 1) {
                self.$el.find('.prevPage').hide();
            } else {
                self.$el.find('.prevPage').show();
            }

        }
    });

    return CollectionRecordsListView;

});


text:
<?php

namespace AppBundle\Service;

use Doctrine\ORM\EntityManager;

class SportService {

    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function deleteSport($sportId){

        $this->deleteEventsWithSport($sportId);

        $sport = $this->em->getRepository('AppBundle:Sport')->find($sportId);
        $this->em->remove($sport);
        $this->em->flush();

        return $this;
    }

    private function deleteEventsWithSport($sportId){

        $events = $this->em->getRepository('AppBundle:Event')->findBySport($sportId);

        foreach($events as $e){
            $this->em->remove($e);
        }

        $this->em->flush();

        return $this;
    }
}


text:
[![baboon](logo.png)](http://baboon.litixsoft.de/products-baboon)

# baboon
> Baboon Web Toolkit, modular fullstack web application framework for single-page realtime apps.

> [![NPM version](https://badge.fury.io/js/baboon.svg)](http://badge.fury.io/js/baboon)
[![Build Status](https://secure.travis-ci.org/litixsoft/baboon.svg?branch=master)](https://travis-ci.org/litixsoft/baboon)
[![david-dm](https://david-dm.org/litixsoft/baboon.svg?theme=shields.io)](https://david-dm.org/litixsoft/baboon/)
[![david-dm](https://david-dm.org/litixsoft/baboon/dev-status.svg?theme=shields.io)](https://david-dm.org/litixsoft/baboon#info=devDependencies&view=table)

Baboon is an open source web toolkit for creating Single Page Real-time applications.
It combines tools, libraries, own developments as well as existing frameworks into a complete,
ready for immediate use toolkit. It covers all activities necessary for the development process for the creation
of a single page real-time applications.

Baboon takes care of the complete setup of an immediately usable architecture for SPAs and also provides
the basic functionality of the application. In addition to simple things like LESS-based design,
it also includes the complete implementation of a websocket transport for the real-time communication inside the application. Last but not least the availability of many modules makes Baboon a full SPA-framework. All that is left to you is taking care of your business logic - the rest is done by Baboon.

* Web site: http://baboon.litixsoft.de/products-baboon
* Baboon project generator https://github.com/litixsoft/generator-baboon

# Install
The installation of a Baboon project is very simple. However, some preparatory work is needed.

## System requirements

Baboon need only NodeJS on the respective system.
In production mode on server with activated rights system following stack is desirable:

* MongoDb 2.4.5 or newer
* NodeJs 10.22 or newer

Such a stack including NodeJS version management, RedisIO, MongoDb and other tools can be found here: the [baboon-stack](https://github.com/litixsoft/baboon-stack) covers an easy-to-use one-click setup for Windows, Linux and Mac.
The baboon-stack is suitable with the NodeJS version management also ideal for development.

## NodeJS global dependencies
Without using baboon-stack, you need install Baboon's global dependencies. Skip this section when using Baboon-stack.

Linux / Mac:

    $ sudo npm install -g karma bower grunt-cli yo generator-baboon

Windows:

    $ npm install -g karma bower grunt-cli yo generator-baboon

## Create and start your baboon project
You can simply create a Baboon project with a yeoman generator-baboon and start with grunt serve.
The application starts in development mode with live reload functionality that monitors the directories for any changes.
If changes are detected, a new build is created, the server is restarted if necessary, and the browser is updated.

    $ mkdir my-new-project && cd $_
    $ yo baboon [app-name]
    $ grunt serve

Look out for more information in the sample application or check out the documentations on our web site.

# Contributing
Instead of us handing out a formal style guide, simply stick to the existing programming style. Please create descriptive commit messages.
We use a git hook to validate the commit messages against these [rules](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#heading=h.uyo6cb12dt6w).
Easily expand Baboon with your own extensions or changes in the functionality of Baboon itself. Use this workflow:

1. Write your functionality
2. Write unit tests for your functionality
3. Create an example of your functionality in the sample application (optional)
4. Document your functionality in the documentation section of example app
5. Write unit tests for the example
6. Add end to end tests for the example
7. All tests should be successful
8. Check your test coverage (90 - 100%)
9. Make a pull request

We will check the tests, the example and test coverage. In case your changes are useful and well tested, we will merge your requests.

# Building and Testing Baboon
This section describes how to set up your development environment to build and test Baboon with the example app.

## System requirements

Baboon need only NodeJS on the respective system.
In production mode on server with activated rights system following stack is desirable:

* MongoDb 2.4.5 or newer
* NodeJs 10.22 or newer

Such a stack including NodeJS version management, RedisIO, MongoDb and other tools can be found here: the [baboon-stack](https://github.com/litixsoft/baboon-stack) covers an easy-to-use one-click setup for Windows, Linux and Mac.
The baboon-stack is suitable with the NodeJS version management also ideal for development.

## NodeJS global dependencies
Without using baboon-stack, you need install Baboon's global dependencies. Skip this section when using Baboon-stack.

Linux / Mac:

    $ sudo npm install -g karma bower grunt-cli yo generator-baboon

Windows:

    $ npm install -g karma bower grunt-cli yo generator-baboon

## Install Baboon and example app
The example application is also the reference implementation of Baboon.
Fork Baboon repository and install the dependent modules with npm and bower.

    $ git clone https://github.com/litixsoft/baboon.git
    $ cd baboon
    $ npm install
    $ cd example
    $ npm install
    $ bower install

## Important:
Make sure to always keep the directory you are in in mind. Grunt commands in the baboon/ directory always refer to the
Baboon library. Grunt commands in the baboon/example always refer to the example application.

## Running example
To debug code and run end-to-end tests, it is useful to have a local implementation. For this purpose,
we built an example application with a fully functional web-server on ExpressJs basis.

    $ cd baboon/example
    $ grunt serve

The `grunt serve` command builds the example application in development mode, starts the server and opens the application in a browser.
It then monitors changes inside the directories. When a change to files is detected, grunt rebuilds the app and
reloads the site in the browser.

You can also manually start the `server.js` in development mode. This is sometimes needed for debugging.
You have to trigger the build by yourself then. After each change do a:

    $ grunt build:dev
    $ node server.js --config development

You can also manually start the `server.js` in production mode. This is sometimes needed for debugging.
You have to trigger the build by yourself then. After each change do a:

    $ grunt build
    $ node server.js

## Running tests
You can run all unit tests from Baboon lib and example application with:

    $ npm test // directory baboon

Baboon lib tests only

    $ grunt test // directory baboon

Example app server and client unit tests only

    $ grunt test // directory baboon/example

Example app server unit tests only

    $ grunt test:server // directory baboon/example

Example app client unit tests only

    $ grunt test:client // directory baboon/example

## Running end to end tests
You can run end to end scenario tests in example app with:

Test in development mode:

    $ grunt e2e // directory baboon/example

Test in production mode:

    $ grunt e2e:dist // directory baboon/example

## Running coverage
You can run a coverage task for Baboon lib with:

    $ grunt cover // directory baboon

You can run a coverage task for example app server and client with:

    $ grunt cover // directory baboon/example

You can run a coverage task for example app server with:

    $ grunt cover:server // directory baboon/example

You can run a coverage task for example app client with:

    $ grunt cover:client // directory baboon/example

## All Baboon lib grunt tasks
Important: this tasks run inside the baboon directory only.

Run baboon unit tests and jshint

    $ grunt test

Run baboon unit tests, jshint and code coverage

    $ grunt cover

Run baboon unit tests, jshint and code coverage for ci systems

    $ grunt ci

This generates xml reports inside the build folder.

## All Baboon example app grunt tasks
Important: this tasks run inside the baboon/example directory only.

Build application in development mode, start express server, open browser with app and watch for changes.

    $ grunt serve

Build application in development mode, start express server, open browser with app.

    $ grunt serve:dist

Build application in development mode only.

    $ grunt build:dev

Build application in production mode only.

    $ grunt build

Create the api documentation

    $ grunt doc

Create the api documentation and start the docu-application in browser

    $ grunt doc:serve

Run all unit tests

    $ grunt test

Run client unit tests

    $ grunt test:client

Run server unit tests

    $ grunt test:server

Run e2e protractor tests in development mode

    $ grunt e2e

Run e2e protractor tests in production mode

    $ grunt e2e:dist

Run coverage for server and client

    $ grunt cover

Run coverage for client

    $ grunt cover:client

Run coverage for server

    $ grunt cover:server

Run unit tests, jshint and code coverage for ci systems

    $ grunt ci

This generates xml reports inside the build folder.

## Release a new version
We use [grunt-bump](https://github.com/vojtajina/grunt-bump) and [grunt-conventional-changelog](https://github.com/btford/grunt-conventional-changelog) internally to manage our releases.
To handle the workflow, we created a grunt task `release`. This happens:

* Bump version in package.json
* Update the CHANGELOG.md file
* Commit in git with message "Release v[`the new version number`]"
* Create a git tag v[`the new version number`]

### Create a new release
Release a new patch

    $ grunt release

Release a new minor version

    $ grunt release:minor

Release a new major version

    $ grunt release:major

# Author
[Litixsoft GmbH](http://www.litixsoft.de)

# License
Copyright (C) 2013-2017 Litixsoft GmbH <info@litixsoft.de>
Licensed under the MIT license.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. DEALINGS IN THE SOFTWARE.


text:
layout: post
title:  "100 Days of SwiftUI - Day 24 (repeated)"
date:   2020-05-01 03:37:11 +1200
categories: ohdos
---
According to the rules for taking part in [100 Days of SwiftUI](https://www.hackingwithswift.com/100/swiftui), as soon as I've finished each day, I have to post about it.

The topic for Day 24 (repeated) was: Project 3, part 2


text:
import assert from "assert";
import {
  PhenylMemoryDbEntityClient,
  createEntityClient
} from "../src/create-entity-client";
import { after, before, describe, it } from "mocha";

describe("MongoDBEntityClient", () => {
  let entityClient: PhenylMemoryDbEntityClient<{
    user: { id: string; name: string; hobbies: string[] };
  }>;

  let generatedId: string;
  let versionId: string;

  before(async () => {
    entityClient = createEntityClient({
      validatePushCommand: () => true
    });
  });

  after(async () => {
    await entityClient.delete({ entityName: "user", where: {} });
  });

  describe("update operation", () => {
    it("should succeed when only one operation", async () => {
      const result = await entityClient.insertAndGet({
        entityName: "user",
        value: {
          name: "Jone",
          hobbies: ["play baseball"]
        }
      });
      generatedId = result.entity.id;
      versionId = result.versionId;
      const ope = {
        $push: {
          hobbies: "JavaScript"
        }
      };
      await entityClient.push({
        entityName: "user",
        id: generatedId,
        operations: [ope],
        versionId
      });

      const updatedResult = await entityClient.get({
        entityName: "user",
        id: generatedId
      });

      assert.deepStrictEqual(updatedResult.entity.hobbies, [
        "play baseball",
        "JavaScript"
      ]);
    });

    it("should succeed when conflicted operations with set and push", async () => {
      const result = await entityClient.insertAndGet({
        entityName: "user",
        value: { name: "Jone", hobbies: ["play baseball"] }
      });
      generatedId = result.entity.id;
      versionId = result.versionId;

      await entityClient.push({
        entityName: "user",
        id: generatedId,
        operations: [
          { $set: { name: "Alpha", hobbies: ["TypeScript"] } },
          { $push: { hobbies: "JavaScript" } }
        ],
        versionId
      });

      const updatedEntity = await entityClient.findOne({
        entityName: "user",
        where: {
          id: generatedId
        }
      });

      assert.strictEqual(updatedEntity.entity.id, generatedId);
      assert.strictEqual(updatedEntity.entity.name, "Alpha");
      assert.deepStrictEqual(updatedEntity.entity.hobbies, [
        "TypeScript",
        "JavaScript"
      ]);
    });

    it("should succeed when the clientHeadVersionId behind from DB client versionId", async () => {
      const result = await entityClient.insertAndGet({
        entityName: "user",
        value: {
          name: "Jone",
          hobbies: ["play baseball"]
        }
      });
      generatedId = result.entity.id;
      versionId = result.versionId;

      // update version
      const ops = [{ $push: { hobbies: "JavaScript" } }];
      await entityClient.push({
        entityName: "user",
        id: generatedId,
        operations: ops,
        versionId
      });

      // update by 1 commit behind from DB HEAD
      const ops2 = [{ $push: { hobbies: "TypeScript" } }];
      await entityClient.push({
        entityName: "user",
        id: generatedId,
        operations: ops2,
        versionId
      });

      const update2Result = await entityClient.get({
        entityName: "user",
        id: generatedId
      });

      assert.deepStrictEqual(update2Result.entity.hobbies, [
        "play baseball",
        "JavaScript",
        "TypeScript"
      ]);
    });
  });
});


text:
http_path       = "/"
css_dir         = "assets/css/src"
sass_dir        = "assets/sass"
images_dir      = "assets/img"
javascripts_dir = "assets/js"
fonts_dir       = "assets/font"

http_fonts_path  = "assets/font"
http_images_path = "assets/img"

output_style    = :nested
relative_assets = false
line_comments   = false


text:
package parser

import (
	"fmt"
	"monkey/ast"
	"monkey/lexer"
	"monkey/token"
)

const (
	_ int = iota
	LOWEST
	ASSIGN
	OR
	AND
	EQUALS
	LESSGREATER
	SLICE
	SUM
	PRODUCT
	PREFIX
	CALL
	INDEX
)

var precedences = map[token.TokenType]int{
	token.ASSIGN:   ASSIGN,
	token.OR:       OR,
	token.AND:      AND,
	token.EQ:       EQUALS,
	token.NEQ:      EQUALS,
	token.LT:       LESSGREATER,
	token.GT:       LESSGREATER,
	token.PLUS:     SUM,
	token.MINUS:    SUM,
	token.MOD:      PRODUCT,
	token.ASTERISK: PRODUCT,
	token.SLASH:    PRODUCT,
	token.LPAREN:   CALL,
	token.DOT:      CALL,
	token.COLON:    SLICE,
	token.LBRACKET: INDEX,
}

type Parser struct {
	l      *lexer.Lexer
	errors []string
	path   string

	curToken  token.Token
	peekToken token.Token

	prefixParseFns map[token.TokenType]prefixParseFn
	infixParseFns  map[token.TokenType]infixParseFn
}

type (
	prefixParseFn func() ast.Expression
	infixParseFn  func(ast.Expression) ast.Expression
)

func (p *Parser) registerPrefix(tokenType token.TokenType, fn prefixParseFn) {
	p.prefixParseFns[tokenType] = fn
}

func (p *Parser) registerInfix(tokenType token.TokenType, fn infixParseFn) {
	p.infixParseFns[tokenType] = fn
}

func New(l *lexer.Lexer, wd string) *Parser {
	p := &Parser{
		l:      l,
		errors: []string{},
		path:   wd,
	}

	p.prefixParseFns = make(map[token.TokenType]prefixParseFn)
	p.registerPrefix(token.IDENT, p.parseIdentifier)
	p.registerPrefix(token.INT, p.parseIntegerLiteral)
	p.registerPrefix(token.BANG, p.parsePrefixExpression)
	p.registerPrefix(token.MINUS, p.parsePrefixExpression)
	p.registerPrefix(token.TRUE, p.parseBoolean)
	p.registerPrefix(token.FALSE, p.parseBoolean)
	p.registerPrefix(token.LPAREN, p.parseGroupedExpression)
	p.registerPrefix(token.IF, p.parseIfExpression)
	p.registerPrefix(token.FUNCTION, p.parseFunctionLiteral)
	p.registerPrefix(token.DO, p.parseDoLoopExpression)
	p.registerPrefix(token.STRING, p.parseStringLiteralExpression)
	p.registerPrefix(token.LBRACKET, p.parseArrayExpression)
	p.registerPrefix(token.LBRACE, p.parseHashExpression)
	p.registerPrefix(token.STRUCT, p.parseStructExpression)
	p.registerPrefix(token.ISTRING, p.parseInterpolatedString)
	p.registerPrefix(token.BREAK, p.parseBreakWithoutLoopContext)

	p.infixParseFns = make(map[token.TokenType]infixParseFn)
	p.registerInfix(token.PLUS, p.parseInfixExpression)
	p.registerInfix(token.MINUS, p.parseInfixExpression)
	p.registerInfix(token.ASTERISK, p.parseInfixExpression)
	p.registerInfix(token.EQ, p.parseInfixExpression)
	p.registerInfix(token.SLASH, p.parseInfixExpression)
	p.registerInfix(token.NEQ, p.parseInfixExpression)
	p.registerInfix(token.LT, p.parseInfixExpression)
	p.registerInfix(token.GT, p.parseInfixExpression)
	p.registerInfix(token.AND, p.parseInfixExpression)
	p.registerInfix(token.OR, p.parseInfixExpression)
	p.registerInfix(token.ASSIGN, p.parseAssignExpression)
	p.registerInfix(token.LPAREN, p.parseCallExpressions)
	p.registerInfix(token.LBRACKET, p.parseIndexExpression)
	p.registerInfix(token.DOT, p.parseMethodCallExpression)
	p.registerInfix(token.COLON, p.parseSliceExpression)
	p.registerInfix(token.MOD, p.parseInfixExpression)
	p.nextToken()
	p.nextToken()

	return p
}

func (p *Parser) ParseProgram() *ast.Program {
	program := &ast.Program{}
	program.Statements = []ast.Statement{}
	program.Includes = make(map[string]*ast.IncludeStatement)

	for p.curToken.Type != token.EOF {
		stmt := p.parseStatement()
		if stmt != nil {
			if include, ok := stmt.(*ast.IncludeStatement); ok {
				_, ok := program.Includes[include.IncludePath.String()]
				if !ok {
					program.Includes[include.IncludePath.String()] = include
				}
			} else {
				program.Statements = append(program.Statements, stmt)
			}
		}
		p.nextToken()
	}
	return program
}

func (p *Parser) parseStatement() ast.Statement {
	switch p.curToken.Type {
	case token.LET:
		return p.parseLetStatement()
	case token.RETURN:
		return p.parseReturnStatement()
	case token.INCLUDE:
		return p.parseIncludeStatement()
	default:
		return p.parseExpressionStatement()
	}
}

func (p *Parser) parseExpressionStatement() *ast.ExpressionStatement {
	stmt := &ast.ExpressionStatement{Token: p.curToken}

	stmt.Expression = p.parseExpression(LOWEST)

	if p.peekTokenIs(token.SEMICOLON) {
		p.nextToken()
	}
	return stmt
}

func (p *Parser) parseExpression(precedence int) ast.Expression {
	prefix := p.prefixParseFns[p.curToken.Type]
	if prefix == nil {
		p.noPrefixParseFnError(p.curToken.Type)
		return nil
	}
	leftExp := prefix()
	for !p.peekTokenIs(token.SEMICOLON) && precedence < p.peekPrecedence() {
		infix := p.infixParseFns[p.peekToken.Type]
		if infix == nil {
			return leftExp
		}
		p.nextToken()
		leftExp = infix(leftExp)
	}
	return leftExp
}

func (p *Parser) parsePrefixExpression() ast.Expression {
	expression := &ast.PrefixExpression{Token: p.curToken, Operator: p.curToken.Literal}
	p.nextToken()
	expression.Right = p.parseExpression(PREFIX)
	return expression
}

func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {
	expression := &ast.InfixExpression{
		Token:    p.curToken,
		Operator: p.curToken.Literal,
		Left:     left,
	}
	precedence := p.curPrecedence()
	p.nextToken()
	expression.Right = p.parseExpression(precedence)

	return expression
}

func (p *Parser) parseGroupedExpression() ast.Expression {
	p.nextToken()

	exp := p.parseExpression(LOWEST)
	if !p.expectPeek(token.RPAREN) {
		return nil
	}

	return exp
}

func (p *Parser) noPrefixParseFnError(t token.TokenType) {
	msg := fmt.Sprintf("no prefix parse functions for '%s' found", t)
	p.errors = append(p.errors, msg)
}

func (p *Parser) curTokenIs(t token.TokenType) bool {
	return p.curToken.Type == t
}

func (p *Parser) peekTokenIs(t token.TokenType) bool {
	return p.peekToken.Type == t
}

func (p *Parser) peekPrecedence() int {
	if p, ok := precedences[p.peekToken.Type]; ok {
		return p
	}
	return LOWEST
}

func (p *Parser) curPrecedence() int {
	if p, ok := precedences[p.curToken.Type]; ok {
		return p
	}
	return LOWEST
}

func (p *Parser) nextToken() {
	p.curToken = p.peekToken
	p.peekToken = p.l.NextToken()
}

func (p *Parser) nextInterpToken() {
	p.curToken = p.l.NextInterpToken()
	p.peekToken = p.l.NextToken()
}

func (p *Parser) expectPeek(t token.TokenType) bool {
	if p.peekTokenIs(t) {
		p.nextToken()
		return true
	}
	p.peekError(t)
	return false
}

func (p *Parser) peekError(t token.TokenType) {
	msg := fmt.Sprintf("expected next token to be %s, got %s instead", t, p.peekToken.Type)
	p.errors = append(p.errors, msg)
}

func (p *Parser) Errors() []string {
	return p.errors
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/readable/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

        <ion-nav-bar class="bar-stable">
            <ion-nav-back-button></ion-nav-back-button>
        </ion-nav-bar>
        <ion-nav-view></ion-nav-view>


text:
from math import sqrt
from itertools import product

def generate_primes(limit):
	is_prime = [True for i in range(limit)]
	for i in range(2, int(sqrt(limit))):
		if is_prime[i]:
			for j in range(i * i, limit, i):
				is_prime[j] = False
	return filter(lambda x: is_prime[x], range(2, limit))

primes = set(generate_primes(1000000))

def count_prime_w_replacement(num, digit):
	count = 0
	for c in range(0, 10):
		tmp = num.replace(digit, str(c))
		if tmp[0] <> '0' and int(tmp) in primes:
			count += 1
	return count

ans = 1000000
for p in primes:
	num = str(p)
	for c in range(0, 3):
		if num.count(str(c)) == 3 and count_prime_w_replacement(num, str(c)) > 7:
			ans = min(ans, p)

print ans


text:
package mock_test

import (
	"bytes"
	"net/http"
	"testing"

	"github.com/EscherAuth/escher/keydb"
	"github.com/EscherAuth/escher/request"
	"github.com/EscherAuth/escher/validator"
)

func requestBy(t testing.TB, method, path, body string) *request.Request {

	requestBody := bytes.NewReader([]byte(body))
	httpRequest, err := http.NewRequest(method, path, requestBody)

	if err != nil {
		t.Fatal(err)
	}

	escherRequest, err := request.NewFromHTTPRequest(httpRequest)

	if err != nil {
		t.Fatal(err)
	}

	return escherRequest
}

func useValidator(t testing.TB, v validator.Validator, request request.Interface, keydb keydb.KeyDB, mandatoryHeaders []string) (string, error) {
	return v.Validate(request, keydb, mandatoryHeaders)
}