text:
package org.apache.directory.server;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.Cursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultAttribute;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.filter.ExprNode;
import org.apache.directory.api.ldap.model.filter.PresenceNode;
import org.apache.directory.api.ldap.model.message.AliasDerefMode;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.AttributeTypeOptions;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.api.ldap.model.schema.registries.SchemaLoader;
import org.apache.directory.api.ldap.model.schema.syntaxCheckers.CsnSyntaxChecker;
import org.apache.directory.api.ldap.model.schema.syntaxCheckers.GeneralizedTimeSyntaxChecker;
import org.apache.directory.api.ldap.model.schema.syntaxCheckers.UuidSyntaxChecker;
import org.apache.directory.api.ldap.schema.extractor.SchemaLdifExtractor;
import org.apache.directory.api.ldap.schema.extractor.impl.DefaultSchemaLdifExtractor;
import org.apache.directory.api.ldap.schema.loader.LdifSchemaLoader;
import org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager;
import org.apache.directory.api.util.DateUtils;
import org.apache.directory.api.util.exception.Exceptions;
import org.apache.directory.server.config.ConfigPartitionReader;
import org.apache.directory.server.config.ConfigPartitionInitializer;
import org.apache.directory.server.config.beans.ConfigBean;
import org.apache.directory.server.config.beans.DirectoryServiceBean;
import org.apache.directory.server.config.beans.HttpServerBean;
import org.apache.directory.server.config.beans.JdbmPartitionBean;
import org.apache.directory.server.config.beans.LdapServerBean;
import org.apache.directory.server.config.beans.NtpServerBean;
import org.apache.directory.server.config.builder.ServiceBuilder;
import org.apache.directory.server.config.listener.ConfigChangeListener;
import org.apache.directory.server.core.api.CoreSession;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.api.DnFactory;
import org.apache.directory.server.core.api.InstanceLayout;
import org.apache.directory.server.core.api.event.EventType;
import org.apache.directory.server.core.api.event.NotificationCriteria;
import org.apache.directory.server.core.api.interceptor.context.ModifyOperationContext;
import org.apache.directory.server.core.api.partition.Partition;
import org.apache.directory.server.core.api.schema.SchemaPartition;
import org.apache.directory.server.core.partition.impl.btree.AbstractBTreePartition;
import org.apache.directory.server.core.partition.ldif.LdifPartition;
import org.apache.directory.server.core.security.CertificateUtil;
import org.apache.directory.server.core.shared.DefaultDnFactory;
import org.apache.directory.server.i18n.I18n;
import org.apache.directory.server.integration.http.HttpServer;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.ntp.NtpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A class used to start various servers in a given {@link InstanceLayout}.
 *
 * @author Apache Directory Project
 */
@SuppressWarnings("restriction")
public class ApacheDsService
{
    /** A logger for this class */
    private static final Logger LOG = LoggerFactory.getLogger( ApacheDsService.class );

    /** The LDAP server instance */
    private LdapServer ldapServer;

    /** The NTP server instance */
    private NtpServer ntpServer;

    /** The DNS server instance */
    //    private DnsServer dnsServer;

    /** The started HttpServer */
    private HttpServer httpServer;

    /** The Schema partition */
    private LdifPartition schemaLdifPartition;

    /** The SchemaManager instance */
    private SchemaManager schemaManager;

    /** The configuration partition */
    private LdifPartition configPartition;

    // variables used during the initial startup to update the mandatory operational
    // attributes
    /** The UUID syntax checker instance */
    private UuidSyntaxChecker uuidChecker = UuidSyntaxChecker.INSTANCE;

    /** The CSN syntax checker instance */
    private CsnSyntaxChecker csnChecker = CsnSyntaxChecker.INSTANCE;

    private GeneralizedTimeSyntaxChecker timeChecker = GeneralizedTimeSyntaxChecker.INSTANCE;

    private static final Map<String, AttributeTypeOptions> MANDATORY_ENTRY_ATOP_MAP = new HashMap<>();
    private static final String[] MANDATORY_ENTRY_ATOP_AT = new String[5];

    private boolean isSchemaPartitionFirstExtraction = false;

    /**
     * Starts various services configured according to the
     *
     * @param instanceLayout the on disk location's layout of the instance to be started
     * @throws Exception If we failed to start the server
     */
    public void start( InstanceLayout instanceLayout ) throws Exception
    {
        start( instanceLayout, true );
    }

    /**
     * starts various services configured according to the
     * configuration present in the given instance's layout
     *
     * @param instanceLayout the on disk location's layout of the instance to be started
     * @param startServers Tell the server that the various servers have to be started too
     * @throws Exception If we failed to start the server
     */
    public void start( InstanceLayout instanceLayout, boolean startServers ) throws Exception
    {
        File partitionsDir = instanceLayout.getPartitionsDirectory();

        if ( !partitionsDir.exists() )
        {
            LOG.info( "partition directory doesn't exist, creating {}", partitionsDir.getAbsolutePath() );

            if ( !partitionsDir.mkdirs() )
            {
                throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECTORY, partitionsDir ) );
            }
        }

        LOG.info( "using partition dir {}", partitionsDir.getAbsolutePath() );

        initSchemaManager( instanceLayout );
        DnFactory bootstrapDnFactory = new DefaultDnFactory( schemaManager, 100 );
        initSchemaLdifPartition( instanceLayout, bootstrapDnFactory );
        initConfigPartition( instanceLayout, bootstrapDnFactory );

        // Read the configuration
        ConfigPartitionReader cpReader = new ConfigPartitionReader( configPartition );

        ConfigBean configBean = cpReader.readConfig();

        DirectoryServiceBean directoryServiceBean = configBean.getDirectoryServiceBean();

        /*
         * Calculate the DN cache size: from all defined partitions get the max cache size setting.
         * Note: currently only JDBM partition beans have such a setting.
         */
        int dnCacheSize = directoryServiceBean.getPartitions().stream()
            .filter( JdbmPartitionBean.class::isInstance )
            .map( JdbmPartitionBean.class::cast )
            .map( JdbmPartitionBean::getPartitionCacheSize )
            .mapToInt( Integer::intValue )
            .max().orElse( AbstractBTreePartition.DEFAULT_CACHE_SIZE );
        DnFactory dnFactory = new DefaultDnFactory( schemaManager, dnCacheSize );

        // Initialize the DirectoryService now
        DirectoryService directoryService = initDirectoryService( instanceLayout, directoryServiceBean, dnFactory );

        // start the LDAP server
        LdapServerBean ldapServerBean = directoryServiceBean.getLdapServerBean();

        if ( ldapServerBean.getLdapServerKeystoreFile() == null )
        {
            File ldapServerKeystoreFile = instanceLayout.getKeyStoreFile();

            if ( !ldapServerKeystoreFile.exists() )
            {
                ldapServerBean.setLdapServerCertificatePassword( "secret" );

                // We need to create a KeyStore
                ldapServerKeystoreFile = CertificateUtil.createTempKeyStore( "tempks", "secret".toCharArray() );
            }

            ldapServerBean.setLdapServerKeystoreFile( ldapServerKeystoreFile.getAbsolutePath() );
        }

        if ( ldapServerBean.getLdapServerCertificatePassword() == null )
        {
            ldapServerBean.setLdapServerCertificatePassword( "secret" );
        }

        startLdap( ldapServerBean, directoryService, startServers );

        // start the NTP server
        startNtp( directoryServiceBean.getNtpServerBean(), directoryService, startServers );

        // Initialize the DNS server (Not ready yet)
        // initDns( configBean );

        // Initialize the DHCP server (Not ready yet)
        // initDhcp( configBean );

        // start the jetty http server
        startHttpServer( directoryServiceBean.getHttpServerBean(), directoryService, startServers );

        LOG.info( "Registering config change listener" );
        ConfigChangeListener configListener = new ConfigChangeListener( cpReader, directoryService );

        NotificationCriteria criteria = new NotificationCriteria( directoryService.getSchemaManager() );
        criteria.setBase( configPartition.getSuffixDn() );
        criteria.setEventMask( EventType.ALL_EVENT_TYPES_MASK );

        PresenceNode filter = new PresenceNode( SchemaConstants.OBJECT_CLASS_AT );
        criteria.setFilter( filter );
        criteria.setScope( SearchScope.SUBTREE );

        directoryService.getEventService().addListener( configListener, criteria );
    }

    /**
     * Try to repair the partitions. Precondition is that this service was started before.
     *
     * @param instanceLayout the on disk location's layout of the intance to be repaired
     * @throws Exception If the repair failed
     */
    public void repair( InstanceLayout instanceLayout ) throws Exception
    {
        File partitionsDir = instanceLayout.getPartitionsDirectory();

        System.out.println( "Repairing partition dir " + partitionsDir.getAbsolutePath() );

        Set<? extends Partition> partitions = getDirectoryService().getPartitions();

        // Iterate on the partitions to repair them
        for ( Partition partition : partitions )
        {
            try
            {
                partition.repair();
            }
            catch ( Exception e )
            {
                System.out.println( "Failed to repair the partition " + partition.getId() );
                e.printStackTrace();
                return;
            }
        }
    }

    /**
     * Initialize the schema Manager by loading the schema LDIF files
     *
     * @param instanceLayout the instance layout
     * @throws Exception in case of any problems while extracting and writing the schema files
     */
    private void initSchemaManager( InstanceLayout instanceLayout ) throws Exception
    {
        File schemaPartitionDirectory = new File( instanceLayout.getPartitionsDirectory(), "schema" );

        // Extract the schema on disk (a brand new one) and load the registries
        if ( schemaPartitionDirectory.exists() )
        {
            LOG.info( "schema partition already exists, skipping schema extraction" );
        }
        else
        {
            SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( instanceLayout.getPartitionsDirectory() );
            extractor.extractOrCopy();
            isSchemaPartitionFirstExtraction = true;
        }

        SchemaLoader loader = new LdifSchemaLoader( schemaPartitionDirectory );
        schemaManager = new DefaultSchemaManager( loader.getAllSchemas() );

        // We have to load the schema now, otherwise we won't be able
        // to initialize the Partitions, as we won't be able to parse
        // and normalize their suffix Dn
        schemaManager.loadAllEnabled();

        List<Throwable> errors = schemaManager.getErrors();

        if ( !errors.isEmpty() )
        {
            throw new Exception( I18n.err( I18n.ERR_317, Exceptions.printErrors( errors ) ) );
        }
    }

    /**
     * Initialize the schema partition
     *
     * @param instanceLayout the instance layout
     */
    private void initSchemaLdifPartition( InstanceLayout instanceLayout, DnFactory dnFactory )
    {
        File schemaPartitionDirectory = new File( instanceLayout.getPartitionsDirectory(), "schema" );

        // Init the LdifPartition
        schemaLdifPartition = new LdifPartition( schemaManager, dnFactory );
        schemaLdifPartition.setPartitionPath( schemaPartitionDirectory.toURI() );
    }

    /**
     *
     * initializes a LDIF partition for configuration
     *
     * @param instanceLayout the instance layout
     * @param cacheService the Cache service
     * @throws Exception in case of any issues while extracting the schema
     */
    private void initConfigPartition( InstanceLayout instanceLayout, DnFactory dnFactory )
        throws Exception
    {
        ConfigPartitionInitializer initializer = new ConfigPartitionInitializer( instanceLayout, dnFactory,
            schemaManager );
        configPartition = initializer.initConfigPartition();
    }

    private DirectoryService initDirectoryService( InstanceLayout instanceLayout,
        DirectoryServiceBean directoryServiceBean, DnFactory dnFactory ) throws Exception
    {
         LOG.info( "Initializing the DirectoryService..." );

        long startTime = System.currentTimeMillis();

        DirectoryService directoryService = ServiceBuilder.createDirectoryService( directoryServiceBean,
            instanceLayout, schemaManager );

        // Inject the DnFactory
        directoryService.setDnFactory( dnFactory );

        // The schema partition
        SchemaPartition schemaPartition = new SchemaPartition( schemaManager );
        schemaPartition.setWrappedPartition( schemaLdifPartition );
        directoryService.setSchemaPartition( schemaPartition );

        directoryService.addPartition( configPartition );

        // Store the default directories
        directoryService.setInstanceLayout( instanceLayout );

        directoryService.startup();

        AttributeType ocAt = directoryService.getAtProvider().getObjectClass();
        MANDATORY_ENTRY_ATOP_MAP.put( ocAt.getName(), new AttributeTypeOptions( ocAt ) );

        AttributeType uuidAt = directoryService.getAtProvider().getEntryUUID();
        MANDATORY_ENTRY_ATOP_MAP.put( uuidAt.getName(), new AttributeTypeOptions( uuidAt ) );

        AttributeType csnAt = directoryService.getAtProvider().getEntryCSN();
        MANDATORY_ENTRY_ATOP_MAP.put( csnAt.getName(), new AttributeTypeOptions( csnAt ) );

        AttributeType creatorAt = directoryService.getAtProvider().getCreatorsName();
        MANDATORY_ENTRY_ATOP_MAP.put( creatorAt.getName(), new AttributeTypeOptions( creatorAt ) );

        AttributeType createdTimeAt = directoryService.getAtProvider().getCreateTimestamp();
        MANDATORY_ENTRY_ATOP_MAP.put( createdTimeAt.getName(), new AttributeTypeOptions( createdTimeAt ) );

        int pos = 0;

        for ( AttributeTypeOptions attributeTypeOptions : MANDATORY_ENTRY_ATOP_MAP.values() )
        {
            MANDATORY_ENTRY_ATOP_AT[pos++] = attributeTypeOptions.getAttributeType().getName();
        }

        if ( isSchemaPartitionFirstExtraction )
        {
            LOG.info( "begining to update schema partition LDIF files after modifying manadatory attributes" );

            updateMandatoryOpAttributes( schemaLdifPartition, directoryService );

            LOG.info( "schema partition data was successfully updated" );
        }

        LOG.info( "DirectoryService initialized in {} milliseconds", ( System.currentTimeMillis() - startTime ) );

        return directoryService;
    }

    /**
     * start the LDAP server
     */
    private void startLdap( LdapServerBean ldapServerBean, DirectoryService directoryService, boolean startServers ) throws Exception
    {
        LOG.info( "Starting the LDAP server" );
        long startTime = System.currentTimeMillis();

        // Add a reference to the KeyStore file, or create one if missing

        ldapServer = ServiceBuilder.createLdapServer( ldapServerBean, directoryService );

        if ( ldapServer == null )
        {
            LOG.info( "Cannot find any reference to the LDAP Server in the configuration : the server won't be started" );
            return;
        }

        printBanner( BANNER_LDAP );

        // And start the server now if required
        if ( startServers )
        {
            ldapServer.start();
        }

        LOG.info( "LDAP server: started in {} milliseconds", ( System.currentTimeMillis() - startTime ) );
    }

    /**
     * start the NTP server
     */
    private void startNtp( NtpServerBean ntpServerBean, DirectoryService directoryService, boolean startServers ) throws Exception
    {
        LOG.info( "Starting the NTP server" );
        long startTime = System.currentTimeMillis();

        ntpServer = ServiceBuilder.createNtpServer( ntpServerBean, directoryService );

        if ( ntpServer == null )
        {
            LOG.info( "Cannot find any reference to the NTP Server in the configuration : the server won't be started" );
            return;
        }

        printBanner( BANNER_NTP );

        if ( startServers )
        {
            ntpServer.start();
        }

        if ( LOG.isInfoEnabled() )
        {
            LOG.info( "NTP server: started in {} milliseconds", ( System.currentTimeMillis() - startTime ) + "" );
        }
    }

    /**
     * Initialize the DNS server
     */
    //    private void initDns( InstanceLayout layout ) throws Exception
    //    {
    //        if ( factory == null )
    //        {
    //            return;
    //        }
    //
    //        try
    //        {
    //            dnsServer = ( DnsServer ) factory.getBean( "dnsServer" );
    //        }
    //        catch ( Exception e )
    //        {
    //            LOG.info( "Cannot find any reference to the DNS Server in the configuration : the server won't be started" );
    //            return;
    //        }
    //
    //        System.out.println( "Starting the DNS server" );
    //        LOG.info( "Starting the DNS server" );
    //
    //        printBanner( BANNER_DNS );
    //        long startTime = System.currentTimeMillis();
    //
    //        dnsServer.start();
    //        System.out.println( "DNS Server started" );
    //
    //        if ( LOG.isInfoEnabled() )
    //        {
    //            LOG.info( "DNS server: started in {} milliseconds", ( System.currentTimeMillis() - startTime ) + "" );
    //        }
    //    }

    /**
     * start the embedded HTTP server
     */
    private void startHttpServer( HttpServerBean httpServerBean, DirectoryService directoryService, boolean startServers ) throws Exception
    {
        httpServer = ServiceBuilder.createHttpServer( httpServerBean, directoryService );

        if ( httpServer == null )
        {
            LOG.info( "Cannot find any reference to the HTTP Server in the configuration : the server won't be started" );
            return;
        }

        LOG.info( "Starting the Http server" );
        long startTime = System.currentTimeMillis();

        if ( startServers )
        {
            httpServer.start( getDirectoryService() );
        }

        if ( LOG.isInfoEnabled() )
        {
            LOG.info( "Http server: started in {} milliseconds", ( System.currentTimeMillis() - startTime )
                + "" );
        }
    }

    public DirectoryService getDirectoryService()
    {
        return ldapServer.getDirectoryService();
    }

    public void synch() throws Exception
    {
        ldapServer.getDirectoryService().sync();
    }

    public void stop() throws Exception
    {
        DirectoryService directoryService = null;

        // Stops the server
        if ( ldapServer != null )
        {
            ldapServer.stop();
            directoryService = ldapServer.getDirectoryService();
        }

        if ( ntpServer != null )
        {
            ntpServer.stop();
        }

        if ( httpServer != null )
        {
            httpServer.stop();
        }

        // We now have to stop the underlaying DirectoryService
        if ( directoryService != null )
        {
            directoryService.shutdown();
        }
    }

    private static final String BANNER_LDAP = "           _                     _          ____  ____   \n"
        + "          / \\   _ __    ___  ___| |__   ___|  _ \\/ ___|  \n"
        + "         / _ \\ | '_ \\ / _` |/ __| '_ \\ / _ \\ | | \\___ \\  \n"
        + "        / ___ \\| |_) | (_| | (__| | | |  __/ |_| |___) | \n"
        + "       /_/   \\_\\ .__/ \\__,_|\\___|_| |_|\\___|____/|____/  \n"
        + "               |_|                                       \n";

    private static final String BANNER_NTP = "           _                     _          _   _ _____ _ __    \n"
        + "          / \\   _ __    ___  ___| |__   ___| \\ | |_  __| '_ \\   \n"
        + "         / _ \\ | '_ \\ / _` |/ __| '_ \\ / _ \\ .\\| | | | | |_) |  \n"
        + "        / ___ \\| |_) | (_| | (__| | | |  __/ |\\  | | | | .__/   \n"
        + "       /_/   \\_\\ .__/ \\__,_|\\___|_| |_|\\___|_| \\_| |_| |_|      \n"
        + "               |_|                                              \n";

    //    private static final String BANNER_DNS =
    //          "           _                     _          ____  _   _ ____    \n"
    //        + "          / \\   _ __    ___  ___| |__   ___|  _ \\| \\ | / ___|   \n"
    //        + "         / _ \\ | '_ \\ / _` |/ __| '_ \\ / _ \\ | | |  \\| \\__  \\   \n"
    //        + "        / ___ \\| |_) | (_| | (__| | | |  __/ |_| | . ' |___) |  \n"
    //        + "       /_/   \\_\\ .__/ \\__,_|\\___|_| |_|\\___|____/|_|\\__|____/   \n"
    //        + "               |_|                                              \n";
    //
    //
    //    private static final String BANNER_DHCP =
    //          "           _                     _          ____  _   _  ___ ____  \n"
    //        + "          / \\   _ __    ___  ___| |__   ___|  _ \\| | | |/ __|  _ \\ \n"
    //        + "         / _ \\ | '_ \\ / _` |/ __| '_ \\ / _ \\ | | | |_| / /  | |_) )\n"
    //        + "        / ___ \\| |_) | (_| | (__| | | |  __/ |_| |  _  \\ \\__|  __/ \n"
    //        + "       /_/   \\_\\ .__/ \\__,_|\\___|_| |_|\\___|____/|_| |_|\\___|_|    \n"
    //        + "               |_|                                                 \n";

    /**
     * Print the banner for a server
     *
     * @param bannerConstant The banner to print
     */
    public static void printBanner( String bannerConstant )
    {
        System.out.println( bannerConstant );
    }

    /**
     *
     * adds mandatory operational attributes {@link #MANDATORY_ENTRY_ATOP_MAP} and updates all the LDIF files.
     * WARN: this method is only called for the first time when schema and config files are bootstrapped
     *       afterwards it is the responsibility of the user to ensure correctness of LDIF files if modified
     *       by hand
     *
     * Note: we do these modifications explicitly cause we have no idea if each entry's LDIF file has the
     *       correct values for all these mandatory attributes
     *
     * @param partition instance of the partition Note: should only be those which are loaded before starting the DirectoryService
     * @param dirService the DirectoryService instance
     * @throws Exception  If the update failed
     */
    public void updateMandatoryOpAttributes( Partition partition, DirectoryService dirService ) throws Exception
    {
        CoreSession session = dirService.getAdminSession();

        String adminDn = session.getEffectivePrincipal().getName();

        ExprNode filter = new PresenceNode( SchemaConstants.OBJECT_CLASS_AT );

        Cursor<Entry> cursor = session.search( partition.getSuffixDn(), SearchScope.SUBTREE, filter,
            AliasDerefMode.NEVER_DEREF_ALIASES, MANDATORY_ENTRY_ATOP_AT );
        cursor.beforeFirst();

        List<Modification> mods = new ArrayList<>();

        while ( cursor.next() )
        {
            Entry entry = cursor.get();

            AttributeType atType = MANDATORY_ENTRY_ATOP_MAP.get( SchemaConstants.ENTRY_UUID_AT ).getAttributeType();

            Attribute uuidAt = entry.get( atType );
            String uuid = ( uuidAt == null ? null : uuidAt.getString() );

            if ( !uuidChecker.isValidSyntax( uuid ) )
            {
                uuidAt = new DefaultAttribute( atType, UUID.randomUUID().toString() );
            }

            Modification uuidMod = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, uuidAt );
            mods.add( uuidMod );

            atType = MANDATORY_ENTRY_ATOP_MAP.get( SchemaConstants.ENTRY_CSN_AT ).getAttributeType();
            Attribute csnAt = entry.get( atType );
            String csn = ( csnAt == null ? null : csnAt.getString() );

            if ( !csnChecker.isValidSyntax( csn ) )
            {
                csnAt = new DefaultAttribute( atType, dirService.getCSN().toString() );
            }

            Modification csnMod = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, csnAt );
            mods.add( csnMod );

            atType = MANDATORY_ENTRY_ATOP_MAP.get( SchemaConstants.CREATORS_NAME_AT ).getAttributeType();
            Attribute creatorAt = entry.get( atType );
            String creator = ( creatorAt == null ? "" : creatorAt.getString().trim() );

            if ( ( creator.length() == 0 ) || ( !Dn.isValid( creator ) ) )
            {
                creatorAt = new DefaultAttribute( atType, adminDn );
            }

            Modification creatorMod = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, creatorAt );
            mods.add( creatorMod );

            atType = MANDATORY_ENTRY_ATOP_MAP.get( SchemaConstants.CREATE_TIMESTAMP_AT ).getAttributeType();
            Attribute createdTimeAt = entry.get( atType );
            String createdTime = ( createdTimeAt == null ? null : createdTimeAt.getString() );

            if ( !timeChecker.isValidSyntax( createdTime ) )
            {
                createdTimeAt = new DefaultAttribute( atType, DateUtils.getGeneralizedTime( dirService.getTimeProvider() ) );
            }

            Modification createdMod = new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, createdTimeAt );
            mods.add( createdMod );

            if ( !mods.isEmpty() )
            {
                LOG.debug( "modifying the entry {} after adding missing manadatory operational attributes",
                    entry.getDn() );
                ModifyOperationContext modifyContext = new ModifyOperationContext( session );
                modifyContext.setEntry( entry );
                modifyContext.setDn( entry.getDn() );
                modifyContext.setModItems( mods );
                partition.modify( modifyContext );
            }

            mods.clear();
        }

        cursor.close();
    }

}


text:
/*jshint node:true*/
'use strict';

var express = require('express'),
    bodyParser = require('body-parser'),
    glob = require('glob'),
    path = require('path'),
    app = express(),
    port = process.env.PORT || 8000,
    routes = require('./routes'),
    src_deps = require('../scripts/get_src_deps')(),
    vendor_deps = require('./vendor-deps');

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.get('/ping', function(req, res, next) {
    console.log(req.query);
    res.send('pong');
});
app.use("/src", express.static(path.resolve(__dirname + "/../client/")));
app.use("/assets", express.static(path.resolve(__dirname + "/../client/assets")));
app.use("/vendor", express.static(path.resolve(__dirname + "/../node_modules/")));
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Headers", "App-Name");
    next();
});
app.use("/api", routes);

app.use(require('./util/error_handler'));
app.get("/*", function (req, res) {
    res.render('index', {
        vendor_deps: vendor_deps,
        src_deps: src_deps
    });
});
app.listen(port, function() {
    console.log('************************');
    console.log('Server is go');
    console.log('Listening on port ' + port);
});

redpajama_set_name: RedPajamaGithub


text:
HangFire.TinyIoC
================

[![Build status](https://ci.appveyor.com/api/projects/status/o5fdyjwi1f38xjmm)](https://ci.appveyor.com/project/RichClement/hangfire-tinyioc)

[HangFire](http://hangfire.io) background job activator based on [TinyIoC](https://github.com/grumpydev/TinyIoC) Container. It allows you to use instance methods of classes that define parameterized constructors

Installation
------

HangFire.TinyIoC is available as a NuGet Package. Type the following command into the Nuget package Manager Console window to install it:

```
Install-Package Hangfire.TinyIoC
```

Usage
------

This package provides an extension method for [OWIN bootstrapper](http://docs.hangfire.io/en/latest/users-guide/getting-started/owin-bootstrapper.html):

```csharp
app.UseHangfire(config =>
{
	var container = new TinyIoCContainer();
	config.UseTinyIoCActivator(container);
});
```

In order to use the library outside of web application, set the static JobActivator.Current property:

```csharp
var container = new TinyIoCContainer();
JobActivator.Current = new TinyIoCJobActivator(container);
```


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
Copyright (C) 2006 StatPro Italia srl

This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/

QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license.  You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/models/marketmodels/products/multiproductcomposite.hpp>

namespace QuantLib {

    Size MultiProductComposite::numberOfProducts() const {
        Size result = 0;
        for (const_iterator i=components_.begin(); i!=components_.end(); ++i)
            result += i->product->numberOfProducts();
        return result;
    }

    Size MultiProductComposite::maxNumberOfCashFlowsPerProductPerStep() const {
        Size result = 0;
        for (const_iterator i=components_.begin(); i!=components_.end(); ++i)
            result = std::max(result,
            i->product
            ->maxNumberOfCashFlowsPerProductPerStep());
        return result;
    }

    bool MultiProductComposite::nextTimeStep(
                     const CurveState& currentState,
                     std::vector<Size>& numberCashFlowsThisStep,
                     std::vector<std::vector<CashFlow> >& cashFlowsGenerated) {
        QL_REQUIRE(finalized_, "composite not finalized");
        bool done = true;
        Size n = 0, offset = 0;
        // for each sub-product...
        for (iterator i=components_.begin(); i!=components_.end(); ++i, ++n) {
            if (isInSubset_[n][currentIndex_] && !i->done) {
                // ...make it evolve...
                bool thisDone = i->product->nextTimeStep(currentState,
                                                         i->numberOfCashflows,
                                                         i->cashflows);
                // ...and copy the results. Time indices need to be remapped
                // so that they point into all cash-flow times. Amounts need
                // to be adjusted by the corresponding multiplier.
                for (Size j=0; j<i->product->numberOfProducts(); ++j) {
                    numberCashFlowsThisStep[j+offset] =
                        i->numberOfCashflows[j];
                    for (Size k=0; k<i->numberOfCashflows[j]; ++k) {
                        CashFlow& from = i->cashflows[j][k];
                        CashFlow& to = cashFlowsGenerated[j+offset][k];
                        to.timeIndex = i->timeIndices[from.timeIndex];
                        to.amount = from.amount * i->multiplier;
                    }
                }
                // finally, set done to false if this product isn't done
                done = done && thisDone;
            }
            else
                for (Size j=0; j<i->product->numberOfProducts(); ++j)
                    numberCashFlowsThisStep[j+offset] =0;

            // the offset is updated whether or not the product was evolved
            offset += i->product->numberOfProducts();
        }
        ++currentIndex_;
        return done;
    }

    std::auto_ptr<MarketModelMultiProduct>
        MultiProductComposite::clone() const {
            return std::auto_ptr<MarketModelMultiProduct>(
                new MultiProductComposite(*this));
    }

}


text:
<tool id="megablast_wrapper" name="Megablast" version="1.0.0">
	<description> compare short reads against nt and wgs databases</description>
	<command interpreter="python">megablast_wrapper.py $source_select $input_query $output1 $word_size $iden_cutoff $evalue_cutoff $filter_query ${GALAXY_DATA_INDEX_DIR}</command>
	<inputs>
		<param name="input_query" type="data" format="fasta" label="Compare these sequences"/>
		<param name="source_select" type="select" display="radio" label="against target database">
			<options from_file="blastdb.loc">
			  <column name="name" index="0"/>
			  <column name="value" index="0"/>
			</options>
		</param>
		<param name="word_size" type="select" label="using word size" help="Size of best perfect match">
			<option value="28">28</option>
			<option value="16">16</option>
		</param>
		<param name="iden_cutoff" type="float" size="15" value="90.0" label="report hits above this identity" help="no cutoff if 0" />
        <param name="evalue_cutoff" type="float" size="15" value="0.001" label="set expectation value cutoff" />
		<param name="filter_query" type="select" label="Filter out low complexity regions?">
            <option value="T">Yes</option>
            <option value="F">No</option>
		</param>
	</inputs>
	<outputs>
		<data name="output1" format="tabular"/>
	</outputs>
	<requirements>
		<requirement type="binary">megablast</requirement>
	</requirements>
	<tests>
		<test>
			<param name="input_query" value="megablast_wrapper_test1.fa" ftype="fasta"/>
			<param name="source_select" value="test" />
			<param name="word_size" value="28" />
			<param name="iden_cutoff" value="99.0" />
			<param name="evalue_cutoff" value="10.0" />
			<param name="filter_query" value="T" />
			<output name="output1" file="megablast_wrapper_test1.out"/>
		</test>
	</tests>
	<help>

.. class:: warningmark

**Note**. Database searches may take substantial amount of time. For large input datasets it is advisable to allow overnight processing.

-----

**What it does**

This tool runs **megablast** (for information about megablast, please see the reference below) a high performance nucleotide local aligner developed by Webb Miller and colleagues.

-----

**Output format**

Output of this tool contains 13 columns delimited by Tabs:

1. Id of your sequence
2. GI of the database hit
3. Length of the database hit
4. % identity
5. Alignment length
6. # mismatches
7. # gaps
8. Start position in your sequence
9. End position in your sequence
10. Start position in database hit
11. End position in database hit
12. E-value
13. Bit score

-------

**Reference**

Zhang et al. A Greedy Algorithm for Aligning DNA Sequences. 2000. JCB: 203-214.

	</help>
</tool>


text:
import React, { useEffect, useState } from 'react';
import { ErrorMessage, Field, Form, FormikProvider, useFormik } from 'formik';
import * as Yup from 'yup';
import { useRouter } from 'next/router';

const SignIn = () => {
  const router = useRouter();
  const [errorLog, setErrorLog] = useState([]);

  const formik = useFormik({
    validateOnMount: router.query.validateOnMount === 'true',
    validateOnBlur: router.query.validateOnBlur !== 'false',
    validateOnChange: router.query.validateOnChange !== 'false',
    initialValues: { username: '', password: '' },
    validationSchema: Yup.object().shape({
      username: Yup.string().required('Required'),
      password: Yup.string().required('Required'),
    }),
    onSubmit: async values => {
      await new Promise(r => setTimeout(r, 500));
      alert(JSON.stringify(values, null, 2));
    },
  });

  useEffect(() => {
    if (formik.errors.username && formik.touched.username) {
      setErrorLog(logs => [
        ...logs,
        {
          name: 'username',
          value: formik.values.username,
          error: formik.errors.username,
        },
      ]);
    }

    if (formik.errors.password && formik.touched.password) {
      setErrorLog(logs => [
        ...logs,
        {
          name: 'password',
          value: formik.values.password,
          error: formik.errors.password,
        },
      ]);
    }
  }, [
    formik.values.username,
    formik.errors.username,
    formik.touched.username,
    formik.values.password,
    formik.errors.password,
    formik.touched.password,
  ]);

  return (

Sign In

      <FormikProvider value={formik}>
        <Form>

            <Field name="username" placeholder="Username" />
            <ErrorMessage name="username" component="p" />

            <Field name="password" placeholder="Password" type="password" />
            <ErrorMessage name="password" component="p" />

          <button type="submit" disabled={!formik.isValid}>
            Submit
          </button>

          <button
            type="reset"
            onClick={() => {
              setErrorLog([]);
            }}
          >
            Reset
          </button>

{JSON.stringify(errorLog, null, 2)}

        </Form>
      </FormikProvider>

  );
};

export default SignIn;


text:
- Juice up the 404 page [404.html](404.html)
- Paginate posts [announcements.html](announcements.html)
- add Search [baseof.html](baseof.html)
- use safeHTML to make sure the HTML declrations all show - was creating errors [baseof.html](baseof.html)
- These need to be sorted by the order they are given in the globals file. Now they are random [color-palette.html](color-palette.html)
- It doesn't look like the second sort parameter (interior) actually sorts [index.html](index.html)
- It doesn't look like the second sort parameter (interior) actually sorts [list.html](list.html)
- Not getting ismenucurrent [nav-links.html](nav-links.html)
- opengraph ! [opengraph.html](opengraph.html)
- account for more than one tag. (case of "prices" not showing up on Memberhsip plans) [single.html](single.html)
- Sort by alpha [single.html](single.html)


text:
from Framework.Resposta import Resposta
from Models.Matricula import Matricula as ModelMatricula

class RespostaEditar(Resposta):

	def __init__(self,mensagem):
		self.corpo = mensagem


text:
import se.gu.ling.trindikit.oaa.common.*;
import com.sri.oaa2.icl.*;
public class Song extends OAASolver{

    private MusicDbAgent dba;
    static String solvableString="song(A)";

    public Song(MusicDbAgent _dba){
	super(solvableString);
	dba=_dba;
    }

    public boolean solve(IclTerm goal, IclList params, IclList answers){
	IclList ans=new IclList();
	IclTerm q = new IclStruct("post",goal);
	IclDb db=dba.getDb();
	if(db==null)
	    return false;
	if(db.db_Solve(q, new IclList(),ans)){
	    for(int i=0;i<ans.size();i++){
		answers.add(ans.getTerm(i).getTerm(0));
	    }
	    return true;
	}
	else return false;
    }

}


text:
#ifndef _RWAPP_CONFIG_H_
#define _RWAPP_CONFIG_H_

/**
 ****************************************************************************************
 * @addtogroup app
 * @brief Application configuration definition
 *
 * @{
 ****************************************************************************************
 */

/*
 * INCLUDE FILES
 ****************************************************************************************
 */

/*
 * DEFINES
 ****************************************************************************************
 */

/******************************************************************************************/
/* -------------------------   BLE APPLICATION SETTINGS      -----------------------------*/
/******************************************************************************************/

/// Health Thermometer Application
#if defined(CFG_APP_HT)
#define BLE_APP_HT           1
#else // defined(CFG_APP_HT)
#define BLE_APP_HT           0
#endif // defined(CFG_APP_HT)

/// HID Application
#if defined(CFG_APP_HID)
#define BLE_APP_HID          1
#else // defined(CFG_APP_HID)
#define BLE_APP_HID          0
#endif // defined(CFG_APP_HID)

/// DIS Application
#if defined(CFG_APP_DIS)
#define BLE_APP_DIS          1
#else // defined(CFG_APP_DIS)
#define BLE_APP_DIS          0
#endif // defined(CFG_APP_DIS)

/// Time Application
#if defined(CFG_APP_TIME)
#define BLE_APP_TIME         1
#else // defined(CFG_APP_TIME)
#define BLE_APP_TIME         0
#endif // defined(CFG_APP_TIME)

/// Battery Service Application
#if defined(CFG_PRF_BASS)
#define BLE_APP_BATT          1
#else
#define BLE_APP_BATT          0
#endif // defined(CFG_PRF_BCSS)

/// Security Application
#if (defined(CFG_APP_SEC) || BLE_APP_HID || defined(BLE_APP_AM0))
#define BLE_APP_SEC          1
//#define BLE_APP_SEC_CON       1
#else // defined(CFG_APP_SEC)
#define BLE_APP_SEC          0
#endif // defined(CFG_APP_SEC)

/// user-defined
#if defined(CFG_APP_USER)
#define BLE_APP_USER           1
#else // defined(CFG_APP_USER)
#define BLE_APP_USER          0
#endif // defined(CFG_APP_USER)

/// @} rwapp_config

#endif /* _RWAPP_CONFIG_H_ */


text:
@interface LGX01ViewController : UIViewController

@end


text:
@extends('mixdinternet/admix::form')

@section('title')
    Gerenciar {{ strtolower(config('marticles.name', 'Artigos')) }}
@endsection

@section('form')
    {!! BootForm::horizontal(['model' => $article, 'store' => 'admin.articles.store', 'update' => 'admin.articles.update'
        , 'id' => 'form-model', 'class' => 'form-horizontal form-rocket jq-form-validate jq-form-save'
        , 'files' => true ]) !!}

Geral

SEO

            @if (config('marticles.galleries', true))

Galeria

            @endif

                @if ($article['id'])
                    {!! BootForm::text('id', 'Código', null, ['disabled' => true]) !!}
                @endif

                {!! BootForm::select('status', 'Status', ['active' => 'Ativo', 'inactive' => 'Inativo'], null
                    , ['class' => 'jq-select2', 'data-rule-required' => true]) !!}

                {!! BootForm::select('star', 'Destaque', ['0' => 'Não', '1' => 'Sim'], null
                    , ['class' => 'jq-select2', 'data-rule-required' => true]) !!}

                @if (config('marticles.call', true))
                    {!! BootForm::text('call', 'Chamada', null, ['maxlength' => '150']) !!}
                @endif

                {!! BootForm::text('name', 'Nome', null, ['data-rule-required' => true, 'maxlength' => '150']) !!}

                {!! BootForm::textarea('description', 'Descrição', null, ['class' => 'jq-summernote', 'data-rule-required' => true, 'style' => 'height: 200px']) !!}

                @if (config('marticles.image', true))
                    {!! BootForm::file('image', 'Imagem ('.config("marticles.image.width", 640).' x '.config("marticles.image.height", 480).')', [
                            'data-allowed-file-extensions' => '["jpg", "png"]',
                            'data-initial-preview' => '["image->url('crop') . '\" class=\"file-preview-image\">"]',
                            'data-initial-caption' => $article->image->originalFilename(),
                            'data-min-image-width' => config('marticles.image.width', 640),
                            'data-min-image-height' => config('marticles.image.height', 480),
                            'data-aspect-ratio' => number_format(config('marticles.image.width', 640)/config('marticles.image.height', 480), 2)
                        ]) !!}
                @endif

                {!! BootForm::text('published_at', 'Data de publicação', ($article->published_at) ? $article->published_at->format('d/m/Y H:i') : null
                    , ['data-rule-required' => true, 'class' => 'jq-datetimepicker', 'maxlength' => '16']) !!}

                @include('mixdinternet/seo::partials.form', ['model' => isset($article) ? $article : null])

            @if (config('marticles.galleries', true))

                    {!! Gallery::form($article) !!}

            @endif

    {!! BootForm::close() !!}
@endsection


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/accessibility/select_to_speak/select_to_speak_menu_bubble_controller.h"

#include "ash/accessibility/accessibility_controller_impl.h"
#include "ash/accessibility/test_accessibility_controller_client.h"
#include "ash/public/cpp/accessibility_controller_enums.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/system/accessibility/floating_menu_button.h"
#include "ash/system/accessibility/select_to_speak/select_to_speak_menu_view.h"
#include "ash/test/ash_test_base.h"
#include "base/test/scoped_feature_list.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"

namespace ash {

class SelectToSpeakMenuBubbleControllerTest : public AshTestBase {
 public:
  SelectToSpeakMenuBubbleControllerTest() = default;
  ~SelectToSpeakMenuBubbleControllerTest() override = default;

  SelectToSpeakMenuBubbleControllerTest(
      const SelectToSpeakMenuBubbleControllerTest&) = delete;
  SelectToSpeakMenuBubbleControllerTest& operator=(
      const SelectToSpeakMenuBubbleControllerTest&) = delete;

  // AshTestBase:
  void SetUp() override {
    AshTestBase::SetUp();
    Shell::Get()->accessibility_controller()->select_to_speak().SetEnabled(
        true);
  }

  void TearDown() override { AshTestBase::TearDown(); }

  AccessibilityControllerImpl* GetAccessibilitController() {
    return Shell::Get()->accessibility_controller();
  }

  SelectToSpeakMenuBubbleController* GetBubbleController() {
    return GetAccessibilitController()
        ->GetSelectToSpeakMenuBubbleControllerForTest();
  }

  SelectToSpeakSpeedBubbleController* GetSpeedBubbleController() {
    return GetBubbleController()->speed_bubble_controller_.get();
  }

  views::Widget* GetBubbleWidget() {
    return GetBubbleController()->bubble_widget_;
  }

  SelectToSpeakMenuView* GetMenuView() {
    return GetBubbleController()->menu_view_;
  }

  FloatingMenuButton* GetMenuButton(SelectToSpeakMenuView::ButtonId view_id) {
    SelectToSpeakMenuView* menu_view = GetMenuView();
    if (!menu_view)
      return nullptr;
    return static_cast<FloatingMenuButton*>(
        menu_view->GetViewByID(static_cast<int>(view_id)));
  }

  void ShowSelectToSpeakPanel(bool is_paused) {
    gfx::Rect anchor_rect(10, 10, 0, 0);
    GetAccessibilitController()->ShowSelectToSpeakPanel(anchor_rect, is_paused,
                                                        /*speech_rate=*/1.2);
  }

 protected:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(SelectToSpeakMenuBubbleControllerTest, ShowSelectToSpeakPanel_paused) {
  ShowSelectToSpeakPanel(/*is_paused=*/true);
  EXPECT_TRUE(GetMenuView());

  FloatingMenuButton* pause_button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kPause);
  EXPECT_EQ(pause_button->GetTooltipText(),
            l10n_util::GetStringUTF16(IDS_ASH_SELECT_TO_SPEAK_RESUME));
  EXPECT_TRUE(GetBubbleWidget()->IsVisible());
}

TEST_F(SelectToSpeakMenuBubbleControllerTest,
       ShowSelectToSpeakPanel_notPaused) {
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  EXPECT_TRUE(GetMenuView());

  FloatingMenuButton* pause_button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kPause);
  EXPECT_EQ(pause_button->GetTooltipText(),
            l10n_util::GetStringUTF16(IDS_ASH_SELECT_TO_SPEAK_PAUSE));
  EXPECT_TRUE(GetBubbleWidget()->IsVisible());
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, HideSelectToSpeakPanel) {
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  GetAccessibilitController()->HideSelectToSpeakPanel();
  EXPECT_TRUE(GetMenuView());
  EXPECT_FALSE(GetBubbleWidget()->IsVisible());
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, PauseButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kPause);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kPause);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, ResumeButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/true);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kPause);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kResume);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, PrevParagraphButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kPrevParagraph);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kPreviousParagraph);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, PrevParagraphKeyPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_UP, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kPreviousParagraph);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, PrevSentenceButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kPrevSentence);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kPreviousSentence);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, PrevSentenceKeyPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_LEFT, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kPreviousSentence);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, PrevSentenceKeyPressedRtl) {
  base::i18n::SetICUDefaultLocale("he");
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_RIGHT, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kPreviousSentence);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, NextParagraphButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kNextParagraph);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kNextParagraph);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, NextParagraphKeyPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_DOWN, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kNextParagraph);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, NextSentenceButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kNextSentence);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kNextSentence);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, NextSentenceKeyPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_RIGHT, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kNextSentence);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, NextSentenceKeyPressedRtl) {
  base::i18n::SetICUDefaultLocale("he");
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_LEFT, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kNextSentence);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, StopButtonPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kStop);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kExit);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, StopKeyPressed) {
  TestAccessibilityControllerClient client;
  ShowSelectToSpeakPanel(/*is_paused=*/false);

  GetEventGenerator()->PressKey(ui::VKEY_ESCAPE, ui::EF_NONE);

  EXPECT_EQ(client.last_select_to_speak_panel_action(),
            SelectToSpeakPanelAction::kExit);
}

TEST_F(SelectToSpeakMenuBubbleControllerTest, ChangeSpeedButtonPressed) {
  ShowSelectToSpeakPanel(/*is_paused=*/false);
  FloatingMenuButton* button =
      GetMenuButton(SelectToSpeakMenuView::ButtonId::kSpeed);
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());

  EXPECT_TRUE(GetSpeedBubbleController() &&
              GetSpeedBubbleController()->IsVisible());

  // Clicking button again closes the speed selection bubble.
  GetEventGenerator()->GestureTapAt(button->GetBoundsInScreen().CenterPoint());
  EXPECT_TRUE(!GetSpeedBubbleController() ||
              !GetSpeedBubbleController()->IsVisible());
}

}  // namespace ash


text:
package net.devh.boot.grpc.test.setup;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.test.config.BaseAutoConfiguration;
import net.devh.boot.grpc.test.config.ServiceConfiguration;

/**
 * A test checking that the server and client can start and connect to each other with minimal config.
 *
 * @author Daniel Theuke (daniel.theuke@heuboe.de)
 */
@Slf4j
@SpringBootTest(properties = {
        "grpc.server.security.enabled=true",
        "grpc.server.security.keyStore=file:src/test/resources/certificates/server.jks",
        "grpc.server.security.trustStore=file:src/test/resources/certificates/trusted-clients.jks",
        "grpc.server.security.clientAuth=REQUIRE",

        "grpc.client.test.address=localhost:9090",
        "grpc.client.test.security.authorityOverride=localhost",
        "grpc.client.test.security.trustStore=file:src/test/resources/certificates/trusted-servers.jks",
        "grpc.client.test.security.clientAuthEnabled=true",
        "grpc.client.test.security.keyStore=file:src/test/resources/certificates/client1.jks",
})
@SpringJUnitConfig(classes = {ServiceConfiguration.class, BaseAutoConfiguration.class})
@DirtiesContext
public class SelfSignedMutualJksKeystoreSetupTest extends AbstractSimpleServerClientTest {

    public SelfSignedMutualJksKeystoreSetupTest() {
        log.info("--- SelfSignedMutualJksKeystoreSetupTest ---");
    }

}


text:
"use strict";
/**
 * Class for working with cookie
 */
export default class Cookie {

  public static regValidKey = new RegExp("([a-zA-Z0-9_-]{1,})", "i");

  /**
   * The method returns the flag whether supported this storage type or not
   * @returns {boolean}
   */
  public static isSupported(): boolean {
    return (
        typeof document === "object" &&
        typeof document.cookie === "string"
    );
  }

  /**
   * The method sets the value and returns true if it has been set
   * @param checkSupport {boolean}
   * @param key {string}
   * @param value {string}
   * @param expires {number}
   * @param path {string}
   * @param domain {string}
   * @param secure {boolean}
   * @return {boolean}
   */
  public static setItem(checkSupport: boolean = true,
                        key: string,
                        value: string,
                        expires: number = 30,
                        path: string = "/",
                        domain: string = location.hostname,
                        secure: boolean = (location.protocol === "https:")): boolean {
    try {
      /**
       * Validate input data
       */
      if (
          typeof checkSupport === "boolean" &&
          (
              typeof key === "string" &&
              Cookie.regValidKey.test(key)
          ) &&
          (
              typeof value === "string" &&
              (value === "" || Cookie.regValidKey.test(value))
          ) &&
          (
              typeof expires === "number" &&
              expires < 365
          ) &&
          typeof path === "string" &&
          (
              typeof domain === "string" &&
              domain.indexOf(location.hostname) !== -1
          ) &&
          (
              typeof secure === "boolean" &&
              secure === (location.protocol === "https:")
          )
      ) {
        /**
         * Validate input data
         */
        const a: any = document.createElement("a");
        a.href = "http://" + domain + path;
        if (
            a.hostname === domain ||
            a.path === path
        ) {
          /**
           * If that store is supported
           */
          if (!checkSupport || Cookie.isSupported()) {
            /**
             * Save cookies for 30 days
             * @type {Date}
             */
            const date: Date = new Date();
            date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
            const exp: string = date.toUTCString();
            /**
             * Encode value for store
             * @type {string}
             */
            value = encodeURIComponent(value);
            /**
             * Writing value to the document cookie storage
             * @type {string}
             */
            document.cookie = (
                key + "=" +
                value +
                ((exp) ? "; expires=" + exp : "") +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "")
            );
            /**
             * If all ok return true
             */
            return this.getItem(checkSupport, key) === decodeURIComponent(value);
          } else {
            /**
             * If cookie does not supported return false
             */
            return false;
          }
        } else {
          /**
           * If input data is not valid
           */
          return false;
        }
      } else {
        /**
         * If input data is not valid
         */
        return false;
      }
    } catch (e) {
      /**
       * If something goes wrong return false
       */
      return false;
    }
  }

  /**
   * The method reads the value and returns it or returns false if the value does not exist
   * @param checkSupport {boolean}
   * @param key {string}
   * @returns {string|boolean}
   */
  public static getItem(checkSupport: boolean = true,
                        key: string): string|boolean {
    try {
      /**
       * Validate input data
       */
      if (
          typeof checkSupport === "boolean" &&
          (
              typeof key === "string" &&
              Cookie.regValidKey.test(key)
          )
      ) {
        /**
         * If that store is supported
         */
        if (!checkSupport || Cookie.isSupported()) {
          /**
           * Get the array from document cookie split by ;
           * @type {string[]}
           */
          const arrCookie: string[] = document.cookie.split(";");
          /**
           * Iterate through the cookies
           */
          for (let j = 0; j < arrCookie.length; j++) {
            const i = arrCookie[j];
            /**
             * Trim and split each cookie by = for key value pare
             * @type {string[]}
             */
            const v: string[] = i.trim().split("=", 2);
            /**
             * If it is correct cookie key return the value
             */
            if (v[0] === key) {
              /**
               * If the value was found return the value
               */
              return decodeURIComponent(v[1]);
            }
          }
          /**
           * If the value was not found return false
           */
          return false;
        } else {
          /**
           * If cookie does not supported return false
           */
          return false;
        }
      } else {
        /**
         * If input data is not valid
         */
        return false;
      }
    } catch (e) {
      /**
       * If something goes wrong return false
       */
      return false;
    }
  }

  /**
   * The method removes the value and return true if the value does not exist
   * @param checkSupport {boolean}
   * @param key {string}
   * @returns {boolean}
   */
  public static removeItem(checkSupport: boolean = true,
                           key: string): boolean {
    try {
      /**
       * Validate input data
       */
      if (
          typeof checkSupport === "boolean" &&
          (
              typeof key === "string" &&
              Cookie.regValidKey.test(key)
          )
      ) {
        /**
         * If that store is supported
         */
        if (!checkSupport || Cookie.isSupported()) {
          /**
           * Set empty overdue value by key
           */
          Cookie.setItem(checkSupport, key, "", -1 * 24 * 60 * 60);
          /**
           * If all ok return true
           */
          return (Cookie.getItem(checkSupport, key) === false);
        } else {
          /**
           * If cookie does not supported return false
           */
          return false;
        }
      } else {
        /**
         * If input data is not valid
         */
        return false;
      }
    } catch (e) {
      /**
       * If something goes wrong return false
       */
      return false;
    }
  }

  /**
   * The method returns the array of string of available keys
   * @param checkSupport {boolean}
   * @returns {string[]}
   */
  public static getKeys(checkSupport: boolean = true): string[] {
    try {
      /**
       * Validate input data
       */
      if (
          typeof checkSupport === "boolean"
      ) {
        /**
         * If that store is supported
         */
        if (!checkSupport || Cookie.isSupported()) {
          /**
           * The array of available keys
           * @type {Array}
           */
          const arrKeys: string[] = [];
          /**
           * Get the array from document cookie split by ;
           * @type {string[]}
           */
          const arrCookie: string[] = document.cookie.split(";");
          /**
           * Iterate through the cookies
           */
          for (let j = 0; j < arrCookie.length; j++) {
            const i = arrCookie[j];
            /**
             * Trim and split each cookie by = for key value pare
             * @type {string[]}
             */
            const v: string[] = i.trim().split("=", 2);
            /**
             * Add key to the list
             */
            if (v[0]) {
              arrKeys.push(v[0]);
            }
          }
          return arrKeys;
        } else {
          /**
           * If cookie does not supported return false
           */
          return [];
        }
      } else {
        /**
         * If input data is not valid
         */
        return [];
      }
    } catch (e) {
      /**
       * If something goes wrong return false
       */
      return [];
    }
  }

  /**
   * The method cleans the storage and return true if it is empty
   * @param checkSupport {boolean}
   * @returns {boolean}
   */
  public static clear(checkSupport: boolean = true): boolean {
    try {
      /**
       * Validate input data
       */
      if (
          typeof checkSupport === "boolean"
      ) {
        /**
         * If that store is supported
         */
        if (!checkSupport || Cookie.isSupported()) {

          const arrKeys = Cookie.getKeys(checkSupport);

          if (arrKeys) {

            for (let j = 0; j < arrKeys.length; j++) {
              const i = arrKeys[j];

              Cookie.removeItem(checkSupport, i);
            }
          }
          /**
           * If all ok return true
           */
          return (Cookie.getKeys(checkSupport).length === 0);
        } else {
          /**
           * If cookie does not supported return false
           */
          return true;
        }
      } else {
        /**
         * If input data is not valid
         */
        return false;
      }
    } catch (e) {
      /**
       * If something goes wrong return false
       */
      return false;
    }
  }
}


text:
<?php

namespace Bookboon\Api\Client;

use PHPUnit\Framework\TestCase;

/**
 * Class HeadersTest
 * @package Client
 * @group client
 * @group header
 */
class HeadersTest extends TestCase
{
    public function testInvalidXFFIP() : void
    {
        $_SERVER['REMOTE_ADDR'] = '127.';
        $headers = new Headers();
        self::assertEmpty($headers->get(Headers::HEADER_XFF));
    }

    public function testValidXFFIP() : void
    {
        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
        $headers = new Headers();
        self::assertEquals('127.0.0.1', $headers->get(Headers::HEADER_XFF));
    }

    public function testOverrideXFF() : void
    {
        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
        $headers = new Headers();
        $headers->set(Headers::HEADER_XFF, 'TEST');
        self::assertEquals('TEST', $headers->get(Headers::HEADER_XFF));
    }
}


text:
<?php

namespace Symfony\Component\Mailer\Transport;

use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Exception\UnsupportedSchemeException;
use Symfony\Component\Mailer\Transport\Smtp\SmtpTransport;
use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;

/**
 * Factory that configures a transport (sendmail or SMTP) based on php.ini settings.
 *
 * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
 */
final class NativeTransportFactory extends AbstractTransportFactory
{
    public function create(Dsn $dsn): TransportInterface
    {
        if (!\in_array($dsn->getScheme(), $this->getSupportedSchemes(), true)) {
            throw new UnsupportedSchemeException($dsn, 'native', $this->getSupportedSchemes());
        }

        if ($sendMailPath = ini_get('sendmail_path')) {
            return new SendmailTransport($sendMailPath, $this->dispatcher, $this->logger);
        }

        if ('\\' !== \DIRECTORY_SEPARATOR) {
            throw new TransportException('sendmail_path is not configured in php.ini.');
        }

        // Only for windows hosts; at this point non-windows
        // host have already thrown an exception or returned a transport
        $host = ini_get('smtp');
        $port = (int) ini_get('smtp_port');

        if (!$host || !$port) {
            throw new TransportException('smtp or smtp_port is not configured in php.ini.');
        }

        $socketStream = new SocketStream();
        $socketStream->setHost($host);
        $socketStream->setPort($port);
        if (465 !== $port) {
            $socketStream->disableTls();
        }

        return new SmtpTransport($socketStream, $this->dispatcher, $this->logger);
    }

    protected function getSupportedSchemes(): array
    {
        return ['native'];
    }
}


text:
<?php
namespace Reivaj86\ChefAuth\Contracts;

interface ChefAuthContract
{
    /**
     * Check if the recipe has an ingredient or ingredients.
     *
     * @param int|string|array $ingredient
     * @param string $methodName
     * @return bool
     * @throws \Reivaj86\ChefAuth\Exceptions\InvalidArgumentException
     */
    public function cooks($ingredient, $methodName = 'One');

    /**
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public function __callChef($method, $parameters);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">PodPlayer</string>
    <string name="albums">专辑</string>
    <string name="artists">艺术家</string>
    <string name="songs">歌曲</string>
    <string name="cover_flow">Cover Flow</string>
    <string name="playlists">播放列表</string>
    <string name="genres">流派</string>
    <string name="settings">设置</string>
    <string name="now_playing">正在播放</string>
    <string name="shuffle_songs">随机全部</string>
    <string name="brought_you_by">来自</string>
    <string name="about">关于</string>
    <string name="connect">连接手环</string>
    <string name="debug">调试器</string>
    <string name="shuffle">随机</string>
    <string name="repeat">重复</string>
    <string name="get_source_code">获取源代码</string>
    <string name="contact_us">联系我们</string>
    <string name="nothing_to_play">现在没有歌曲可播放</string>
    <string name="repeat_all">重复全部</string>
    <string name="repeat_none">不重复</string>
    <string name="repeat_one">单曲循环</string>
    <string name="str_true">是</string>
    <string name="str_false">否</string>
    <string name="empty">空的!</string>
    <string name="finger_spinning_on_wheel_will_control_the_screen">转动滚轮来控制屏幕上的内容</string>
    <string name="tap_on_middle_button_to_select">点击中间的按钮来选择</string>
    <string name="connect_miband_get_control_by_your_body">使用小米手环来控制你的播放器</string>
    <string name="music_player_which_looks_feels_like_a_real_device">一个APP看起来用起来都像真的播放器</string>
    <string name="about_prodigal">关于 Prodigal</string>
    <string name="brought_you_by_bob_sun">由Bob Sun为你带来</string>
    <string name="if_you_like_this_app">如果你喜欢这个APP, 请在GitHub上给我一颗星星</string>
    <string name="credits">鸣谢</string>
    <string name="icons_by">图标来自</string>
    <string name="send_mail_using">给我发邮件</string>
    <string name="nobody">无</string>
    <string name="nothing">无</string>
    <string name="contact_me_at">给我发邮件</string>
    <string name="connect_band">连接手环</string>
    <string name="search_band">搜索手环</string>
    <string name="start_scan">扫描手环</string>
    <string name="stop_scan">停止手环</string>

    <string name="debug_tools">调试工具</string>
    <string name="avg_steps">设置平均步数</string>
    <string name="is_sleep">是否睡眠</string>
</resources>


text:
<!DOCTYPE html>

<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./../public/dashboard/activities.css">
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./../public/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" href="./../public/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.css">

添加活动

管理活动

活动名称

				<input type="text" id="name" name="name" class="txt" placeholder="中英文或下划线">

开始时间

				<input class="txt time" id="startTime" placeholder="请选择时间">

结束时间

				<input class="txt time" id="endTime" placeholder="请选择时间">

限制人数

				<input type="text" id="limit" name="limit" value="0" class="txt">

只能为数字,0表示不限制

PS:默认会保存学生的所有信息

字段

						<input type="text" class="txt" id="parameters" placeholder="字段的名称,不可放空">

删除

						<input type="text" class="txt" id="value" placeholder="默认值,可放空">

			<button class="addParam">添加字段</button>

				<button id="submit" disabled="disabled">发布活动</button>

			发送模板

活动名称

<input id="actName" type="text">

活动时间

<input id="actTime" type="text" placeholder="活动举办时间">

活动地点

<input id="actSpace" type="text" placeholder="活动举办地点">

备注

<input id="remark" type="text" placeholder="模板消息推送中的备注">

选中学生

<textarea id="student" type="text" placeholder="选中的学生的学号,多个学生用英文的逗号分隔开,如:2014150001,2014150002(全部选中请填写为英文小写的all)"></textarea>

				<input type="hidden" id="actId">

<button class="submitReply">发送</button>取消

			链接


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TrackRoamer.Robotics.LibMapping
{
    /// <summary>
    /// MapVicinity tries to be just a W x H collection of "Relative" cells and a grid of "Geo" cells.
    /// It is not aware of coordinates or distances, direction or detected objects.
    /// MapCells may keep track of objects and have enough intelligence to compute obstacle weight.
    /// </summary>
    public class MapVicinity
    {
        private readonly int nrW;   // "Relative" grid dimensions
        private readonly int nrH;

        private readonly int ngW;   // "Geo" grid dimensions
        private readonly int ngH;

        private MapCell[,] relCells;
        private MapCell[,] geoCells;

        public MapVicinity()
        {
            // we might need this because in Designer the view does not seem to see App.config in MapperSettings properly:
            nrW = MapperSettings.nW < 10 ? 10 : MapperSettings.nW;
            nrH = MapperSettings.nH < 10 ? 10 : MapperSettings.nH;

            relCells = new MapCell[nrH, nrW];

            ngW = MapperSettings.nW < 10 ? 10 : MapperSettings.nW;
            ngH = MapperSettings.nH < 10 ? 10 : MapperSettings.nH;

            geoCells = new MapCell[ngH, ngW];
        }

        public int RelMapWidth { get { return relCells.GetLength(1); } }
        public int RelMapHeight { get { return relCells.GetLength(0); } }

        public int GeoMapWidth { get { return geoCells.GetLength(1); } }
        public int GeoMapHeight { get { return geoCells.GetLength(0); } }

        public MapCell relCellAt(int cellXindex, int cellYindex)
        {
            if (cellXindex < 0 || cellYindex < 0 || cellXindex >= nrW || cellYindex >= nrH)
            {
                return null;
            }

            return relCells[cellYindex, cellXindex];
        }

        public MapCell geoCellAt(int cellXindex, int cellYindex)
        {
            if (cellXindex < 0 || cellYindex < 0 || cellXindex >= ngW || cellYindex >= ngH)
            {
                return null;
            }

            return geoCells[cellYindex, cellXindex];
        }

        public void ClearRelCells()
        {
            foreach (MapCell cell in relCells)
            {
                cell.Clear();
                cell.colors.Clear();
            }
        }

        public void ClearGeoCells()
        {
            foreach (MapCell cell in geoCells)
            {
                cell.Clear();
                cell.colors.Clear();
            }
        }

        /// <summary>
        /// one-time initialization routine
        /// </summary>
        public void init()
        {
            Random random = new Random();

            for (int i = 0; i < nrH; i++)
            {
                for (int j = 0; j < nrW; j++)
                {
                    relCells[i, j] = new MapCell() { val = random.Next(2), x = j, y = i };
                }
            }

            for (int i = 0; i < ngH; i++)
            {
                for (int j = 0; j < ngW; j++)
                {
                    geoCells[i, j] = new MapCell() { val = random.Next(2), x = j, y = i };
                }
            }
        }

        /// <summary>
        /// a lean version of init(), can be called repeatedly. Does not empty the cells.
        /// </summary>
        public void ensureNonEmpty()
        {
            for (int i = 0; i < nrH; i++)
            {
                for (int j = 0; j < nrW; j++)
                {
                    if (relCells[i, j] == null)
                    {
                        relCells[i, j] = new MapCell() { val = 0, x = j, y = i };
                    }
                }
            }

            for (int i = 0; i < ngH; i++)
            {
                for (int j = 0; j < ngW; j++)
                {
                    if (geoCells[i, j] == null)
                    {
                        geoCells[i, j] = new MapCell() { val = 0, x = j, y = i };
                    }
                }
            }
        }
    }
}


text:
// Package httpauth implements cookie/session based authentication and
// authorization. Intended for use with the net/http or github.com/gorilla/mux
// packages, but may work with github.com/codegangsta/martini as well.
// Credentials are stored as a username + password hash, computed with bcrypt.
//
// Three user storage systems are currently implemented: file based
// (encoding/gob), sql databases (database/sql), and MongoDB databases.
//
// Access can be restricted by a users' role. A higher role will give more
// access.
//
// Users can be redirected to the page that triggered an authentication error.
//
// Messages describing the reason a user could not authenticate are saved in a
// cookie, and can be accessed with the Messages function.
//
// Example source can be found at
// https://github.com/apexskier/httpauth/blob/master/examples/server.go
package httpauth

import (
	"errors"
	"net/http"

	"github.com/gorilla/sessions"
	"golang.org/x/crypto/bcrypt"
)

// ErrDeleteNull is returned by DeleteUser when that user didn't exist at the
// time of call.
// ErrMissingUser is returned by Users when a user is not found.
var (
	ErrDeleteNull  = mkerror("deleting non-existant user")
	ErrMissingUser = mkerror("can't find user")
)

// Role represents an interal role. Roles are essentially a string mapped to an
// integer. Roles must be greater than zero.
type Role int

// UserData represents a single user. It contains the users username, email,
// and role as well as a hash of their password. When creating
// users, you should not specify a hash; it will be generated in the Register
// and Update functions.
type UserData struct {
	Username string `bson:"Username"`
	Email    string `bson:"Email"`
	Hash     []byte `bson:"Hash"`
	Role     string `bson:"Role"`
}

// Authorizer structures contain the store of user session cookies a reference
// to a backend storage system.
type Authorizer struct {
	cookiejar   *sessions.CookieStore
	backend     AuthBackend
	defaultRole string
	roles       map[string]Role
}

// The AuthBackend interface defines a set of methods an AuthBackend must
// implement.
type AuthBackend interface {
	SaveUser(u UserData) error
	User(username string) (user UserData, e error)
	Users() (users []UserData, e error)
	DeleteUser(username string) error
	Close()
}

// Helper function to add a user directed message to a message queue.
func (a Authorizer) addMessage(rw http.ResponseWriter, req *http.Request, message string) {
	messageSession, _ := a.cookiejar.Get(req, "messages")
	defer messageSession.Save(req, rw)
	messageSession.AddFlash(message)
}

// Helper function to save a redirect to the page a user tried to visit before
// logging in.
func (a Authorizer) goBack(rw http.ResponseWriter, req *http.Request) {
	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	defer redirectSession.Save(req, rw)
	redirectSession.Flashes()
	redirectSession.AddFlash(req.URL.Path)
}

func mkerror(msg string) error {
	return errors.New("httpauth: " + msg)
}

// NewAuthorizer returns a new Authorizer given an AuthBackend, a cookie store
// key, a default user role, and a map of roles. If the key changes, logged in
// users will need to reauthenticate.
//
// Roles are a map of string to httpauth.Role values (integers). Higher Role values
// have more access.
//
// Example roles:
//
//     var roles map[string]httpauth.Role
//     roles["user"] = 2
//     roles["admin"] = 4
//     roles["moderator"] = 3
func NewAuthorizer(backend AuthBackend, key []byte, defaultRole string, roles map[string]Role) (Authorizer, error) {
	var a Authorizer
	a.cookiejar = sessions.NewCookieStore([]byte(key))
	a.backend = backend
	a.roles = roles
	a.defaultRole = defaultRole
	if _, ok := roles[defaultRole]; !ok {
		return a, mkerror("httpauth: defaultRole missing")
	}
	return a, nil
}

// Login logs a user in. They will be redirected to dest or to the last
// location an authorization redirect was triggered (if found) on success. A
// message will be added to the session on failure with the reason.
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
	session, _ := a.cookiejar.Get(req, "auth")
	if session.Values["username"] != nil {
		return mkerror("already authenticated")
	}
	if user, err := a.backend.User(u); err == nil {
		verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))
		if verify != nil {
			a.addMessage(rw, req, "Invalid username or password.")
			return mkerror("password doesn't match")
		}
	} else {
		a.addMessage(rw, req, "Invalid username or password.")
		return mkerror("user not found")
	}
	session.Values["username"] = u
	session.Save(req, rw)

	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	if flashes := redirectSession.Flashes(); len(flashes) > 0 {
		dest = flashes[0].(string)
	}
	http.Redirect(rw, req, dest, http.StatusSeeOther)
	return nil
}

// Register and save a new user. Returns an error and adds a message if the
// username is in use.
//
// Pass in a instance of UserData with at least a username and email specified. If no role
// is given, the default one is used.
func (a Authorizer) Register(rw http.ResponseWriter, req *http.Request, user UserData, password string) error {
	if user.Username == "" {
		return mkerror("no username given")
	}
	if user.Email == "" {
		return mkerror("no email given")
	}
	if user.Hash != nil {
		return mkerror("hash will be overwritten")
	}
	if password == "" {
		return mkerror("no password given")
	}

	// Validate username
	_, err := a.backend.User(user.Username)
	if err == nil {
		a.addMessage(rw, req, "Username has been taken.")
		return mkerror("user already exists")
	} else if err != ErrMissingUser {
		if err != nil {
			return mkerror(err.Error())
		}
		return nil
	}

	// Generate and save hash
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return mkerror("couldn't save password: " + err.Error())
	}
	user.Hash = hash

	// Validate role
	if user.Role == "" {
		user.Role = a.defaultRole
	} else {
		if _, ok := a.roles[user.Role]; !ok {
			return mkerror("non-existant role")
		}
	}

	err = a.backend.SaveUser(user)
	if err != nil {
		a.addMessage(rw, req, err.Error())
		return mkerror(err.Error())
	}
	return nil
}

// Update changes data for an existing user. Needs thought...
func (a Authorizer) Update(rw http.ResponseWriter, req *http.Request, p string, e string) error {
	var (
		hash  []byte
		email string
	)
	authSession, err := a.cookiejar.Get(req, "auth")
	username, ok := authSession.Values["username"].(string)
	if !ok {
		return mkerror("not logged in")
	}
	user, err := a.backend.User(username)
	if err == ErrMissingUser {
		a.addMessage(rw, req, "User doesn't exist.")
		return mkerror("user doesn't exists")
	} else if err != nil {
		return mkerror(err.Error())
	}
	if p != "" {
		hash, err = bcrypt.GenerateFromPassword([]byte(p), bcrypt.DefaultCost)
		if err != nil {
			return mkerror("couldn't save password: " + err.Error())
		}
	} else {
		hash = user.Hash
	}
	if e != "" {
		email = e
	} else {
		email = user.Email
	}

	newuser := UserData{username, email, hash, user.Role}

	err = a.backend.SaveUser(newuser)
	if err != nil {
		a.addMessage(rw, req, err.Error())
	}
	return nil
}

// Authorize checks if a user is logged in and returns an error on failed
// authentication. If redirectWithMessage is set, the page being authorized
// will be saved and a "Login to do that." message will be saved to the
// messages list. The next time the user logs in, they will be redirected back
// to the saved page.
func (a Authorizer) Authorize(rw http.ResponseWriter, req *http.Request, redirectWithMessage bool) error {
	authSession, err := a.cookiejar.Get(req, "auth")
	if err != nil {
		if redirectWithMessage {
			a.goBack(rw, req)
		}
		return mkerror("new authorization session")
	}
	/*if authSession.IsNew {
	    if redirectWithMessage {
	        a.goBack(rw, req)
	        a.addMessage(rw, req, "Log in to do that.")
	    }
	    return mkerror("no session existed")
	}*/
	username := authSession.Values["username"]
	if !authSession.IsNew && username != nil {
		_, err := a.backend.User(username.(string))
		if err == ErrMissingUser {
			authSession.Options.MaxAge = -1 // kill the cookie
			authSession.Save(req, rw)
			if redirectWithMessage {
				a.goBack(rw, req)
				a.addMessage(rw, req, "Log in to do that.")
			}
			return mkerror("user not found")
		} else if err != nil {
			return mkerror(err.Error())
		}
	}
	if username == nil {
		if redirectWithMessage {
			a.goBack(rw, req)
			a.addMessage(rw, req, "Log in to do that.")
		}
		return mkerror("user not logged in")
	}
	return nil
}

// AuthorizeRole runs Authorize on a user, then makes sure their role is at
// least as high as the specified one, failing if not.
func (a Authorizer) AuthorizeRole(rw http.ResponseWriter, req *http.Request, role string, redirectWithMessage bool) error {
	r, ok := a.roles[role]
	if !ok {
		return mkerror("role not found")
	}
	if err := a.Authorize(rw, req, redirectWithMessage); err != nil {
		return mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth") // should I check err? I've already checked in call to Authorize
	username := authSession.Values["username"]
	if user, err := a.backend.User(username.(string)); err == nil {
		if a.roles[user.Role] >= r {
			return nil
		}
		a.addMessage(rw, req, "You don't have sufficient privileges.")
		return mkerror("user doesn't have high enough role")
	}
	return mkerror("user not found")
}

// CurrentUser returns the currently logged in user and a boolean validating
// the information.
func (a Authorizer) CurrentUser(rw http.ResponseWriter, req *http.Request) (user UserData, e error) {
	if err := a.Authorize(rw, req, false); err != nil {
		return user, mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth")

	username, ok := authSession.Values["username"].(string)
	if !ok {
		return user, mkerror("User not found in authsession")
	}
	return a.backend.User(username)
}

// Logout clears an authentication session and add a logged out message.
func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {
	session, _ := a.cookiejar.Get(req, "auth")
	defer session.Save(req, rw)

	session.Options.MaxAge = -1 // kill the cookie
	a.addMessage(rw, req, "Logged out.")
	return nil
}

// DeleteUser removes a user from the Authorize. ErrMissingUser is returned if
// the user to be deleted isn't found.
func (a Authorizer) DeleteUser(username string) error {
	err := a.backend.DeleteUser(username)
	if err != nil && err != ErrDeleteNull {
		return mkerror(err.Error())
	}
	return err
}

// Messages fetches a list of saved messages. Use this to get a nice message to print to
// the user on a login page or registration page in case something happened
// (username taken, invalid credentials, successful logout, etc).
func (a Authorizer) Messages(rw http.ResponseWriter, req *http.Request) []string {
	session, _ := a.cookiejar.Get(req, "messages")
	flashes := session.Flashes()
	session.Save(req, rw)
	var messages []string
	for _, val := range flashes {
		messages = append(messages, val.(string))
	}
	return messages
}


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\jui\DatePicker;
use yii\helpers\Url;
use yii\data\ActiveDataProvider;
use yii\grid\GridView;
use app\modules\business\models\CustomerDetails;
use app\modules\business\models\BalanceSheet;
use app\modules\business\models\Transactions;

$this->title = "Generate Bill";
$this->params['breadcrumbs'][] = ['label' => 'Bills', 'url'=>['/index']];
$this->params['breadcrumbs'][] = ['label' => $this->title];

?>

  <div class="<?php echo $model->isNewRecord ? 'box-success' : 'box-info'; ?> box col-xs-12 col-lg-12 no-padding">

<?=CustomerDetails::$customerType[$model->customer_type]?> Payment Details

	<col class="col-sm-2">
  	<col class="col-sm-2">
	<col class="col-sm-8">
	<?php
            $imgData= Yii::getAlias('@web')."/data/stu_images/no-photo.png";
            $displayImg = Html::img($imgData, ['alt'=>'No Image', 'class'=>'img-circle edusec-img-disp']); ?>

		<?= $displayImg ?>

		<?php echo $model->getAttributeLabel('name'); ?>
		<?php echo $model->name; ?>

		<?php echo $model->getAttributeLabel('place'); ?>
		<?php echo $model->place; ?>

		<?php echo $model->getAttributeLabel('address'); ?>
		<?php echo $model->address; ?>

		<?php echo $model->getAttributeLabel('account_details'); ?>
		<?php echo $model->account_details; ?>

		<?php echo $model->getAttributeLabel('phone'); ?>
		<?php echo $model->phone; ?>

<div class="<?php echo $model->isNewRecord ? 'box-success' : 'box-info'; ?> box col-xs-12 col-lg-12 no-padding">

 Generate Bill :

<?php
	$form = ActiveForm::begin([
			'id'=>'fees-collect-form',
			'errorSummaryCssClass' => 'error-summary text-red',
			'fieldConfig' => [
			    'template' => "{label}{input}{error}",
			]]);

$closed_bill=Transactions::find()->where(['status'=>'closed','customer_id'=>$model->id])->orderBy(['id'=> SORT_DESC])->one();
$previous_balance = isset($closed_bill->balance)?$closed_bill->balance:0;
$totalAmount = $totalPay = $advance_total = $return_total=0;
$feesDetails = BalanceSheet::find()->with(['materials','trip'])->where(['status' => 'open',
'customer_id'=>$model->id])->all();
	echo '
';
	echo '<col class="col-xs-1">';
  	echo '<col class="col-xs-9">';
	echo '<col class="col-xs-2">';
	echo '
';
	echo 'SI No.	';
	echo 'Product	';
	echo 'Date	';

	echo 'Amount	';
	echo '
';
	if($feesDetails){
	 $trip_id =Yii::$app->params['tripId'];
	foreach($feesDetails as $key=>$value) {
//                 print_r($value->trip->returns);
		echo '
';
		echo ''.($key+1).'	';
		if($value->trip_id==$trip_id){
                    echo 'Advance	';
                    echo ''.date("d-m-Y",strtotime($value['created_on'])).'	';
		}else{

		    $products = '';
		    if($value->trip->returns=="yes"){
                       $products .="Return : ";
                       }
		    $returnProducts='';
		    if($value->materials)
		    {
		     foreach($value->materials as $material)
		     {

		       $products .= $material->material->name.' - '.$material['unit_price'].' X '.$material['quantity'].' = '.$material['price'].', ';
		     }
		     $products = rtrim($products,', ');
		    }else $products = "Purchase";

                    echo ''.$products.'	';
                    echo ''.date("d-m-Y",strtotime($value['created_on'])).'	';
		}

		echo ''.abs($value['amount']).'	';
		echo '
';

		if($value['amount'] > 0)
		{
		$totalAmount+=$value['amount'];
                }else{
                    if($value->trip->returns=="yes"){
                        $return_total += $value['amount'];
                    }else{
                        $advance_total += $value['amount'];
                    }
		}

	}
	$grandTotal = $totalAmount+$previous_balance;
	$colspan=3;

	echo '
Total	'.$totalAmount.'
';
	}else{
            echo "
 No trip to show
";
	}
	$grandTotal = $totalAmount+$previous_balance;
	$colspan=3;

	echo '
Previous Balance	'.$previous_balance.'
';

	echo '
Grand Amount	'.$grandTotal.'
';

    if($advance_total>0)
    {
     echo '
Deducting Advance	'.abs($advance_total).'
';
     echo '
Effective Amount	'.($grandTotal=$grandTotal +
$advance_total).'
';
    }

     if($return_total)
    {
     echo '
Deducting Returns	'.abs($return_total).'
';
      echo '
Effective Amount	'.($grandTotal=$grandTotal +
$return_total).'
';
    }

$open_bill=Transactions::findOne(['status'=>'open','customer_id'=>$model->id]);
 //if(!isset($open_bill->balance) && $grandTotal>0){
        echo '
'. Html::submitButton(' Generate Bill', ['class' =>
'btn btn-primary' ]).'
';
//}

//
	echo '
';

?>
<?php ActiveForm::end() ?>


text:
package de.develman.mmi.algorithm;

import de.develman.mmi.exception.NegativeCycleException;
import de.develman.mmi.model.Edge;
import de.develman.mmi.model.Graph;
import de.develman.mmi.model.Vertex;
import de.develman.mmi.model.algorithm.ShortestPath;
import java.util.ArrayList;
import java.util.List;

/**
 * Die Klasse MooreBellmanFord implementiert den Bellman–Ford–Moore-Algorithmus zur Berechnung des Kürzester-Wege-Baumes
 * in einem Digraph
 *
 * @author Georg Henkel <georg@develman.de>
 */
public class MooreBellmanFord extends AbstractShortestPath
{
    /**
     * Sucht nach einem negativen Zykel im Graphen
     *
     * @param graph Graph
     * @param startVertex Startknoten
     * @return Negativer Zykel oder null, wenn keiner gefunden wurde
     */
    public List<Edge> findNegativeCycle(Graph graph, Vertex startVertex)
    {
        init(graph, startVertex);
        calculateDistances(graph);

        distance.keySet().forEach(v ->
        {
            if (distance.get(v) < Double.POSITIVE_INFINITY)
            {
                v.setVisited(true);
            }
        });

        for (Edge e : graph.getEdges())
        {
            if (checkForCycle(e))
            {
                List<Edge> cycle = loadCycle(e, graph.countVertices());
                return cycle;
            }
        }

        return null;
    }

    /**
     * Berechnung des Kürzester-Wege-Baumes
     *
     * @param graph Digraph mit positiven Kantengewichten
     * @param startVertex Startknoten
     * @param endVertex Zielknoten
     * @throws NegativeCycleException
     * @return Liste der Kanten des Kürzester-Wege-Baum
     */
    public ShortestPath findShortestPath(Graph graph, Vertex startVertex, Vertex endVertex) throws NegativeCycleException
    {
        init(graph, startVertex);
        calculateDistances(graph);

        for (Edge e : graph.getEdges())
        {
            if (checkForCycle(e))
            {
                throw new NegativeCycleException();
            }
        }

        return loadShortestPath(startVertex, endVertex);
    }

    private void calculateDistances(Graph graph)
    {
        int count = 0;
        while (count < graph.countVertices() - 1)
        {
            graph.getEdges().forEach(e -> updateCost(e));
            count++;
        }
    }

    private boolean checkForCycle(Edge e)
    {
        boolean hasCycle = false;

        Vertex source = e.getSource();
        Vertex sink = e.getSink();

        double newDistance = distance.get(source) + e.getCost();
        if (newDistance < distance.get(sink))
        {
            hasCycle = true;
        }

        return hasCycle;
    }

    private List<Edge> loadCycle(Edge e, int countVertices)
    {
        Vertex start = e.getSource();
        for (int i = 0; i < countVertices; i++)
        {
            start = predecessor.get(start);
        }

        return extractCycle(start);
    }

    private List<Edge> extractCycle(Vertex start)
    {
        List<Edge> cycle = new ArrayList<>();

        Vertex pred;
        Vertex current = start;
        do
        {
            pred = predecessor.get(current);
            cycle.add(pred.getEdgeTo(current.getKey()));

            if (pred == start)
            {
                break;
            }

            current = pred;
        }
        while (true);

        return cycle;
    }
}


text:
import $ from 'jquery';
import _ from 'lodash';

export default class {
  constructor(callback) {
    this._actions = ['click'];

    this._callback = callback;

    this._bindFns();
    this._bindEvents();
  }

  _bindFns() {
    _.bindAll(this, [
      '_onAction'
    ]);
  }

  _bindEvents() {
    $(document.body).on(this._actions.join(' '), '[data-track-actions]', this._onAction);
  }

  cleanup() {

  }

  // Events
  _onAction(e) {
    var $node = $(e.target);
    var nodeActions = $node.data('trackActions');
    nodeActions = '[' + nodeActions + ']';
    nodeActions = JSON.parse(nodeActions);

    if(_.indexOf(nodeActions, e.type) === -1) {
      // Do not track
      return;
    }

    var dataPrefix = 'track' + _.capitalize(e.type);

    var category = $node.data(dataPrefix + 'Category'),
      action = $node.data(dataPrefix + 'Action'),
      label = $node.data(dataPrefix + 'Label');

    this._callback({
      category: category,
      action: action,
      label: label
    });
  }
};


text:
import threading

from utils import list_contains

class TagCache:
    def __init__(self):
        self.data = []
        self.threadLock = threading.Lock()

    def append(self, tag):
        self.threadLock.acquire()
        self.data.append(tag)
        self.threadLock.release()

    def remove(self, tag):
        self.threadLock.acquire()
        self.data.remove(tag)
        self.threadLock.release()

    def hasTagByMac(self, mac):
        self.threadLock.acquire()
        result = list_contains(self.data, lambda t: t.mac == mac)
        self.threadLock.release()

        return result

    def findByMac(self, mac):
        result = None

        self.threadLock.acquire()
        for tag in self.data:
            if tag.mac == mac:
                result = tag
                break
        self.threadLock.release()

        return result

    def getData(self):
        return self.data[:]


text:
WorkingWithGitAPI
=================

Getting commits from one branch and verifying whether they were cherry-picked into the main branch


text:
'use strict';

import BaseMw from './base-mw';
import scss from 'koa-scss';

export default class ScssMw extends BaseMw {
  constructor(config) {
    super(config);
  }

  mount(config) {
    config = config || this.config;
    this.use(scss({
      src: this.config.stylesheets.scss.srcPath,
      dest: this.config.static.stylesheets.path,
      debug: true,
      force: true
    }));
    return this;
  }
}