text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TieredMenuDemo } from './tieredmenudemo';

@NgModule({
    imports: [RouterModule.forChild([{ path: '', component: TieredMenuDemo }])],
    exports: [RouterModule]
})
export class TieredMenuDemoRoutingModule {}


text:
package workbench.db.hsqldb;

import java.util.List;

import workbench.TestUtil;
import workbench.WbTestCase;

import workbench.db.ConnectionMgr;
import workbench.db.ConstraintReader;
import workbench.db.ReaderFactory;
import workbench.db.TableConstraint;
import workbench.db.TableDefinition;
import workbench.db.TableIdentifier;
import workbench.db.WbConnection;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 * @author Thomas Kellerer
 */
public class HsqlConstraintReaderTest
	extends WbTestCase
{

	public HsqlConstraintReaderTest()
	{
		super("HsqlConstraintReaderTest");
	}

	@BeforeClass
	public static void setUpClass()
		throws Exception
	{
	}

	@AfterClass
	public static void tearDownClass()
		throws Exception
	{
		ConnectionMgr.getInstance().disconnectAll();
	}

	@Test
	public void testReader()
		throws Exception
	{
		TestUtil util = getTestUtil();
		WbConnection conn = util.getHSQLConnection("constraintreader");
		TestUtil.executeScript(conn, "create table cons_test (id integer, nr integer, constraint min_value check (id > 42), check (nr < 100));");
		ConstraintReader reader = ReaderFactory.getConstraintReader(conn.getMetadata());
		assertTrue(reader instanceof HsqlConstraintReader);
		HsqlConstraintReader hsqlReader = (HsqlConstraintReader)reader;
		TableDefinition tbl = conn.getMetadata().getTableDefinition(new TableIdentifier("CONS_TEST"));
		List<TableConstraint> constraints = reader.getTableConstraints(conn, tbl);
		assertEquals(2, constraints.size());
		TableConstraint minValue = constraints.get(0);
		// HSQLDB 2.0 includes the table's schema
		assertEquals("(PUBLIC.CONS_TEST.ID>42)", minValue.getExpression());

		TableConstraint maxValue = constraints.get(1);
		assertEquals("(PUBLIC.CONS_TEST.NR<100)", maxValue.getExpression());
		assertTrue(hsqlReader.isSystemConstraintName(maxValue.getConstraintName()));
	}

}

redpajama_set_name: RedPajamaGithub


text:
package io.redlink.smarti.processor.ner;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.regex.Pattern;

/**
 * @author Thomas Kurz (thomas.kurz@redlink.co)
 * @since 26.07.17.
 */
public class UrlFactoryTest {

    @Test
    public void testRegexPattern() {
        Pattern p = new UrlFactory().getRegexes(null, null).get(0).getPattern();

        String url1 = "http://foo.com/blah_blah/";
        String url2 = "Ein beispiel: https://www.example.com/foo/?bar=baz&inga=42&quux";
        String wrong_url1 = "khttp://foo.bar?q=Spaces should be encoded";
        String wrong_url2 = "Das ist keine URL khttp://foo.bar?q=Spaces should be encoded";
        Assert.assertTrue(p.matcher(url1).find());
        Assert.assertTrue(p.matcher(url2).find());
        Assert.assertFalse(p.matcher(wrong_url1).find());
        Assert.assertFalse(p.matcher(wrong_url2).find());
    }

}


text:
package org.ovirt.engine.core.vdsbroker;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VdsStatistics;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.vdscommands.SetVdsStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VdsIdAndVdsVDSCommandParametersBase;
import org.ovirt.engine.core.compat.DateTime;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.compat.LogCompat;
import org.ovirt.engine.core.compat.LogFactoryCompat;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation;
import org.ovirt.engine.core.utils.timer.SchedulerUtil;
import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.irsbroker.IRSErrorException;
import org.ovirt.engine.core.vdsbroker.irsbroker.IrsBrokerCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.CollectVdsNetworkDataVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.GetCapabilitiesVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.IVdsServer;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSNetworkException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSRecoveringException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerConnector;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerWrapper;
import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcUtils;

public class VdsManager {
    private VDS _vds;

    protected VDS getVds() {
        return _vds;
    }

    protected void setVds(VDS value) {
        _vds = value;
    }

    public boolean getRefreshStatistics() {
        return (_refreshIteration == _numberRefreshesBeforeSave);
    }

    private static final int VDS_REFRESH_RATE = Config.<Integer> GetValue(ConfigValues.VdsRefreshRate) * 1000;

    private String onTimerJobId;

    private final int _numberRefreshesBeforeSave = Config.<Integer> GetValue(ConfigValues.NumberVmRefreshesBeforeSave);
    private int _refreshIteration = 1;

    private final Object _lockObj = new Object();
    private static Map<Guid, String> recoveringJobIdMap = new ConcurrentHashMap<Guid, String>();
    private boolean isSetNonOperationalExecuted;

    public Object getLockObj() {
        return _lockObj;
    }

    public static void cancelRecoveryJob(Guid vdsId) {
        String jobId = recoveringJobIdMap.remove(vdsId);
        if (jobId != null) {
            log.infoFormat("Cancelling the recovery from crash timer for VDS {0} because vds started initializing", vdsId);
            try {
                SchedulerUtilQuartzImpl.getInstance().deleteJob(jobId);
            } catch (Exception e) {
                log.warnFormat("Failed deleting job {0} at cancelRecoveryJob", jobId);
            }
        }
    }

    public DateTime mLastUpdate = DateTime.getNow();

    private final AtomicInteger mFailedToRunVmAttempts;
    private final AtomicInteger mUnrespondedAttempts;

    private static final int VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES = Config
            .<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes);
    private static final int VDS_RECOVERY_TIMEOUT_IN_MINUTES = Config
            .<Integer> GetValue(ConfigValues.VdsRecoveryTimeoutInMintues);
    private String duringFailureJobId;
    private boolean privateInitialized;

    public boolean getInitialized() {
        return privateInitialized;
    }

    public void setInitialized(boolean value) {
        privateInitialized = value;
    }

    private IVdsServer _vdsProxy;

    public IVdsServer getVdsProxy() {
        return _vdsProxy;
    }

    public Guid getVdsId() {
        return _vdsId;
    }

    private boolean mBeforeFirstRefresh = true;

    public boolean getbeforeFirstRefresh() {
        return mBeforeFirstRefresh;
    }

    public void setbeforeFirstRefresh(boolean value) {
        mBeforeFirstRefresh = value;
    }

    private final Guid _vdsId;

    private VdsManager(VDS vds) {
        _vds = vds;
        _vdsId = vds.getvds_id();
        mUnrespondedAttempts = new AtomicInteger();
        mFailedToRunVmAttempts = new AtomicInteger();
        log.info("Eneterd VdsManager:constructor");
        if (_vds.getstatus() == VDSStatus.PreparingForMaintenance) {
            _vds.setprevious_status(_vds.getstatus());
        } else {
            _vds.setprevious_status(VDSStatus.Up);
        }
        // if ssl is on and no certificate file
        if (Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)
                    && !FileUtil.fileExists(Config.resolveCertificatePath())) {
            if (_vds.getstatus() != VDSStatus.Maintenance && _vds.getstatus() != VDSStatus.InstallFailed) {
                setStatus(VDSStatus.NonResponsive, _vds);
                UpdateDynamicData(_vds.getDynamicData());
            }
            log.error("Could not find VDC Certificate file.");
            AuditLogableBase logable = new AuditLogableBase(_vdsId);
            AuditLogDirector.log(logable, AuditLogType.CERTIFICATE_FILE_NOT_FOUND);
        }
        InitVdsBroker();
        _vds = null;

    }

    public static VdsManager buildVdsManager(VDS vds) {
        VdsManager vdsManager = new VdsManager(vds);
        vdsManager.schedulJobs();
        return vdsManager;
    }

    private void schedulJobs() {
        SchedulerUtil sched = SchedulerUtilQuartzImpl.getInstance();
        duringFailureJobId = sched.scheduleAFixedDelayJob(this, "OnVdsDuringFailureTimer", new Class[0],
                    new Object[0], VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES, VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES,
                    TimeUnit.MINUTES);
        sched.pauseJob(duringFailureJobId);
        // start with refresh statistics
        _refreshIteration = _numberRefreshesBeforeSave - 1;

        onTimerJobId = sched.scheduleAFixedDelayJob(this, "OnTimer", new Class[0], new Object[0], VDS_REFRESH_RATE,
                VDS_REFRESH_RATE, TimeUnit.MILLISECONDS);
    }

    private void InitVdsBroker() {
        log.infoFormat("vdsBroker({0},{1})", _vds.gethost_name(), _vds.getport());

        int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout) * 1000;
        KeyValuePairCompat<VdsServerConnector, HttpClient> returnValue =
                XmlRpcUtils.getConnection(_vds.gethost_name(),
                        _vds.getport(),
                        clientTimeOut,
                        VdsServerConnector.class,
                        Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers));
        _vdsProxy = new VdsServerWrapper(returnValue.getKey(), returnValue.getValue());
    }

    public void UpdateVmDynamic(VmDynamic vmDynamic) {
        if (_vdsUpdater != null) {
            VM vm = _vdsUpdater.GetVmFromDictionary(vmDynamic.getId());
            if (vm != null) {
                vm.setDynamicData(vmDynamic);
            }
        }
        DbFacade.getInstance().getVmDynamicDAO().update(vmDynamic);
    }

    private VdsUpdateRunTimeInfo _vdsUpdater;

    @OnTimerMethodAnnotation("OnTimer")
    public void OnTimer() {
        try {
            setIsSetNonOperationalExecuted(false);
            Guid vdsId = null;
            Guid storagePoolId = null;
            String vdsName = null;
            ArrayList<VDSDomainsData> domainsList = null;

            synchronized (getLockObj()) {
                TransactionSupport.executeInScope(TransactionScopeOption.Suppress, new TransactionMethod<Object>() {
                    @Override
                    public Object runInTransaction() {
                        {
                            _vds = DbFacade.getInstance().getVdsDAO().get(getVdsId());
                            if (_vds == null) {
                                log.errorFormat("ResourceManager::refreshVdsRunTimeInfo - OnTimer is NULL for {0}",
                                        getVdsId());
                                return null;
                            }

                            try {
                                if (_refreshIteration == _numberRefreshesBeforeSave) {
                                    _refreshIteration = 1;
                                } else {
                                    _refreshIteration++;
                                }
                                if ((_vds.getstatus() != VDSStatus.NonOperational || (_vds.getvm_count() > 0))
                                        && (_vds.getstatus() != VDSStatus.Installing
                                                && _vds.getstatus() != VDSStatus.InstallFailed
                                                && _vds.getstatus() != VDSStatus.Reboot
                                                && _vds.getstatus() != VDSStatus.Maintenance
                                                && _vds.getstatus() != VDSStatus.PendingApproval
                                                && _vds.getstatus() != VDSStatus.Down)) {

                                    _vdsUpdater = new VdsUpdateRunTimeInfo(VdsManager.this, _vds);
                                    _vdsUpdater.Refresh();
                                    mUnrespondedAttempts.set(0);
                                    mLastUpdate = DateTime.getNow();
                                }
                                if (!getInitialized() && getVds().getstatus() != VDSStatus.NonResponsive
                                        && getVds().getstatus() != VDSStatus.PendingApproval) {
                                    log.info("Initializing Host: " + getVds().getvds_name());
                                    ResourceManager.getInstance().HandleVdsFinishedInit(_vds.getvds_id());
                                    setInitialized(true);
                                }
                            } catch (VDSNetworkException e) {
                                logNetworkException(e);
                            } catch (VDSRecoveringException ex) {
                                HandleVdsRecoveringException(ex);
                            } catch (IRSErrorException ex) {
                                logFailureMessage(ex);
                                if (log.isDebugEnabled()) {
                                    logException(ex);
                                }
                            } catch (RuntimeException ex) {
                                logFailureMessage(ex);
                                logException(ex);
                            }

                        }
                        return null;
                    }

                    private void logFailureMessage(RuntimeException ex) {
                        log.warnFormat(
                                "ResourceManager::refreshVdsRunTimeInfo::Failed to refresh VDS , vds = {0} : {1}, error = '{2}', continuing.",
                                _vds.getvds_id(),
                                _vds.getvds_name(),
                                ExceptionUtils.getMessage(ex));
                    }
                });
                try {
                    if (_vdsUpdater != null) {
                        _vdsUpdater.AfterRefreshTreatment();

                        // Get vds data for updating domains list, ignoring vds which is down, since it's not connected to
                        // the storage anymore (so there is no sense in updating the domains list in that case).
                        if (_vds != null && _vds.getstatus() != VDSStatus.Maintenance) {
                            vdsId = _vds.getvds_id();
                            vdsName = _vds.getvds_name();
                            storagePoolId = _vds.getstorage_pool_id();
                            domainsList = _vds.getDomains();
                        }
                    }

                    _vds = null;
                    _vdsUpdater = null;
                } catch (IRSErrorException ex) {
                    logFailureMessage(ex);
                    if (log.isDebugEnabled()) {
                        logException(ex);
                    }
                } catch (RuntimeException ex) {
                    logFailureMessage(ex);
                    logException(ex);
                }

            }

            // Now update the status of domains, this code should not be in
            // synchronized part of code
            if (domainsList != null) {
                IrsBrokerCommand.UpdateVdsDomainsData(vdsId, vdsName, storagePoolId, domainsList);
            }
        } catch (Exception e) {
            log.error("Timer update runtimeinfo failed. Exception:", e);
        }
    }

    private static void logException(final RuntimeException ex) {
        log.error("ResourceManager::refreshVdsRunTimeInfo", ex);
    }

    private void logFailureMessage(RuntimeException ex) {
        log.warnFormat(
                "ResourceManager::refreshVdsRunTimeInfo::Failed to AfterRefreshTreatment VDS  error = '{0}', continuing.",
                ExceptionUtils.getMessage(ex));
    }

    private void HandleVdsRecoveringException(VDSRecoveringException ex) {
        if (_vds.getstatus() != VDSStatus.Initializing && _vds.getstatus() != VDSStatus.NonOperational) {
            setStatus(VDSStatus.Initializing, _vds);
            UpdateDynamicData(_vds.getDynamicData());
            AuditLogableBase logable = new AuditLogableBase(_vds.getvds_id());
            logable.AddCustomValue("ErrorMessage", ex.getMessage());
            AuditLogDirector.log(logable, AuditLogType.VDS_INITIALIZING);
            log.warnFormat(
                    "ResourceManager::refreshVdsRunTimeInfo::Failed to refresh VDS , vds = {0} : {1}, error = {2}, continuing.",
                    _vds.getvds_id(),
                    _vds.getvds_name(),
                    ex.getMessage());

            String jobId = SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0],
                    new Object[0], VDS_RECOVERY_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
            recoveringJobIdMap.put(_vds.getvds_id(), jobId);
        }
    }

    @OnTimerMethodAnnotation("onTimerHandleVdsRecovering")
    public void onTimerHandleVdsRecovering() {
        recoveringJobIdMap.remove(getVdsId());
        VDS vds = DbFacade.getInstance().getVdsDAO().get(getVdsId());
        if (vds.getstatus() == VDSStatus.Initializing) {
            try {
                ResourceManager
                            .getInstance()
                            .getEventListener()
                            .VdsNonOperational(vds.getvds_id(),
                                    NonOperationalReason.TIMEOUT_RECOVERING_FROM_CRASH,
                                    true,
                                    true,
                                    Guid.Empty);
                setIsSetNonOperationalExecuted(true);
            } catch (RuntimeException exp) {
                log.errorFormat(
                            "HandleVdsRecoveringException::Error in recovery timer treatment, vds = {0} : {1}, error = {2}.",
                            vds.getvds_id(),
                            vds.getvds_name(),
                            exp.getMessage());
            }
        }
    }

    /**
     * Save dynamic data to cache and DB.
     *
     * @param dynamicData
     */
    public void UpdateDynamicData(VdsDynamic dynamicData) {
        DbFacade.getInstance().getVdsDynamicDAO().update(dynamicData);
    }

    /**
     * Save statistics data to cache and DB.
     *
     * @param statisticsData
     */
    public void UpdateStatisticsData(VdsStatistics statisticsData) {
        DbFacade.getInstance().getVdsStatisticsDAO().update(statisticsData);
    }

    public void activate() {
        VDS vds = null;
        boolean cpuFlagsChanged = false;
        try {
            // refresh vds from db in case changed while was down
            // ResourceManager.Instance.RunVdsCommand(VDSCommandType.UpdateVdsCache,
            // new VdsIdVDSCommandParametersBase(_vds.vds_id));
            if (log.isDebugEnabled()) {
                log.debugFormat(
                        "ResourceManager::activateVds - trying to activate host {0} , meanwhile setting status to Unassigned meanwhile",
                        getVdsId());
            }
            vds = DbFacade.getInstance().getVdsDAO().get(getVdsId());
            /**
             * refresh capabilities
             */
            RefObject<Boolean> tempRefObject = new RefObject<Boolean>(cpuFlagsChanged);
            VDSStatus newStatus = refreshCapabilities(tempRefObject, vds);
            if (log.isDebugEnabled()) {
                log.debugFormat(
                        "ResourceManager::activateVds - success to refreshCapabilities for host {0} , new status will be {1} ",
                        getVdsId(),
                        newStatus);
            }
            cpuFlagsChanged = tempRefObject.argvalue;
        } catch (java.lang.Exception e) {
            log.infoFormat("ResourceManager::activateVds - failed to get VDS = {0} capabilities with error: {1}.",
                    getVdsId(), e.getMessage());
            log.infoFormat("ResourceManager::activateVds - failed to activate VDS = {0}", getVdsId());

        } finally {
            if (vds != null) {
                UpdateDynamicData(vds.getDynamicData());
                // always check flags in case host cluster changed
                ResourceManager.getInstance().getEventListener().ProcessOnCpuFlagsChange(vds.getvds_id());
            }
        }
    }

    public void setStatus(VDSStatus status, VDS vds) {
        synchronized (getLockObj()) {
            if (vds == null) {
                vds = DbFacade.getInstance().getVdsDAO().get(getVdsId());
            }
            if (vds.getprevious_status() != vds.getstatus()) {
                vds.setprevious_status(vds.getstatus());
                if (_vds != null) {
                    _vds.setprevious_status(vds.getstatus());
                }
            }
            // update to new status
            vds.setstatus(status);
            if (_vds != null) {
                _vds.setstatus(status);
            }

            switch (status) {
            case NonOperational:
                if (_vds != null) {
                    _vds.setNonOperationalReason(vds.getNonOperationalReason());
                }
                if(vds.getvm_count() > 0) {
                    break;
                }
            case NonResponsive:
            case Down:
            case Maintenance:
                vds.setcpu_sys(Double.valueOf(0));
                vds.setcpu_user(Double.valueOf(0));
                vds.setcpu_idle(Double.valueOf(0));
                vds.setcpu_load(Double.valueOf(0));
                vds.setusage_cpu_percent(0);
                vds.setusage_mem_percent(0);
                vds.setusage_network_percent(0);
                if (_vds != null) {
                    _vds.setcpu_sys(Double.valueOf(0));
                    _vds.setcpu_user(Double.valueOf(0));
                    _vds.setcpu_idle(Double.valueOf(0));
                    _vds.setcpu_load(Double.valueOf(0));
                    _vds.setusage_cpu_percent(0);
                    _vds.setusage_mem_percent(0);
                    _vds.setusage_network_percent(0);
                }
            }
        }
    }

    /**
     * This function called when vds have failed vm attempts one in predefined time. Its increments failure attemts to
     * one
     *
     * @param obj
     * @param arg
     */
    @OnTimerMethodAnnotation("OnVdsDuringFailureTimer")
    public void OnVdsDuringFailureTimer() {
        synchronized (getLockObj()) {
            VDS vds = DbFacade.getInstance().getVdsDAO().get(getVdsId());
            /**
             * Disable timer if vds returns from suspitious mode
             */
            if (mFailedToRunVmAttempts.decrementAndGet() == 0) {
                SchedulerUtilQuartzImpl.getInstance().pauseJob(duringFailureJobId);
            }
            /**
             * Move vds to Up status from error
             */
            if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
                    && vds.getstatus() == VDSStatus.Error) {
                setStatus(VDSStatus.Up, vds);
                UpdateDynamicData(vds.getDynamicData());
            }
            log.infoFormat("OnVdsDuringFailureTimer of vds {0} entered. Time:{1}. Attemts after{2}", vds.getvds_name(),
                    new java.util.Date(), mFailedToRunVmAttempts);
        }
    }

    public void failedToRunVm(VDS vds) {
        if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
                && mFailedToRunVmAttempts.incrementAndGet() >= Config
                        .<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)) {
            ResourceManager.getInstance().runVdsCommand(VDSCommandType.SetVdsStatus,
                    new SetVdsStatusVDSCommandParameters(vds.getvds_id(), VDSStatus.Error));

            SchedulerUtilQuartzImpl.getInstance().resumeJob(duringFailureJobId);
            AuditLogableBase logable = new AuditLogableBase(vds.getvds_id());
            logable.AddCustomValue("Time", Config.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes)
                    .toString());
            AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_RUN_VMS);
            log.infoFormat("Vds {0} moved to Error mode after {1} attemts. Time: {2}", vds.getvds_name(),
                    mFailedToRunVmAttempts, new java.util.Date());
        }
    }

    public void forceRefreshRunTimeInfo() {
        // TODO should be solved with a thread pool
        SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "OnTimer", new Class[0], new Object[0], 0,
                TimeUnit.MILLISECONDS);
    }

    /**
     */
    public void SuccededToRunVm(Guid vmId) {
        mUnrespondedAttempts.set(0);
        ResourceManager.getInstance().SuccededToRunVm(vmId, _vds.getvds_id());
    }

    public VDSStatus refreshCapabilities(RefObject<Boolean> cpuFlagsHasChanged, VDS vds) {
        log.debug("refreshCapabilities:GetCapabilitiesVDSCommand started method");
        String oldFlags = vds.getcpu_flags();
        GetCapabilitiesVDSCommand vdsBrokerCommand = new GetCapabilitiesVDSCommand(
                new VdsIdAndVdsVDSCommandParametersBase(vds));
        vdsBrokerCommand.Execute();
        if (vdsBrokerCommand.getVDSReturnValue().getSucceeded()) {

            VDSStatus returnStatus = vds.getstatus();
            boolean isSetNonOperational = CollectVdsNetworkDataVDSCommand.UpdateNetworkToDb(vds);
            if (isSetNonOperational) {
                setIsSetNonOperationalExecuted(true);
            }

            if (isSetNonOperational && returnStatus != VDSStatus.NonOperational) {
                if (log.isDebugEnabled()) {
                    log.debugFormat(
                            "refreshCapabilities:GetCapabilitiesVDSCommand vds {0} networks  not match it's cluster networks, vds will be moved to NonOperational",
                            vds.getStaticData().getId());
                }
                vds.setstatus(VDSStatus.NonOperational);
                vds.setNonOperationalReason(NonOperationalReason.NETWORK_UNREACHABLE);
                returnStatus = vds.getstatus();
            }

            // if (vds.getkvm_enabled() != null && vds.getkvm_enabled().equals(false)
            // && vds.getstatus() != VDSStatus.NonOperational) {
            // if (log.isDebugEnabled()) {
            // log.debugFormat(
            // "refreshCapabilities:GetCapabilitiesVDSCommand vds {0} has not kvm, vds will be moved to NonOperational",
            // vds.getStaticData().getId());
            // }
            // ResourceManager
            // .getInstance()
            // .getEventListener()
            // .VdsNonOperational(vds.getvds_id(), NonOperationalReason.KVM_NOT_RUNNING, true, true,
            // Guid.Empty);
            // vds.setstatus(VDSStatus.NonOperational);
            // returnStatus = vds.getstatus();
            // setIsSetNonOperationalExecuted(true);
            // }

            cpuFlagsHasChanged.argvalue = (!StringHelper.EqOp(oldFlags, vds.getcpu_flags()));
            return returnStatus;
        } else if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() != null) {
            // if exception is VDSNetworkException then call to
            // handleNetworkException
            if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() instanceof VDSNetworkException
                    && handleNetworkException((VDSNetworkException) vdsBrokerCommand.getVDSReturnValue()
                            .getExceptionObject(), vds)) {
                UpdateDynamicData(vds.getDynamicData());
                UpdateStatisticsData(vds.getStatisticsData());
            }
            throw vdsBrokerCommand.getVDSReturnValue().getExceptionObject();
        } else {
            log.errorFormat("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!");
            throw new RuntimeException(vdsBrokerCommand.getVDSReturnValue().getExceptionString());
        }
    }

    /**
     * Handle network exception, return true if save vdsDynamic to DB is needed.
     *
     * @param ex
     * @return
     */
    public boolean handleNetworkException(VDSNetworkException ex, VDS vds) {
        if (vds.getstatus() != VDSStatus.Down) {
            if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount)
                    || mLastUpdate.AddSeconds(Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds))
                            .compareTo(new java.util.Date()) > 0) {
                boolean result = false;
                if (vds.getstatus() != VDSStatus.Problematic && vds.getstatus() != VDSStatus.PreparingForMaintenance
                        && vds.getstatus() != VDSStatus.NonResponsive) {
                    setStatus(VDSStatus.Problematic, vds);
                    result = true;
                }
                mUnrespondedAttempts.incrementAndGet();
                return result;
            }

            if (vds.getstatus() == VDSStatus.NonResponsive || vds.getstatus() == VDSStatus.Maintenance) {
                // clearNotRespondingVds();
                setStatus(VDSStatus.NonResponsive, vds);
                return true;
            }
            setStatus(VDSStatus.NonResponsive, vds);
            log.errorFormat(
                    "VDS::handleNetworkException Server failed to respond,  vds_id = {0}, vds_name = {1}, error = {2}",
                    vds.getvds_id(), vds.getvds_name(), ex.getMessage());

            AuditLogableBase logable = new AuditLogableBase(vds.getvds_id());
            AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE);
            if (ResourceManager.getInstance().getEventListener() != null) {
                ResourceManager.getInstance().getEventListener().VdsNotResponding(vds);
            }
        }
        return true;
    }

    public void dispose() {
        log.info("vdsManager::disposing");
        SchedulerUtilQuartzImpl.getInstance().deleteJob(onTimerJobId);
        XmlRpcUtils.shutDownConnection(((VdsServerWrapper) _vdsProxy).getHttpClient());;
    }

    /**
     * Log the network exception depending on the VDS status.
     *
     * @param e
     *            The exception to log.
     */
    private void logNetworkException(VDSNetworkException e) {
        switch (_vds.getstatus()) {
        case Down:
            break;
        case NonResponsive:
            log.debugFormat(
                    "ResourceManager::refreshVdsRunTimeInfo::Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
                    _vds.getvds_id(),
                    _vds.getvds_name(),
                    e.getMessage());
            break;
        default:
            log.warnFormat(
                    "ResourceManager::refreshVdsRunTimeInfo::Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
                    _vds.getvds_id(),
                    _vds.getvds_name(),
                    e.getMessage());
        }
    }

    public void setIsSetNonOperationalExecuted(boolean isExecuted) {
        this.isSetNonOperationalExecuted = isExecuted;
    }

    public boolean isSetNonOperationalExecuted() {
        return isSetNonOperationalExecuted;
    }

    private static LogCompat log = LogFactoryCompat.getLog(VdsManager.class);

}


text:
class GURL;

namespace net {

struct DnsConfig;
class HistogramWatcher;
class NetworkChangeNotifierFactory;
struct NetworkInterface;
typedef std::vector<NetworkInterface> NetworkInterfaceList;
class URLRequest;

#if defined(OS_LINUX)
namespace internal {
class AddressTrackerLinux;
}
#endif

// NetworkChangeNotifier monitors the system for network changes, and notifies
// registered observers of those events.  Observers may register on any thread,
// and will be called back on the thread from which they registered.
// NetworkChangeNotifiers are threadsafe, though they must be created and
// destroyed on the same thread.
class NET_EXPORT NetworkChangeNotifier {
 public:
  // This is a superset of the connection types in the NetInfo v3 specification:
  // http://w3c.github.io/netinfo/.
  //
  // A Java counterpart will be generated for this enum.
  // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.net
  //
  // New enum values should only be added to the end of the enum and no values
  // should be modified or reused, as this is reported via UMA.
  enum ConnectionType {
    CONNECTION_UNKNOWN = 0,  // A connection exists, but its type is unknown.
                             // Also used as a default value.
    CONNECTION_ETHERNET = 1,
    CONNECTION_WIFI = 2,
    CONNECTION_2G = 3,
    CONNECTION_3G = 4,
    CONNECTION_4G = 5,
    CONNECTION_NONE = 6,     // No connection.
    CONNECTION_BLUETOOTH = 7,
    CONNECTION_LAST = CONNECTION_BLUETOOTH
  };

  // This is the NetInfo v3 set of connection technologies as seen in
  // http://w3c.github.io/netinfo/. This enum is copied in
  // NetworkChangeNotifier.java so be sure to change both at once.
  //
  // A Java counterpart will be generated for this enum.
  // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.net
  enum ConnectionSubtype {
    SUBTYPE_GSM = 0,
    SUBTYPE_IDEN,
    SUBTYPE_CDMA,
    SUBTYPE_1XRTT,
    SUBTYPE_GPRS,
    SUBTYPE_EDGE,
    SUBTYPE_UMTS,
    SUBTYPE_EVDO_REV_0,
    SUBTYPE_EVDO_REV_A,
    SUBTYPE_HSPA,
    SUBTYPE_EVDO_REV_B,
    SUBTYPE_HSDPA,
    SUBTYPE_HSUPA,
    SUBTYPE_EHRPD,
    SUBTYPE_HSPAP,
    SUBTYPE_LTE,
    SUBTYPE_LTE_ADVANCED,
    SUBTYPE_BLUETOOTH_1_2,
    SUBTYPE_BLUETOOTH_2_1,
    SUBTYPE_BLUETOOTH_3_0,
    SUBTYPE_BLUETOOTH_4_0,
    SUBTYPE_ETHERNET,
    SUBTYPE_FAST_ETHERNET,
    SUBTYPE_GIGABIT_ETHERNET,
    SUBTYPE_10_GIGABIT_ETHERNET,
    SUBTYPE_WIFI_B,
    SUBTYPE_WIFI_G,
    SUBTYPE_WIFI_N,
    SUBTYPE_WIFI_AC,
    SUBTYPE_WIFI_AD,
    SUBTYPE_UNKNOWN,
    SUBTYPE_NONE,
    SUBTYPE_OTHER,
    SUBTYPE_LAST = SUBTYPE_OTHER
  };

  class NET_EXPORT IPAddressObserver {
   public:
    // Will be called when the IP address of the primary interface changes.
    // This includes when the primary interface itself changes.
    virtual void OnIPAddressChanged() = 0;

   protected:
    IPAddressObserver() {}
    virtual ~IPAddressObserver() {}

   private:
    DISALLOW_COPY_AND_ASSIGN(IPAddressObserver);
  };

  class NET_EXPORT ConnectionTypeObserver {
   public:
    // Will be called when the connection type of the system has changed.
    // See NetworkChangeNotifier::GetConnectionType() for important caveats
    // about the unreliability of using this signal to infer the ability to
    // reach remote sites.
    virtual void OnConnectionTypeChanged(ConnectionType type) = 0;

   protected:
    ConnectionTypeObserver() {}
    virtual ~ConnectionTypeObserver() {}

   private:
    DISALLOW_COPY_AND_ASSIGN(ConnectionTypeObserver);
  };

  class NET_EXPORT DNSObserver {
   public:
    // Will be called when the DNS settings of the system may have changed.
    // Use GetDnsConfig to obtain the current settings.
    virtual void OnDNSChanged() = 0;
    // Will be called when DNS settings of the system have been loaded.
    // Use GetDnsConfig to obtain the current settings.
    virtual void OnInitialDNSConfigRead();

   protected:
    DNSObserver() {}
    virtual ~DNSObserver() {}

   private:
    DISALLOW_COPY_AND_ASSIGN(DNSObserver);
  };

  class NET_EXPORT NetworkChangeObserver {
   public:
    // OnNetworkChanged will be called when a change occurs to the host
    // computer's hardware or software that affects the route network packets
    // take to any network server. Some examples:
    //   1. A network connection becoming available or going away. For example
    //      plugging or unplugging an Ethernet cable, WiFi or cellular modem
    //      connecting or disconnecting from a network, or a VPN tunnel being
    //      established or taken down.
    //   2. An active network connection's IP address changes.
    //   3. A change to the local IP routing tables.
    // The signal shall only be produced when the change is complete.  For
    // example if a new network connection has become available, only give the
    // signal once we think the O/S has finished establishing the connection
    // (i.e. DHCP is done) to the point where the new connection is usable.
    // The signal shall not be produced spuriously as it will be triggering some
    // expensive operations, like socket pools closing all connections and
    // sockets and then re-establishing them.
    // |type| indicates the type of the active primary network connection after
    // the change.  Observers performing "constructive" activities like trying
    // to establish a connection to a server should only do so when
    // |type != CONNECTION_NONE|.  Observers performing "destructive" activities
    // like resetting already established server connections should only do so
    // when |type == CONNECTION_NONE|.  OnNetworkChanged will always be called
    // with CONNECTION_NONE immediately prior to being called with an online
    // state; this is done to make sure that destructive actions take place
    // prior to constructive actions.
    virtual void OnNetworkChanged(ConnectionType type) = 0;

   protected:
    NetworkChangeObserver() {}
    virtual ~NetworkChangeObserver() {}

   private:
    DISALLOW_COPY_AND_ASSIGN(NetworkChangeObserver);
  };

  class NET_EXPORT MaxBandwidthObserver {
   public:
    // Called when a change occurs to the network's maximum bandwidth as
    // defined in http://w3c.github.io/netinfo/. Also called on type change,
    // even if the maximum bandwidth doesn't change. See the documentation of
    // GetMaxBanwidthAndConnectionType for what to expect for the values of
    // |max_bandwidth_mbps|.
    virtual void OnMaxBandwidthChanged(double max_bandwidth_mbps,
                                       ConnectionType type) = 0;

   protected:
    MaxBandwidthObserver() {}
    virtual ~MaxBandwidthObserver() {}

   private:
    DISALLOW_COPY_AND_ASSIGN(MaxBandwidthObserver);
  };

  // Opaque handle for device-wide connection to a particular network. For
  // example an association with a particular WiFi network with a particular
  // SSID or a connection to particular cellular network.
  // The meaning of this handle is target-dependent. On Android NetworkHandles
  // are equivalent to the framework's concept of NetIDs (e.g. Network.netId).
  typedef int32_t NetworkHandle;

  // A list of networks.
  typedef std::vector<NetworkHandle> NetworkList;

  // An interface that when implemented and added via AddNeworkObserver(),
  // provides notifications when networks come and go.
  // Only implemented for Android (Lollipop and newer), no callbacks issued when
  // unimplemented.
  class NET_EXPORT NetworkObserver {
   public:
    // Called when device connects to |network|. For example device associates
    // with a WiFi access point. This does not imply the network has Internet
    // access as it may well be behind a captive portal.
    virtual void OnNetworkConnected(NetworkHandle network) = 0;
    // Called when device disconnects from |network|.
    virtual void OnNetworkDisconnected(NetworkHandle network) = 0;
    // Called when device determines the connection to |network| is no longer
    // preferred, for example when a device transitions from cellular to WiFi
    // it might deem the cellular connection no longer preferred. The device
    // will disconnect from |network| in a period of time (30s on Android),
    // allowing network communications via |network| to wrap up.
    virtual void OnNetworkSoonToDisconnect(NetworkHandle network) = 0;
    // Called when |network| is made the default network for communication.
    virtual void OnNetworkMadeDefault(NetworkHandle network) = 0;

   protected:
    NetworkObserver() {}
    virtual ~NetworkObserver() {}

   private:
    DISALLOW_COPY_AND_ASSIGN(NetworkObserver);
  };

  // An invalid NetworkHandle.
  static const NetworkHandle kInvalidNetworkHandle;

  virtual ~NetworkChangeNotifier();

  // Replaces the default class factory instance of NetworkChangeNotifier class.
  // The method will take over the ownership of |factory| object.
  static void SetFactory(NetworkChangeNotifierFactory* factory);

  // Creates the process-wide, platform-specific NetworkChangeNotifier.  The
  // caller owns the returned pointer.  You may call this on any thread.  You
  // may also avoid creating this entirely (in which case nothing will be
  // monitored), but if you do create it, you must do so before any other
  // threads try to access the API below, and it must outlive all other threads
  // which might try to use it.
  static NetworkChangeNotifier* Create();

  // Returns the connection type.
  // A return value of |CONNECTION_NONE| is a pretty strong indicator that the
  // user won't be able to connect to remote sites. However, another return
  // value doesn't imply that the user will be able to connect to remote sites;
  // even if some link is up, it is uncertain whether a particular connection
  // attempt to a particular remote site will be successful.
  // The returned value only describes the connection currently used by the
  // device, and does not take into account other machines on the network. For
  // example, if the device is connected using Wifi to a 3G gateway to access
  // the internet, the connection type is CONNECTION_WIFI.
  static ConnectionType GetConnectionType();

  // Sets |max_bandwidth_mbps| to a theoretical upper limit on download
  // bandwidth, potentially based on underlying connection type, signal
  // strength, or some other signal. If the network subtype is unknown then
  // |max_bandwidth_mbps| is set to +Infinity and if there is no network
  // connection then it is set to 0.0. The circumstances in which a more
  // specific value is given are: when an Android device is connected to a
  // cellular or WiFi network, and when a ChromeOS device is connected to a
  // cellular network. See the NetInfo spec for the mapping of
  // specific subtypes to bandwidth values: http://w3c.github.io/netinfo/.
  // |connection_type| is set to the current active default network's connection
  // type.
  static void GetMaxBandwidthAndConnectionType(double* max_bandwidth_mbps,
                                               ConnectionType* connection_type);

  // Returns a theoretical upper limit (in Mbps) on download bandwidth given a
  // connection subtype. The mapping of connection type to maximum bandwidth is
  // provided in the NetInfo spec: http://w3c.github.io/netinfo/.
  // TODO(jkarlin): Rename to GetMaxBandwidthMbpsForConnectionSubtype.
  static double GetMaxBandwidthForConnectionSubtype(ConnectionSubtype subtype);

  // Returns true if the platform supports use of APIs based on NetworkHandles.
  // Public methods that use NetworkHandles are GetNetworkConnectionType(),
  // GetNetworkConnectionType(), GetDefaultNetwork(), AddNetworkObserver(),
  // RemoveNetworkObserver(), and all public NetworkObserver methods.
  static bool AreNetworkHandlesSupported();

  // Sets |network_list| to a list of all networks that are currently connected.
  // Only implemented for Android (Lollipop and newer), leaves |network_list|
  // empty when unimplemented. Requires NetworkHandles support, see
  // AreNetworkHandlesSupported().
  static void GetConnectedNetworks(NetworkList* network_list);

  // Returns the type of connection |network| uses. Note that this may vary
  // slightly over time (e.g. CONNECTION_2G to CONNECTION_3G). If |network|
  // is no longer connected, it will return CONNECTION_UNKNOWN.
  // Only implemented for Android (Lollipop and newer), returns
  // CONNECTION_UNKNOWN when unimplemented. Requires NetworkHandles support,
  // see AreNetworkHandlesSupported().
  static ConnectionType GetNetworkConnectionType(NetworkHandle network);

  // Returns the device's current default network connection. This is the
  // network used for newly created socket communication for sockets that are
  // not explicitly bound to a particular network (e.g. via
  // DatagramClientSocket.BindToNetwork). Returns |kInvalidNetworkHandle| if
  // there is no default connected network.
  // Only implemented for Android (Lollipop and newer), returns
  // |kInvalidNetworkHandle| when unimplemented.
  // Requires NetworkHandles support, see AreNetworkHandlesSupported().
  static NetworkHandle GetDefaultNetwork();

  // Retrieve the last read DnsConfig. This could be expensive if the system has
  // a large HOSTS file.
  static void GetDnsConfig(DnsConfig* config);

#if defined(OS_LINUX)
  // Returns the AddressTrackerLinux if present.
  static const internal::AddressTrackerLinux* GetAddressTracker();
#endif

  // Convenience method to determine if the user is offline.
  // Returns true if there is currently no internet connection.
  //
  // A return value of |true| is a pretty strong indicator that the user
  // won't be able to connect to remote sites. However, a return value of
  // |false| is inconclusive; even if some link is up, it is uncertain
  // whether a particular connection attempt to a particular remote site
  // will be successfully.
  static bool IsOffline();

  // Returns true if |type| is a cellular connection.
  // Returns false if |type| is CONNECTION_UNKNOWN, and thus, depending on the
  // implementation of GetConnectionType(), it is possible that
  // IsConnectionCellular(GetConnectionType()) returns false even if the
  // current connection is cellular.
  static bool IsConnectionCellular(ConnectionType type);

  // Gets the current connection type based on |interfaces|. Returns
  // CONNECTION_NONE if there are no interfaces, CONNECTION_UNKNOWN if two
  // interfaces have different connection types or the connection type of all
  // interfaces if they have the same interface type.
  static ConnectionType ConnectionTypeFromInterfaceList(
      const NetworkInterfaceList& interfaces);

  // Like Create(), but for use in tests.  The mock object doesn't monitor any
  // events, it merely rebroadcasts notifications when requested.
  static NetworkChangeNotifier* CreateMock();

  // Registers |observer| to receive notifications of network changes.  The
  // thread on which this is called is the thread on which |observer| will be
  // called back with notifications.  This is safe to call if Create() has not
  // been called (as long as it doesn't race the Create() call on another
  // thread), in which case it will simply do nothing.
  static void AddIPAddressObserver(IPAddressObserver* observer);
  static void AddConnectionTypeObserver(ConnectionTypeObserver* observer);
  static void AddDNSObserver(DNSObserver* observer);
  static void AddNetworkChangeObserver(NetworkChangeObserver* observer);
  static void AddMaxBandwidthObserver(MaxBandwidthObserver* observer);
  static void AddNetworkObserver(NetworkObserver* observer);

  // Unregisters |observer| from receiving notifications.  This must be called
  // on the same thread on which AddObserver() was called.  Like AddObserver(),
  // this is safe to call if Create() has not been called (as long as it doesn't
  // race the Create() call on another thread), in which case it will simply do
  // nothing.  Technically, it's also safe to call after the notifier object has
  // been destroyed, if the call doesn't race the notifier's destruction, but
  // there's no reason to use the API in this risky way, so don't do it.
  static void RemoveIPAddressObserver(IPAddressObserver* observer);
  static void RemoveConnectionTypeObserver(ConnectionTypeObserver* observer);
  static void RemoveDNSObserver(DNSObserver* observer);
  static void RemoveNetworkChangeObserver(NetworkChangeObserver* observer);
  static void RemoveMaxBandwidthObserver(MaxBandwidthObserver* observer);
  static void RemoveNetworkObserver(NetworkObserver* observer);

  // Allow unit tests to trigger notifications.
  static void NotifyObserversOfIPAddressChangeForTests();
  static void NotifyObserversOfConnectionTypeChangeForTests(
      ConnectionType type);
  static void NotifyObserversOfNetworkChangeForTests(ConnectionType type);
  static void NotifyObserversOfInitialDNSConfigReadForTests();
  static void NotifyObserversOfMaxBandwidthChangeForTests(
      double max_bandwidth_mbps,
      ConnectionType type);

  // Enable or disable notifications from the host. After setting to true, be
  // sure to pump the RunLoop until idle to finish any preexisting
  // notifications. To use this, it must must be called before a
  // NetworkChangeNotifier is created.
  static void SetTestNotificationsOnly(bool test_only);

  // Return a string equivalent to |type|.
  static const char* ConnectionTypeToString(ConnectionType type);

  // Let the NetworkChangeNotifier know we received some data.
  // This is used for producing histogram data about the accuracy of
  // the NetworkChangenotifier's online detection and rough network
  // connection measurements.
  static void NotifyDataReceived(const URLRequest& request, int bytes_read);

  // Register the Observer callbacks for producing histogram data.  This
  // should be called from the network thread to avoid race conditions.
  // ShutdownHistogramWatcher() must be called prior to NetworkChangeNotifier
  // destruction.
  static void InitHistogramWatcher();

  // Unregister the Observer callbacks for producing histogram data.  This
  // should be called from the network thread to avoid race conditions.
  static void ShutdownHistogramWatcher();

  // Log the |NCN.NetworkOperatorMCCMNC| histogram.
  static void LogOperatorCodeHistogram(ConnectionType type);

  // Allows a second NetworkChangeNotifier to be created for unit testing, so
  // the test suite can create a MockNetworkChangeNotifier, but platform
  // specific NetworkChangeNotifiers can also be created for testing.  To use,
  // create an DisableForTest object, and then create the new
  // NetworkChangeNotifier object.  The NetworkChangeNotifier must be
  // destroyed before the DisableForTest object, as its destruction will restore
  // the original NetworkChangeNotifier.
  class NET_EXPORT DisableForTest {
   public:
    DisableForTest();
    ~DisableForTest();

   private:
    // The original NetworkChangeNotifier to be restored on destruction.
    NetworkChangeNotifier* network_change_notifier_;
  };

 protected:
  // Types of network changes specified to
  // NotifyObserversOfSpecificNetworkChange.
  enum NetworkChangeType {
    CONNECTED,
    DISCONNECTED,
    SOON_TO_DISCONNECT,
    MADE_DEFAULT
  };

  // NetworkChanged signal is calculated from the IPAddressChanged and
  // ConnectionTypeChanged signals. Delay parameters control how long to delay
  // producing NetworkChanged signal after particular input signals so as to
  // combine duplicates.  In other words if an input signal is repeated within
  // the corresponding delay period, only one resulting NetworkChange signal is
  // produced.
  struct NET_EXPORT NetworkChangeCalculatorParams {
    NetworkChangeCalculatorParams();
    // Controls delay after OnIPAddressChanged when transitioning from an
    // offline state.
    base::TimeDelta ip_address_offline_delay_;
    // Controls delay after OnIPAddressChanged when transitioning from an
    // online state.
    base::TimeDelta ip_address_online_delay_;
    // Controls delay after OnConnectionTypeChanged when transitioning from an
    // offline state.
    base::TimeDelta connection_type_offline_delay_;
    // Controls delay after OnConnectionTypeChanged when transitioning from an
    // online state.
    base::TimeDelta connection_type_online_delay_;
  };

  explicit NetworkChangeNotifier(
      const NetworkChangeCalculatorParams& params =
          NetworkChangeCalculatorParams());

#if defined(OS_LINUX)
  // Returns the AddressTrackerLinux if present.
  // TODO(szym): Retrieve AddressMap from NetworkState. http://crbug.com/144212
  virtual const internal::AddressTrackerLinux*
      GetAddressTrackerInternal() const;
#endif

  // These are the actual implementations of the static queryable APIs.
  // See the description of the corresponding functions named without "Current".
  // Implementations must be thread-safe. Implementations must also be
  // cheap as they are called often.
  virtual ConnectionType GetCurrentConnectionType() const = 0;
  virtual void GetCurrentMaxBandwidthAndConnectionType(
      double* max_bandwidth_mbps,
      ConnectionType* connection_type) const;
  virtual bool AreNetworkHandlesCurrentlySupported() const;
  virtual void GetCurrentConnectedNetworks(NetworkList* network_list) const;
  virtual ConnectionType GetCurrentNetworkConnectionType(
      NetworkHandle network) const;
  virtual NetworkHandle GetCurrentDefaultNetwork() const;

  // Broadcasts a notification to all registered observers.  Note that this
  // happens asynchronously, even for observers on the current thread, even in
  // tests.
  static void NotifyObserversOfIPAddressChange();
  static void NotifyObserversOfConnectionTypeChange();
  static void NotifyObserversOfDNSChange();
  static void NotifyObserversOfInitialDNSConfigRead();
  static void NotifyObserversOfNetworkChange(ConnectionType type);
  static void NotifyObserversOfMaxBandwidthChange(double max_bandwidth_mbps,
                                                  ConnectionType type);
  static void NotifyObserversOfSpecificNetworkChange(NetworkChangeType type,
                                                     NetworkHandle network);

  // Stores |config| in NetworkState and notifies OnDNSChanged observers.
  static void SetDnsConfig(const DnsConfig& config);
  // Stores |config| in NetworkState and notifies OnInitialDNSConfigRead
  // observers.
  static void SetInitialDnsConfig(const DnsConfig& config);

 private:
  friend class HostResolverImplDnsTest;
  friend class NetworkChangeNotifierAndroidTest;
  friend class NetworkChangeNotifierLinuxTest;
  friend class NetworkChangeNotifierWinTest;

  class NetworkState;
  class NetworkChangeCalculator;

  void NotifyObserversOfIPAddressChangeImpl();
  void NotifyObserversOfConnectionTypeChangeImpl(ConnectionType type);
  void NotifyObserversOfDNSChangeImpl();
  void NotifyObserversOfInitialDNSConfigReadImpl();
  void NotifyObserversOfNetworkChangeImpl(ConnectionType type);
  void NotifyObserversOfMaxBandwidthChangeImpl(double max_bandwidth_mbps,
                                               ConnectionType type);
  void NotifyObserversOfSpecificNetworkChangeImpl(NetworkChangeType type,
                                                  NetworkHandle network);

  const scoped_refptr<base::ObserverListThreadSafe<IPAddressObserver>>
      ip_address_observer_list_;
  const scoped_refptr<base::ObserverListThreadSafe<ConnectionTypeObserver>>
      connection_type_observer_list_;
  const scoped_refptr<base::ObserverListThreadSafe<DNSObserver>>
      resolver_state_observer_list_;
  const scoped_refptr<base::ObserverListThreadSafe<NetworkChangeObserver>>
      network_change_observer_list_;
  const scoped_refptr<base::ObserverListThreadSafe<MaxBandwidthObserver>>
      max_bandwidth_observer_list_;
  const scoped_refptr<base::ObserverListThreadSafe<NetworkObserver>>
      network_observer_list_;

  // The current network state. Hosts DnsConfig, exposed via GetDnsConfig.
  scoped_ptr<NetworkState> network_state_;

  // A little-piggy-back observer that simply logs UMA histogram data.
  scoped_ptr<HistogramWatcher> histogram_watcher_;

  // Computes NetworkChange signal from IPAddress and ConnectionType signals.
  scoped_ptr<NetworkChangeCalculator> network_change_calculator_;

  // Set true to disable non-test notifications (to prevent flakes in tests).
  static bool test_notifications_only_;

  DISALLOW_COPY_AND_ASSIGN(NetworkChangeNotifier);
};

}  // namespace net

#endif  // NET_BASE_NETWORK_CHANGE_NOTIFIER_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.gyyx.rbac.mapper.RbacRolePermissionsMapper">

	<!-- 通用查询映射结果 -->
	<resultMap id="BaseResultMap" type="cn.gyyx.rbac.entity.RbacRolePermissions">
		<id column="id" property="id" />
		<result column="role_id" property="roleId" />
		<result column="permissions_id" property="permissionsId" />
		<result column="permissions_type" property="permissionsType" />
	</resultMap>

</mapper>


text:
using System.Web.Mvc;
using M13n.Models;

namespace M13n.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet()]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet()]
        public ActionResult About()
        {
            return View();
        }

        [HttpGet()]
        public ActionResult Contact()
        {
            return View();
        }

        [HttpPost()]
        public ActionResult Contact(ContactModel cm)
        {
            if (ModelState.IsValid)
            {
                // Send it into the void
                cm = new ContactModel();
            }

            return View(cm);
        }
    }
}


text:
package org.duracloud.syncui.service;

import org.duracloud.client.ContentStoreManager;
import org.duracloud.error.ContentStoreException;

/**
 * @author Daniel Bernstein
 */
public interface ContentStoreManagerFactory {

    public ContentStoreManager create() throws ContentStoreException;
}


text:
package garden

import proto "github.com/gogo/protobuf/proto"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

type CreateRequest_BindMount_Mode int32

const (
	CreateRequest_BindMount_RO CreateRequest_BindMount_Mode = 0
	CreateRequest_BindMount_RW CreateRequest_BindMount_Mode = 1
)

var CreateRequest_BindMount_Mode_name = map[int32]string{
	0: "RO",
	1: "RW",
}
var CreateRequest_BindMount_Mode_value = map[string]int32{
	"RO": 0,
	"RW": 1,
}

func (x CreateRequest_BindMount_Mode) Enum() *CreateRequest_BindMount_Mode {
	p := new(CreateRequest_BindMount_Mode)
	*p = x
	return p
}
func (x CreateRequest_BindMount_Mode) String() string {
	return proto.EnumName(CreateRequest_BindMount_Mode_name, int32(x))
}
func (x *CreateRequest_BindMount_Mode) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(CreateRequest_BindMount_Mode_value, data, "CreateRequest_BindMount_Mode")
	if err != nil {
		return err
	}
	*x = CreateRequest_BindMount_Mode(value)
	return nil
}

type CreateRequest_BindMount_Origin int32

const (
	CreateRequest_BindMount_Host      CreateRequest_BindMount_Origin = 0
	CreateRequest_BindMount_Container CreateRequest_BindMount_Origin = 1
)

var CreateRequest_BindMount_Origin_name = map[int32]string{
	0: "Host",
	1: "Container",
}
var CreateRequest_BindMount_Origin_value = map[string]int32{
	"Host":      0,
	"Container": 1,
}

func (x CreateRequest_BindMount_Origin) Enum() *CreateRequest_BindMount_Origin {
	p := new(CreateRequest_BindMount_Origin)
	*p = x
	return p
}
func (x CreateRequest_BindMount_Origin) String() string {
	return proto.EnumName(CreateRequest_BindMount_Origin_name, int32(x))
}
func (x *CreateRequest_BindMount_Origin) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(CreateRequest_BindMount_Origin_value, data, "CreateRequest_BindMount_Origin")
	if err != nil {
		return err
	}
	*x = CreateRequest_BindMount_Origin(value)
	return nil
}

type CreateRequest struct {
	BindMounts       []*CreateRequest_BindMount `protobuf:"bytes,1,rep,name=bind_mounts" json:"bind_mounts,omitempty"`
	GraceTime        *uint32                    `protobuf:"varint,2,opt,name=grace_time" json:"grace_time,omitempty"`
	Handle           *string                    `protobuf:"bytes,3,opt,name=handle" json:"handle,omitempty"`
	Network          *string                    `protobuf:"bytes,4,opt,name=network" json:"network,omitempty"`
	Rootfs           *string                    `protobuf:"bytes,5,opt,name=rootfs" json:"rootfs,omitempty"`
	Properties       []*Property                `protobuf:"bytes,6,rep,name=properties" json:"properties,omitempty"`
	Env              []*EnvironmentVariable     `protobuf:"bytes,7,rep,name=env" json:"env,omitempty"`
	Privileged       *bool                      `protobuf:"varint,8,opt,name=privileged" json:"privileged,omitempty"`
	XXX_unrecognized []byte                     `json:"-"`
}

func (m *CreateRequest) Reset()         { *m = CreateRequest{} }
func (m *CreateRequest) String() string { return proto.CompactTextString(m) }
func (*CreateRequest) ProtoMessage()    {}

func (m *CreateRequest) GetBindMounts() []*CreateRequest_BindMount {
	if m != nil {
		return m.BindMounts
	}
	return nil
}

func (m *CreateRequest) GetGraceTime() uint32 {
	if m != nil && m.GraceTime != nil {
		return *m.GraceTime
	}
	return 0
}

func (m *CreateRequest) GetHandle() string {
	if m != nil && m.Handle != nil {
		return *m.Handle
	}
	return ""
}

func (m *CreateRequest) GetNetwork() string {
	if m != nil && m.Network != nil {
		return *m.Network
	}
	return ""
}

func (m *CreateRequest) GetRootfs() string {
	if m != nil && m.Rootfs != nil {
		return *m.Rootfs
	}
	return ""
}

func (m *CreateRequest) GetProperties() []*Property {
	if m != nil {
		return m.Properties
	}
	return nil
}

func (m *CreateRequest) GetEnv() []*EnvironmentVariable {
	if m != nil {
		return m.Env
	}
	return nil
}

func (m *CreateRequest) GetPrivileged() bool {
	if m != nil && m.Privileged != nil {
		return *m.Privileged
	}
	return false
}

type CreateRequest_BindMount struct {
	SrcPath          *string                         `protobuf:"bytes,1,req,name=src_path" json:"src_path,omitempty"`
	DstPath          *string                         `protobuf:"bytes,2,req,name=dst_path" json:"dst_path,omitempty"`
	Mode             *CreateRequest_BindMount_Mode   `protobuf:"varint,3,req,name=mode,enum=garden.CreateRequest_BindMount_Mode" json:"mode,omitempty"`
	Origin           *CreateRequest_BindMount_Origin `protobuf:"varint,4,opt,name=origin,enum=garden.CreateRequest_BindMount_Origin" json:"origin,omitempty"`
	XXX_unrecognized []byte                          `json:"-"`
}

func (m *CreateRequest_BindMount) Reset()         { *m = CreateRequest_BindMount{} }
func (m *CreateRequest_BindMount) String() string { return proto.CompactTextString(m) }
func (*CreateRequest_BindMount) ProtoMessage()    {}

func (m *CreateRequest_BindMount) GetSrcPath() string {
	if m != nil && m.SrcPath != nil {
		return *m.SrcPath
	}
	return ""
}

func (m *CreateRequest_BindMount) GetDstPath() string {
	if m != nil && m.DstPath != nil {
		return *m.DstPath
	}
	return ""
}

func (m *CreateRequest_BindMount) GetMode() CreateRequest_BindMount_Mode {
	if m != nil && m.Mode != nil {
		return *m.Mode
	}
	return CreateRequest_BindMount_RO
}

func (m *CreateRequest_BindMount) GetOrigin() CreateRequest_BindMount_Origin {
	if m != nil && m.Origin != nil {
		return *m.Origin
	}
	return CreateRequest_BindMount_Host
}

type CreateResponse struct {
	Handle           *string `protobuf:"bytes,1,req,name=handle" json:"handle,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *CreateResponse) Reset()         { *m = CreateResponse{} }
func (m *CreateResponse) String() string { return proto.CompactTextString(m) }
func (*CreateResponse) ProtoMessage()    {}

func (m *CreateResponse) GetHandle() string {
	if m != nil && m.Handle != nil {
		return *m.Handle
	}
	return ""
}

func init() {
	proto.RegisterEnum("garden.CreateRequest_BindMount_Mode", CreateRequest_BindMount_Mode_name, CreateRequest_BindMount_Mode_value)
	proto.RegisterEnum("garden.CreateRequest_BindMount_Origin", CreateRequest_BindMount_Origin_name, CreateRequest_BindMount_Origin_value)
}


text:
package com.braintreegateway;

public class ThreeDSecurePassThruRequest extends Request {
    private String eciFlag;
    private String cavv;
    private String threeDSecureVersion;
    private String xid;
    private String authenticationResponse;
    private String directoryResponse;
    private String cavvAlgorithm;
    private String dsTransactionId;

    public ThreeDSecurePassThruRequest eciFlag(String eciFlag) {
        this.eciFlag = eciFlag;
        return this;
    }

    public ThreeDSecurePassThruRequest cavv(String cavv) {
        this.cavv = cavv;
        return this;
    }

    public ThreeDSecurePassThruRequest threeDSecureVersion(String threeDSecureVersion) {
        this.threeDSecureVersion = threeDSecureVersion;
        return this;
    }

    public ThreeDSecurePassThruRequest xid(String xid) {
        this.xid = xid;
        return this;
    }

    public ThreeDSecurePassThruRequest authenticationResponse(String authenticationResponse) {
        this.authenticationResponse = authenticationResponse;
        return this;
    }

    public ThreeDSecurePassThruRequest directoryResponse(String directoryResponse) {
        this.directoryResponse = directoryResponse;
        return this;
    }

    public ThreeDSecurePassThruRequest cavvAlgorithm(String cavvAlgorithm) {
        this.cavvAlgorithm = cavvAlgorithm;
        return this;
    }

    public ThreeDSecurePassThruRequest dsTransactionId(String dsTransactionId) {
        this.dsTransactionId = dsTransactionId;
        return this;
    }

    @Override
    public String toXML() {
        return buildRequest("threeDSecurePassThru").toXML();
    }

    @Override
    public String toQueryString() {
        return toQueryString("threeDSecurePassThru");
    }

    @Override
    public String toQueryString(String root) {
        return buildRequest(root).toQueryString();
    }

    protected RequestBuilder buildRequest(String root) {
        return new RequestBuilder(root)
            .addElement("eciFlag", eciFlag)
            .addElement("cavv", cavv)
            .addElement("threeDSecureVersion", threeDSecureVersion)
            .addElement("xid", xid)
            .addElement("authenticationResponse", authenticationResponse)
            .addElement("directoryResponse", directoryResponse)
            .addElement("cavvAlgorithm", cavvAlgorithm)
            .addElement("dsTransactionId", dsTransactionId);
    }
}


text:
#include "config.h"
#include "IntRect.h"

#include "FloatRect.h"
#include "LayoutRect.h"
#include <algorithm>
#include <wtf/text/TextStream.h>

namespace WebCore {

IntRect::IntRect(const FloatRect& r)
    : m_location(clampToInteger(r.x()), clampToInteger(r.y()))
    , m_size(clampToInteger(r.width()), clampToInteger(r.height()))
{
}

IntRect::IntRect(const LayoutRect& r)
    : m_location(r.x(), r.y())
    , m_size(r.width(), r.height())
{
}

bool IntRect::intersects(const IntRect& other) const
{
    // Checking emptiness handles negative widths as well as zero.
    return !isEmpty() && !other.isEmpty()
        && x() < other.maxX() && other.x() < maxX()
        && y() < other.maxY() && other.y() < maxY();
}

bool IntRect::contains(const IntRect& other) const
{
    return x() <= other.x() && maxX() >= other.maxX()
        && y() <= other.y() && maxY() >= other.maxY();
}

void IntRect::intersect(const IntRect& other)
{
    int l = std::max(x(), other.x());
    int t = std::max(y(), other.y());
    int r = std::min(maxX(), other.maxX());
    int b = std::min(maxY(), other.maxY());

    // Return a clean empty rectangle for non-intersecting cases.
    if (l >= r || t >= b) {
        l = 0;
        t = 0;
        r = 0;
        b = 0;
    }

    m_location.setX(l);
    m_location.setY(t);
    m_size.setWidth(r - l);
    m_size.setHeight(b - t);
}

void IntRect::unite(const IntRect& other)
{
    // Handle empty special cases first.
    if (other.isEmpty())
        return;
    if (isEmpty()) {
        *this = other;
        return;
    }

    int l = std::min(x(), other.x());
    int t = std::min(y(), other.y());
    int r = std::max(maxX(), other.maxX());
    int b = std::max(maxY(), other.maxY());

    m_location.setX(l);
    m_location.setY(t);
    m_size.setWidth(r - l);
    m_size.setHeight(b - t);
}

void IntRect::uniteIfNonZero(const IntRect& other)
{
    // Handle empty special cases first.
    if (!other.width() && !other.height())
        return;
    if (!width() && !height()) {
        *this = other;
        return;
    }

    int left = std::min(x(), other.x());
    int top = std::min(y(), other.y());
    int right = std::max(maxX(), other.maxX());
    int bottom = std::max(maxY(), other.maxY());

    m_location.setX(left);
    m_location.setY(top);
    m_size.setWidth(right - left);
    m_size.setHeight(bottom - top);
}

void IntRect::scale(float s)
{
    m_location.setX((int)(x() * s));
    m_location.setY((int)(y() * s));
    m_size.setWidth((int)(width() * s));
    m_size.setHeight((int)(height() * s));
}

static inline int distanceToInterval(int pos, int start, int end)
{
    if (pos < start)
        return start - pos;
    if (pos > end)
        return end - pos;
    return 0;
}

IntSize IntRect::differenceToPoint(const IntPoint& point) const
{
    int xdistance = distanceToInterval(point.x(), x(), maxX());
    int ydistance = distanceToInterval(point.y(), y(), maxY());
    return IntSize(xdistance, ydistance);
}

TextStream& operator<<(TextStream& ts, const IntRect& r)
{
    if (ts.hasFormattingFlag(TextStream::Formatting::SVGStyleRect))
        return ts << "at (" << r.x() << "," << r.y() << ") size " << r.width() << "x" << r.height();

    return ts << r.location() << " " << r.size();
}

} // namespace WebCore


text:
var Libpq = require('../')
var async = require('async')
var ok = require('okay')

var blink = function(n, cb) {
  var connections = []
  for(var i = 0; i < 30; i++) {
    connections.push(new Libpq())
  }
  var connect = function(con, cb) {
    con.connect(cb)
  }
  async.each(connections, connect, ok(function() {
    connections.forEach(function(con) {
      con.finish()
    })
    cb()
  }))
}

describe('many connections', function() {
  it('works', function(done) {
    async.timesSeries(10, blink, done)
  })
})