text:
app.controller('TeamsController', function ($scope, $http, TeamsService) {

    var store = new DevExpress.data.ODataStore({
        url: "http://api-ghosts.azurewebsites.net/odata/Teams",
        key: "TeamID",
        keyType: "Int32",
        version: 4
    });

    var storeClubs = new DevExpress.data.ODataStore({
        url: "http://api-ghosts.azurewebsites.net/odata/Clubs",
        key: "ClubID",
        keyType: "Int32",
        version: 4
    });

    var storeCategories = new DevExpress.data.ODataStore({
        url: "http://api-ghosts.azurewebsites.net/odata/Categories",
        key: "CategoryID",
        keyType: "Int32",
        version: 4
    });

    $scope.dataGridOptions = {
        dataSource: store,
        allowColumnResizing: true,
        paging: {
            pageSize: 20
        },
        pager: {
            showPageSizeSelector: true,
            allowedPageSizes: [10, 20, 50],
            showInfo: true
        },
        editing: {
            mode: "form",
            allowUpdating: true,
            allowDeleting: true,
            allowAdding: true
        },
        grouping: {
            autoExpandAll: true
        },
        groupPanel: {
            visible: true
        },
        //filterRow: {
        //    visible: true,
        //    applyFilter: "auto"
        //},
        headerFilter: {
            visible: true
        },
        columns: [{
            dataField: "TeamID",
            allowEditing: false,
            width: 70,
            alignment: 'center'
        }, {
            dataField: "Name",
            validationRules: [{ type: "required" }]
        }, {
            dataField: "CategoryID",
            width: 100,
            lookup: {
                dataSource: storeCategories,
                displayExpr: "Name",
                valueExpr: "CategoryID"
            },
            validationRules: [{ type: "required" }]
        }, {
            dataField: "ClubID",
            width: 200,
            groupIndex:0,
            lookup: {
                dataSource: storeClubs,
                displayExpr: "Name",
                valueExpr: "ClubID"
            },
            validationRules: [{ type: "required" }]
        }]
    }

});


text:
'use strict';

/* eslint-disable no-bitwise */

const base62 = require('base62');
const crc32 = require('crc32');

const PREFIX = '_';

/**
 * @internal
 *
 * Sanitizes a stringified GraphQL field (including any calls and their values)
 * to produce a valid alias.
 *
 * This is used to auto-alias fields in generated queries, so that developers
 * composing multiple components together don't have to worry about collisions
 * between components requesting the same fields. (Explicit aliases are only
 * needed within a single component when it uses the same field multiple times,
 * in order to differentiate these fields in the props).
 */
function generateRQLFieldAlias(input: string): string {
  // Field names with no calls can be used as aliases without encoding
  const index = input.indexOf('.');
  if (index === -1) {
    return input;
  }
  // Unsign crc32 hash so we do not base62 encode a negative number.
  return PREFIX + input.substr(0, index) + base62(crc32(input) >>> 0);
}

module.exports = generateRQLFieldAlias;

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ BruceHurrican
  ~ Copyright (c) 2016.
  ~  Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  ~    This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges.
  ~   And where any person can download and use, but not for commercial purposes.
  ~   Author does not assume the resulting corresponding disputes.
  ~   If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com
  ~   本文件为Bruce's个人学习android的demo, 其中所用到的代码来源于互联网,仅作为学习交流使用。
  ~   任和何人可以下载并使用, 但是不能用于商业用途。
  ~   作者不承担由此带来的相应纠纷。
  ~   如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center"
              android:orientation="vertical">

    <com.bruce.demo.studydata.fragments.meituananimation.widget.MTRefreshFirstStepView
        android:id="@+id/mt_first"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_margin="10dp"/>

    <com.bruce.demo.studydata.fragments.meituananimation.widget.MTRefreshSecondStepView
        android:id="@+id/mt_second"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_margin="10dp"
        android:visibility="gone"/>

    <com.bruce.demo.studydata.fragments.meituananimation.widget.MTRefreshThirdStepView
        android:id="@+id/mt_third"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_margin="10dp"
        android:visibility="gone"/>

    <TextView
        android:id="@+id/tv_pull_to_refresh"
        style="@style/BaseTextView"
        android:layout_marginLeft="10dp"
        android:text="下拉刷新"/>
</LinearLayout>


text:
/**
 * "
 *  Using Zenburn color palette from the Emacs Zenburn Theme
 *  https://github.com/bbatsov/zenburn-emacs/blob/master/zenburn-theme.el
 *
 *  Also using parts of https://github.com/xavi/coderay-lighttable-theme
 * "
 * From: https://github.com/wisenomad/zenburn-lighttable-theme/blob/master/zenburn.css
 */

.cm-s-zenburn .CodeMirror-gutters { background: #3f3f3f !important; }
.cm-s-zenburn .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #999; }
.cm-s-zenburn .CodeMirror-cursor { border-left: 1px solid white; }
.cm-s-zenburn { background-color: #3f3f3f; color: #dcdccc; }
.cm-s-zenburn span.cm-builtin { color: #dcdccc; font-weight: bold; }
.cm-s-zenburn span.cm-comment { color: #7f9f7f; }
.cm-s-zenburn span.cm-keyword { color: #f0dfaf; font-weight: bold; }
.cm-s-zenburn span.cm-atom { color: #bfebbf; }
.cm-s-zenburn span.cm-def { color: #dcdccc; }
.cm-s-zenburn span.cm-variable { color: #dfaf8f; }
.cm-s-zenburn span.cm-variable-2 { color: #dcdccc; }
.cm-s-zenburn span.cm-string { color: #cc9393; }
.cm-s-zenburn span.cm-string-2 { color: #cc9393; }
.cm-s-zenburn span.cm-number { color: #dcdccc; }
.cm-s-zenburn span.cm-tag { color: #93e0e3; }
.cm-s-zenburn span.cm-property { color: #dfaf8f; }
.cm-s-zenburn span.cm-attribute { color: #dfaf8f; }
.cm-s-zenburn span.cm-qualifier { color: #7cb8bb; }
.cm-s-zenburn span.cm-meta { color: #f0dfaf; }
.cm-s-zenburn span.cm-header { color: #f0efd0; }
.cm-s-zenburn span.cm-operator { color: #f0efd0; }
.cm-s-zenburn span.CodeMirror-matchingbracket { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; background: transparent; border-bottom: 1px solid; }
.cm-s-zenburn span.CodeMirror-nonmatchingbracket { border-bottom: 1px solid; background: none; }
.cm-s-zenburn .CodeMirror-activeline { background: #000000; }
.cm-s-zenburn .CodeMirror-activeline-background { background: #000000; }
.cm-s-zenburn div.CodeMirror-selected { background: #545454; }
.cm-s-zenburn .CodeMirror-focused div.CodeMirror-selected { background: #4f4f4f; }


text:
#include <iostream>
#include <assert.h>
#include "smart_enum.h"

SMART_ENUM(Animal, int) {
    SM_ENUM_ELEM(Dog,    1,  "dog"  , "dog_description")
    SM_ENUM_ELEM(Cat,    2,  "cat"  )
    SM_ENUM_ELEM(Lion,   5)
    SM_ENUM_ELEM(Horse)

};

int main()
{

    Animal pet_cat   = Animal::Cat;
    Animal pet_dog   = Animal::Dog;
    Animal pet_lion  = Animal::Lion;
    Animal pet_horse = Animal::Horse;

    /* to string conversion */
    std::cout << "pet name: " << pet_cat.to_string() << std::endl;
    //pet name: cat
    std::cout << "pet name: " << pet_lion.to_string() << std::endl;
    //pet name: Lion

    /* It is possible to get enum by name */
    constexpr Animal ct_pet_lion = Animal::from_string("Lion");

    /* get description for smart enum */
    std::cout << "descr.: " << pet_dog.description() << std::endl;
    //descr.: dog_description
    std::cout << "descr.: " << pet_horse.description() << std::endl;
    //descr.: hOrse

    /* usage in case statements */
    switch (pet_cat) {
        case Animal::Cat:
            //do_something
            break;
        case Animal::Horse:
            //do_something
            break;
        default:
            //do_something
            break;
    }

    /* getting all names for smart enum */
    for (const auto &name : Animal::names())
        std::cout << name << " ";
    std::cout << std::endl;

    /* getting all descriptions for smart enum */
    for (const auto &name : Animal::descriptions())
        std::cout << name << " ";
    std::cout << std::endl;

    /* getting all values for smart enum */
    for (const auto &enum_item : Animal::values())
        std::cout << enum_item.to_string() << " ";
    std::cout << std::endl;

    /* get number of declared elements in smart enum */
    std::cout << "Elements in smart enum: " << Animal::size() << std::endl;
    //Elements in smart enum: 4

    /* It is possible to check if data in smart enum are valid */
    Animal invalid(Animal::Cat);
    *(reinterpret_cast<int*>(&invalid)) = 6666;
    assert(invalid.is_valid() == false);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="KotlinCommonCompilerArguments">
    <option name="errors">
      <ArgumentParseErrors />
    </option>
    <option name="freeArgs">
      <list>
        <option value="chatmessageview_debug" />
        <option value="example_debug" />
        <option value="chatmessageview_debug" />
        <option value="example_debug" />
        <option value="chatmessageview_debug" />
        <option value="example_debug" />
        <option value="chatmessageview_debug" />
        <option value="example_debug" />
      </list>
    </option>
  </component>
</project>


text:
set -eo pipefail

cd docs

if [ -d vendor/cache ]
then
  bundle install --local || bundle install
else
  bundle install && bundle cache
fi

bundle exec jekyll build
bundle exec jekyll serve -H 0.0.0.0 $@


text:
@class LGAutoPkgRecipe;

@interface LGRecipeInfoView : NSViewController

- (instancetype)initWithRecipe:(LGAutoPkgRecipe *)recipe;

@end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.2-hudson-jaxb-ri-2.2-63-
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.08.05 at 03:52:15 PM MESZ
//

package org.iso.mpeg.dash;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for MultipleSegmentBaseType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="MultipleSegmentBaseType">
 *   <complexContent>
 *     <extension base="{urn:mpeg:dash:schema:mpd:2011}SegmentBaseType">
 *       <sequence>
 *         <element name="SegmentTimeline" type="{urn:mpeg:dash:schema:mpd:2011}SegmentTimelineType" minOccurs="0"/>
 *         <element name="BitstreamSwitching" type="{urn:mpeg:dash:schema:mpd:2011}URLType" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="duration" type="{http://www.w3.org/2001/XMLSchema}unsignedInt" />
 *       <attribute name="startNumber" type="{http://www.w3.org/2001/XMLSchema}unsignedInt" />
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MultipleSegmentBaseType", propOrder = {
    "segmentTimeline",
    "bitstreamSwitching"
})
@XmlSeeAlso({
    SegmentTemplateType.class,
    SegmentListType.class
})
public class MultipleSegmentBaseType
    extends SegmentBaseType
{

    @XmlElement(name = "SegmentTimeline")
    protected SegmentTimelineType segmentTimeline;
    @XmlElement(name = "BitstreamSwitching")
    protected URLType bitstreamSwitching;
    @XmlAttribute(name = "duration")
    @XmlSchemaType(name = "unsignedInt")
    protected Long duration;
    @XmlAttribute(name = "startNumber")
    @XmlSchemaType(name = "unsignedInt")
    protected Long startNumber;

    /**
     * Gets the value of the segmentTimeline property.
     *
     * @return
     *     possible object is
     *     {@link SegmentTimelineType }
     *
     */
    public SegmentTimelineType getSegmentTimeline() {
        return segmentTimeline;
    }

    /**
     * Sets the value of the segmentTimeline property.
     *
     * @param value
     *     allowed object is
     *     {@link SegmentTimelineType }
     *
     */
    public void setSegmentTimeline(SegmentTimelineType value) {
        this.segmentTimeline = value;
    }

    /**
     * Gets the value of the bitstreamSwitching property.
     *
     * @return
     *     possible object is
     *     {@link URLType }
     *
     */
    public URLType getBitstreamSwitching() {
        return bitstreamSwitching;
    }

    /**
     * Sets the value of the bitstreamSwitching property.
     *
     * @param value
     *     allowed object is
     *     {@link URLType }
     *
     */
    public void setBitstreamSwitching(URLType value) {
        this.bitstreamSwitching = value;
    }

    /**
     * Gets the value of the duration property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getDuration() {
        return duration;
    }

    /**
     * Sets the value of the duration property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setDuration(Long value) {
        this.duration = value;
    }

    /**
     * Gets the value of the startNumber property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getStartNumber() {
        return startNumber;
    }

    /**
     * Sets the value of the startNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setStartNumber(Long value) {
        this.startNumber = value;
    }

}


text:
(function( w, undefined ) {
	// Enable JS strict mode
	"use strict";

	var ala = w.ala,
		initEl = "script",
		o = {
			pluginName : "ala-embedded-comment",
			endpoint: "sample-endpoint.php"
		},
		methods = {
			_init: function(){
				var el = ala( this );

				if( el.data( "init" ) === true ) {
					return false;
				}

				return ala( this )
					.trigger( o.pluginName + "-create" )
					.data( "init", true )
					[ o.pluginName ]( "_fetchData" );
			},
			_injectiframe: function( data ) {
				var iframe = document.createElement( "iframe" ),
					script = ala( this ),
					commentid = script.data( "comment" ),
					target = w.document.getElementById(  o.pluginName + "-" + commentid ),
					iframew = function( iframe ) {
						if ( iframe.contentWindow ) {
							iframew = iframe.contentWindow;
						} else {
							if ( iframe.contentDocument && iframe.contentDocument.document ) {
								iframew = iframe.contentDocument.document;
							} else {
								iframew = iframe.contentDocument;
							}
						}
						return iframew;
					},
					iframewin;

				// Make the iframe seamless-ish.
				iframe.width = "100%";

				iframe.frameborder = "0";
				iframe.style.padding = "0";
				iframe.style.border = "none";
				iframe.style.minHeight = "96px";
				iframe.style.maxWidth = "75%";
				iframe.style.marginRight = "auto";
				iframe.style.marginLeft = "auto";
				iframe.style.border = "1px solid #dddddd";
				iframe.style.borderRadius = "6px";
				iframe.style.background = "#fff";
				iframe.style.boxShadow = "3px 2px 15px -5px rgba(238, 238, 238,1)";

				if( target ) {
					// If the fallback markup is there, replace it.
					target.parentNode.replaceChild( iframe, target );
				} else {
					// If isn't there (tsk tsk) insert the iframe before the script element.
					this.parentNode.insertBefore( iframe, this );
				}

				iframewin = iframew( iframe );

				iframewin.document.open();
				iframewin.document.write( data );

				/* When the CSS inside the iframe has finished loading, resize the iframe to match the comment's height. */
				iframewin.document.getElementsByTagName( "link" )[ 0 ].onload = function() {
					iframe.scrolling = "no";
					script[ o.pluginName ]( "_handleResize", iframe );
				};

				iframewin.document.close();

			},
			_fetchData: function() {
				var el = ala( this ),
					commentid = el.data( "comment" );

				ala.ajax( o.endpoint, {
					// We'll need to enable CORS on the endpoint side for this to work. We could chuck an `src` into the `iframe`, but resizing it would be a lot trickier.
					data: "?id=" + commentid,
					async: false,
					success: function( data ) {
						el[ o.pluginName ]( "_injectiframe", data );
					}
				});
			},
			_handleResize: function( iframe ) {
				var fixHeight = function() {
						iframe.height = iframe.contentWindow.document.getElementById( o.pluginName ).scrollHeight + 3;
					};

				fixHeight();
				ala( w ).bind( "resize", ala.fn.throttle( fixHeight, 100 ) );
			}
		};

	ala.fn[ o.pluginName ] = function( arrg, a, b, c ) {
		return this.each(function() {
			if( arrg && typeof( arrg ) === "string" ){
				return ala.fn[ o.pluginName ].prototype[ arrg ].call( this, a, b, c );
			}
			if( ala( this ).data( o.pluginName + "data" ) ){
				return ala( this );
			}
			ala( this ).data( o.pluginName + "active", true );
			ala.fn[ o.pluginName ].prototype._init.call( this );
		});
	};

	ala.extend( ala.fn[ o.pluginName ].prototype, methods );

	// Kick it all off.
	var scripts = w.document.getElementsByTagName( initEl );
	for( var i = 0, l = scripts.length; i < l; i++) {
		var el = ala( scripts[ i ] );

		if( el.data( "comment" ) ) {
			el[ o.pluginName ]();
		}
	}

}( this ));


text:
package org.zstack.network.service.virtualrouter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriComponentsBuilder;
import org.zstack.appliancevm.*;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.Platform;
import org.zstack.core.ansible.AnsibleFacade;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.GLock;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.header.AbstractService;
import org.zstack.header.apimediator.ApiMessageInterceptionException;
import org.zstack.header.apimediator.GlobalApiMessageInterceptor;
import org.zstack.header.configuration.APIUpdateInstanceOfferingEvent;
import org.zstack.header.configuration.InstanceOfferingInventory;
import org.zstack.header.configuration.InstanceOfferingVO;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.core.workflow.Flow;
import org.zstack.header.core.workflow.FlowChain;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.HypervisorType;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.image.ImageVO;
import org.zstack.header.managementnode.PrepareDbInitialValueExtensionPoint;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.network.NetworkException;
import org.zstack.header.network.l2.APICreateL2NetworkMsg;
import org.zstack.header.network.l2.L2NetworkConstant;
import org.zstack.header.network.l2.L2NetworkCreateExtensionPoint;
import org.zstack.header.network.l2.L2NetworkInventory;
import org.zstack.header.network.l3.IpRangeInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.L3NetworkVO;
import org.zstack.header.network.service.*;
import org.zstack.header.query.AddExpandedQueryExtensionPoint;
import org.zstack.header.query.ExpandedQueryAliasStruct;
import org.zstack.header.query.ExpandedQueryStruct;
import org.zstack.header.tag.SystemTagInventory;
import org.zstack.header.tag.SystemTagLifeCycleListener;
import org.zstack.header.vm.VmInstanceState;
import org.zstack.identity.AccountManager;
import org.zstack.network.service.eip.EipConstant;
import org.zstack.network.service.lb.LoadBalancerConstants;
import org.zstack.network.service.virtualrouter.eip.VirtualRouterEipRefInventory;
import org.zstack.network.service.virtualrouter.portforwarding.VirtualRouterPortForwardingRuleRefInventory;
import org.zstack.network.service.virtualrouter.vip.VirtualRouterVipInventory;
import org.zstack.search.GetQuery;
import org.zstack.search.SearchQuery;
import org.zstack.tag.SystemTagCreator;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.function.Function;
import org.zstack.utils.logging.CLogger;

import javax.persistence.TypedQuery;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;

public class VirtualRouterManagerImpl extends AbstractService implements VirtualRouterManager,
        PrepareDbInitialValueExtensionPoint, L2NetworkCreateExtensionPoint,
        GlobalApiMessageInterceptor, AddExpandedQueryExtensionPoint {
	private final static CLogger logger = Utils.getLogger(VirtualRouterManagerImpl.class);

	private final static List<String> supportedL2NetworkTypes = new ArrayList<String>();
	private NetworkServiceProviderInventory virtualRouterProvider;
	private Map<String, VirtualRouterHypervisorBackend> hypervisorBackends = new HashMap<String, VirtualRouterHypervisorBackend>();
    private Map<String, Integer> vrParallelismDegrees = new ConcurrentHashMap<String, Integer>();

    private List<String> virtualRouterPostCreateFlows;
    private List<String> virtualRouterPostStartFlows;
    private List<String> virtualRouterPostRebootFlows;
    private List<String> virtualRouterPostDestroyFlows;
    private List<String> virtualRouterReconnectFlows;
    private FlowChainBuilder postCreateFlowsBuilder;
    private FlowChainBuilder postStartFlowsBuilder;
    private FlowChainBuilder postRebootFlowsBuilder;
    private FlowChainBuilder postDestroyFlowsBuilder;
    private FlowChainBuilder reconnectFlowsBuilder;

    private List<VirtualRouterPostCreateFlowExtensionPoint> postCreateFlowExtensionPoints;
    private List<VirtualRouterPostStartFlowExtensionPoint> postStartFlowExtensionPoints;
    private List<VirtualRouterPostRebootFlowExtensionPoint> postRebootFlowExtensionPoints;
    private List<VirtualRouterPostReconnectFlowExtensionPoint> postReconnectFlowExtensionPoints;
    private List<VirtualRouterPostDestroyFlowExtensionPoint> postDestroyFlowExtensionPoints;

	static {
		supportedL2NetworkTypes.add(L2NetworkConstant.L2_NO_VLAN_NETWORK_TYPE);
		supportedL2NetworkTypes.add(L2NetworkConstant.L2_VLAN_NETWORK_TYPE);
	}

	@Autowired
	private CloudBus bus;
	@Autowired
	private DatabaseFacade dbf;
	@Autowired
	private VirtualRouterProviderFactory providerFactory;
	@Autowired
	private PluginRegistry pluginRgty;
    @Autowired
    private AnsibleFacade asf;
    @Autowired
    private ErrorFacade errf;
    @Autowired
    private AccountManager acntMgr;
    @Autowired
    private ThreadFacade thdf;
    @Autowired
    private ApplianceVmFacade apvmf;

	@Override
    @MessageSafe
	public void handleMessage(Message msg) {
        if (msg instanceof APIMessage) {
            handleApiMessage((APIMessage) msg);
        } else {
            handleLocalMessage(msg);
        }
	}

	private void handleLocalMessage(Message msg) {
        if (msg instanceof CreateVirtualRouterVmMsg) {
            handle((CreateVirtualRouterVmMsg) msg);
        } else {
            bus.dealWithUnknownMessage(msg);
        }
    }

    private void handle(final CreateVirtualRouterVmMsg msg) {
        thdf.chainSubmit(new ChainTask(msg) {
            @Override
            public String getSyncSignature() {
                return String.format("create-vr-for-l3-%s", msg.getL3Network().getUuid());
            }

            @Override
            public void run(final SyncTaskChain chain) {
                createVirtualRouter(msg, new NoErrorCompletion(msg, chain) {
                    @Override
                    public void done() {
                        chain.next();
                    }
                });
            }

            @Override
            public String getName() {
                return getSyncSignature();
            }
        });
    }

    private void createVirtualRouter(final CreateVirtualRouterVmMsg msg, final NoErrorCompletion completion) {
        final L3NetworkInventory l3Network = msg.getL3Network();
        final VirtualRouterOfferingInventory offering = msg.getOffering();
        final CreateVirtualRouterVmReply reply = new CreateVirtualRouterVmReply();
        final String accountUuid = acntMgr.getOwnerAccountUuidOfResource(l3Network.getUuid());

        class newVirtualRouterJob {
            private void failAndReply(ErrorCode err) {
                reply.setError(err);
                bus.reply(msg, reply);
                completion.done();
            }

            private void openFirewall(ApplianceVmSpec aspec, String l3NetworkUuid, int port, ApplianceVmFirewallProtocol protocol) {
                ApplianceVmFirewallRuleInventory r = new ApplianceVmFirewallRuleInventory();
                r.setL3NetworkUuid(l3NetworkUuid);
                r.setStartPort(port);
                r.setEndPort(port);
                r.setProtocol(protocol.toString());
                aspec.getFirewallRules().add(r);
            }

            private void openAdditionalPorts(ApplianceVmSpec aspec, String mgmtNwUuid) {
                final List<String> tcpPorts = VirtualRouterGlobalProperty.TCP_PORTS_ON_MGMT_NIC;
                if (!tcpPorts.isEmpty()) {
                    List<Integer> ports = CollectionUtils.transformToList(tcpPorts, new Function<Integer, String>() {
                        @Override
                        public Integer call(String arg) {
                            return Integer.valueOf(arg);
                        }
                    });
                    for (int p : ports) {
                        openFirewall(aspec, mgmtNwUuid, p, ApplianceVmFirewallProtocol.tcp);
                    }
                }

                final List<String> udpPorts = VirtualRouterGlobalProperty.UDP_PORTS_ON_MGMT_NIC;
                if (!udpPorts.isEmpty()) {
                    List<Integer> ports = CollectionUtils.transformToList(udpPorts, new Function<Integer, String>() {
                        @Override
                        public Integer call(String arg) {
                            return Integer.valueOf(arg);
                        }
                    });
                    for (int p : ports) {
                        openFirewall(aspec, mgmtNwUuid, p, ApplianceVmFirewallProtocol.udp);
                    }
                }
            }

            void create() {
                List<String> neededService = l3Network.getNetworkServiceTypesFromProvider(new Callable<String>() {
                    @Override
                    public String call() {
                        SimpleQuery<NetworkServiceProviderVO> q = dbf.createQuery(NetworkServiceProviderVO.class);
                        q.select(NetworkServiceProviderVO_.uuid);
                        q.add(NetworkServiceProviderVO_.type, Op.EQ, msg.getProviderType());
                        return q.findValue();
                    }
                }.call());

                if (neededService.contains(NetworkServiceType.SNAT.toString()) && offering.getPublicNetworkUuid() == null) {
                    String err = String.format("L3Network[uuid:%s, name:%s] requires SNAT service, but default virtual router offering[uuid:%s, name:%s] doesn't have a public network", l3Network.getUuid(), l3Network.getName(), offering.getUuid(), offering.getName());
                    logger.warn(err);
                    failAndReply(errf.instantiateErrorCode(VirtualRouterErrors.NO_PUBLIC_NETWORK_IN_OFFERING, err));
                    return;
                }

                ImageVO imgvo = dbf.findByUuid(offering.getImageUuid(), ImageVO.class);

                final ApplianceVmSpec aspec = new ApplianceVmSpec();
                aspec.setSyncCreate(false);
                aspec.setTemplate(ImageInventory.valueOf(imgvo));
                aspec.setApplianceVmType(ApplianceVmType.valueOf(msg.getApplianceVmType()));
                aspec.setInstanceOffering(offering);
                aspec.setAccountUuid(accountUuid);
                aspec.setName(String.format("vrouter.l3.%s.%s", l3Network.getName(), l3Network.getUuid().substring(0, 6)));
                aspec.setInherentSystemTags(msg.getInherentSystemTags());
                aspec.setSshUsername(VirtualRouterGlobalConfig.SSH_USERNAME.value());
                aspec.setSshPort(VirtualRouterGlobalConfig.SSH_PORT.value(Integer.class));
                aspec.setAgentPort(msg.getApplianceVmAgentPort());

                L3NetworkInventory mgmtNw = L3NetworkInventory.valueOf(dbf.findByUuid(offering.getManagementNetworkUuid(), L3NetworkVO.class));
                ApplianceVmNicSpec mgmtNicSpec = new ApplianceVmNicSpec();
                mgmtNicSpec.setL3NetworkUuid(mgmtNw.getUuid());
                mgmtNicSpec.setMetaData(VirtualRouterNicMetaData.MANAGEMENT_NIC_MASK.toString());
                aspec.setManagementNic(mgmtNicSpec);

                String mgmtNwUuid = mgmtNw.getUuid();
                String pnwUuid;

                // NOTE: don't open 22 port here; 22 port is default opened on mgmt network in virtual router with restricted rules
                // open 22 here will cause a non-restricted rule to be added
                openFirewall(aspec, mgmtNwUuid, 7272, ApplianceVmFirewallProtocol.tcp);
                openAdditionalPorts(aspec, mgmtNwUuid);

                if (offering.getPublicNetworkUuid() != null && !offering.getManagementNetworkUuid().equals(offering.getPublicNetworkUuid())) {
                    L3NetworkInventory pnw = L3NetworkInventory.valueOf(dbf.findByUuid(offering.getPublicNetworkUuid(), L3NetworkVO.class));
                    ApplianceVmNicSpec pnicSpec = new ApplianceVmNicSpec();
                    pnicSpec.setL3NetworkUuid(pnw.getUuid());
                    pnicSpec.setMetaData(VirtualRouterNicMetaData.PUBLIC_NIC_MASK.toString());
                    aspec.getAdditionalNics().add(pnicSpec);
                    pnwUuid = pnicSpec.getL3NetworkUuid();
                    aspec.setDefaultRouteL3Network(pnw);
                } else {
                    // use management nic for both management and public
                    mgmtNicSpec.setMetaData(VirtualRouterNicMetaData.PUBLIC_AND_MANAGEMENT_NIC_MASK.toString());
                    pnwUuid = mgmtNwUuid;
                    aspec.setDefaultRouteL3Network(mgmtNw);
                }

                if (!l3Network.getUuid().equals(mgmtNwUuid) && !l3Network.getUuid().equals(pnwUuid)) {
                    if (neededService.contains(NetworkServiceType.SNAT.toString()) && !msg.isNotGatewayForGuestL3Network()) {
                        DebugUtils.Assert(!l3Network.getIpRanges().isEmpty(), String.format("how can l3Network[uuid:%s] doesn't have ip range", l3Network.getUuid()));
                        IpRangeInventory ipr = l3Network.getIpRanges().get(0);
                        ApplianceVmNicSpec nicSpec = new ApplianceVmNicSpec();
                        nicSpec.setL3NetworkUuid(l3Network.getUuid());
                        nicSpec.setAcquireOnNetwork(false);
                        nicSpec.setNetmask(ipr.getNetmask());
                        nicSpec.setIp(ipr.getGateway());
                        nicSpec.setGateway(ipr.getGateway());
                        aspec.getAdditionalNics().add(nicSpec);
                    } else {
                        ApplianceVmNicSpec nicSpec = new ApplianceVmNicSpec();
                        nicSpec.setL3NetworkUuid(l3Network.getUuid());
                        aspec.getAdditionalNics().add(nicSpec);
                    }
                }

                ApplianceVmNicSpec guestNicSpec = mgmtNicSpec.getL3NetworkUuid().equals(l3Network.getUuid()) ? mgmtNicSpec : CollectionUtils.find(aspec.getAdditionalNics(), new Function<ApplianceVmNicSpec, ApplianceVmNicSpec>() {
                    @Override
                    public ApplianceVmNicSpec call(ApplianceVmNicSpec arg) {
                        return arg.getL3NetworkUuid().equals(l3Network.getUuid()) ? arg : null;
                    }
                });

                guestNicSpec.setMetaData(guestNicSpec.getMetaData() == null ? VirtualRouterNicMetaData.GUEST_NIC_MASK.toString()
                        : String.valueOf(Integer.valueOf(guestNicSpec.getMetaData()) | VirtualRouterNicMetaData.GUEST_NIC_MASK));

                if (neededService.contains(NetworkServiceType.DHCP.toString())) {
                    openFirewall(aspec, l3Network.getUuid(), 68, ApplianceVmFirewallProtocol.udp);
                    openFirewall(aspec, l3Network.getUuid(), 67, ApplianceVmFirewallProtocol.udp);
                }
                if (neededService.contains(NetworkServiceType.DNS.toString())) {
                    openFirewall(aspec, l3Network.getUuid(), 53, ApplianceVmFirewallProtocol.udp);
                }

                logger.debug(String.format("unable to find running virtual for L3Network[name:%s, uuid:%s], is about to create a new one",  l3Network.getName(), l3Network.getUuid()));
                apvmf.createApplianceVm(aspec, new ReturnValueCompletion<ApplianceVmInventory>(completion) {
                    @Override
                    public void success(ApplianceVmInventory apvm) {
                        String paraDegree = VirtualRouterSystemTags.VR_OFFERING_PARALLELISM_DEGREE.getTokenByResourceUuid(offering.getUuid(), VirtualRouterSystemTags.PARALLELISM_DEGREE_TOKEN);

                        if (paraDegree != null) {
                            SystemTagCreator creator = VirtualRouterSystemTags.VR_PARALLELISM_DEGREE.newSystemTagCreator(apvm.getUuid());
                            creator.setTagByTokens(map(e(
                                    VirtualRouterSystemTags.PARALLELISM_DEGREE_TOKEN,
                                    paraDegree
                            )));
                            creator.create();
                        }

                        reply.setInventory(VirtualRouterVmInventory.valueOf(dbf.findByUuid(apvm.getUuid(), VirtualRouterVmVO.class)));
                        bus.reply(msg, reply);
                        completion.done();
                    }

                    @Override
                    public void fail(ErrorCode errorCode) {
                        failAndReply(errorCode);
                    }
                });
            }
        }

        new newVirtualRouterJob().create();
    }

    private void handleApiMessage(APIMessage msg) {
        if (msg instanceof APISearchVirtualRouterOffingMsg) {
            handle((APISearchVirtualRouterOffingMsg)msg);
        } else if (msg instanceof APIGetVirtualRouterOfferingMsg) {
            handle((APIGetVirtualRouterOfferingMsg) msg);
        } else if (msg instanceof APIUpdateVirtualRouterOfferingMsg) {
            handle((APIUpdateVirtualRouterOfferingMsg) msg);
        } else {
            bus.dealWithUnknownMessage(msg);
        }
    }

    private void handle(APIUpdateVirtualRouterOfferingMsg msg) {
        VirtualRouterOfferingVO ovo = dbf.findByUuid(msg.getUuid(), VirtualRouterOfferingVO.class);
        boolean updated = false;
        if (msg.getName() != null) {
            ovo.setName(msg.getName());
            updated = true;
        }
        if (msg.getDescription() != null) {
            ovo.setDescription(msg.getDescription());
            updated = true;
        }
        if (msg.getImageUuid() != null) {
            ovo.setImageUuid(msg.getImageUuid());
            updated = true;
        }

        if (updated) {
            ovo = dbf.updateAndRefresh(ovo);
        }

        if (msg.getIsDefault() != null) {
            DefaultVirtualRouterOfferingSelector selector = new DefaultVirtualRouterOfferingSelector();
            selector.setZoneUuid(ovo.getZoneUuid());
            selector.setPreferToBeDefault(msg.getIsDefault());
            selector.setOfferingUuid(ovo.getUuid());
            selector.selectDefaultOffering();
        }

        APIUpdateInstanceOfferingEvent evt = new APIUpdateInstanceOfferingEvent(msg.getId());
        evt.setInventory(VirtualRouterOfferingInventory.valueOf(dbf.reload(ovo)));
        bus.publish(evt);
    }

    private void handle(APIGetVirtualRouterOfferingMsg msg) {
        GetQuery q = new GetQuery();
        String res = q.getAsString(msg, VirtualRouterOfferingInventory.class);
        APIGetVirtualRouterOfferingReply reply = new APIGetVirtualRouterOfferingReply();
        reply.setInventory(res);
        bus.reply(msg, reply);
    }

    private void handle(APISearchVirtualRouterOffingMsg msg) {
        SearchQuery<VirtualRouterOfferingInventory> q = SearchQuery.create(msg, VirtualRouterOfferingInventory.class);
        APISearchVirtualRouterOffingReply reply = new APISearchVirtualRouterOffingReply();
        String res = q.listAsString();
        reply.setContent(res);
        bus.reply(msg, reply);
    }

    @Override
	public String getId() {
		return bus.makeLocalServiceId(VirtualRouterConstant.SERVICE_ID);
	}

	@Override
	public boolean start() {
		populateExtensions();
        deployAnsible();
		buildWorkFlowBuilder();

        VirtualRouterSystemTags.VR_PARALLELISM_DEGREE.installLifeCycleListener(new SystemTagLifeCycleListener() {
            @Override
            public void tagCreated(SystemTagInventory tag) {
                if (VirtualRouterSystemTags.VR_PARALLELISM_DEGREE.isMatch(tag.getTag())) {
                    String value = VirtualRouterSystemTags.VR_PARALLELISM_DEGREE.getTokenByTag(tag.getTag(), VirtualRouterSystemTags.PARALLELISM_DEGREE_TOKEN);
                    vrParallelismDegrees.put(tag.getResourceUuid(), Integer.valueOf(value));
                }
            }

            @Override
            public void tagDeleted(SystemTagInventory tag) {
                if (VirtualRouterSystemTags.VR_PARALLELISM_DEGREE.isMatch(tag.getTag())) {
                    vrParallelismDegrees.remove(tag.getResourceUuid());
                }
            }

            @Override
            public void tagUpdated(SystemTagInventory old, SystemTagInventory newTag) {
            }
        });
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

	public void prepareDbInitialValue() {
		SimpleQuery<NetworkServiceProviderVO> query = dbf.createQuery(NetworkServiceProviderVO.class);
		query.add(NetworkServiceProviderVO_.type, Op.EQ, VirtualRouterConstant.VIRTUAL_ROUTER_PROVIDER_TYPE);
		NetworkServiceProviderVO rpvo = query.find();
		if (rpvo != null) {
			virtualRouterProvider = NetworkServiceProviderInventory.valueOf(rpvo);
			return;
		}

		NetworkServiceProviderVO vo = new NetworkServiceProviderVO();
        vo.setUuid(Platform.getUuid());
		vo.setName(VirtualRouterConstant.VIRTUAL_ROUTER_PROVIDER_TYPE);
		vo.setDescription("zstack virtual router network service provider");
		vo.getNetworkServiceTypes().add(NetworkServiceType.DHCP.toString());
		vo.getNetworkServiceTypes().add(NetworkServiceType.DNS.toString());
		vo.getNetworkServiceTypes().add(NetworkServiceType.SNAT.toString());
		vo.getNetworkServiceTypes().add(NetworkServiceType.PortForwarding.toString());
        vo.getNetworkServiceTypes().add(EipConstant.EIP_NETWORK_SERVICE_TYPE);
        vo.getNetworkServiceTypes().add(LoadBalancerConstants.LB_NETWORK_SERVICE_TYPE_STRING);
		vo.setType(VirtualRouterConstant.VIRTUAL_ROUTER_PROVIDER_TYPE);
		vo = dbf.persistAndRefresh(vo);
		virtualRouterProvider = NetworkServiceProviderInventory.valueOf(vo);
	}

	private void populateExtensions() {
		for (VirtualRouterHypervisorBackend extp : pluginRgty.getExtensionList(VirtualRouterHypervisorBackend.class)) {
			VirtualRouterHypervisorBackend old = hypervisorBackends.get(extp.getVirtualRouterSupportedHypervisorType().toString());
            if (old != null) {
                throw new CloudRuntimeException(String.format("duplicate VirtualRouterHypervisorBackend[%s, %s] for type[%s]",
                        extp.getClass().getName(), old.getClass().getName(), old.getVirtualRouterSupportedHypervisorType()));
            }
			hypervisorBackends.put(extp.getVirtualRouterSupportedHypervisorType().toString(), extp);
		}

		postCreateFlowExtensionPoints = pluginRgty.getExtensionList(VirtualRouterPostCreateFlowExtensionPoint.class);
        postStartFlowExtensionPoints = pluginRgty.getExtensionList(VirtualRouterPostStartFlowExtensionPoint.class);
        postRebootFlowExtensionPoints = pluginRgty.getExtensionList(VirtualRouterPostRebootFlowExtensionPoint.class);
        postReconnectFlowExtensionPoints = pluginRgty.getExtensionList(VirtualRouterPostReconnectFlowExtensionPoint.class);
        postDestroyFlowExtensionPoints = pluginRgty.getExtensionList(VirtualRouterPostDestroyFlowExtensionPoint.class);
	}

	private NetworkServiceProviderVO getRouterVO() {
		SimpleQuery<NetworkServiceProviderVO> query = dbf.createQuery(NetworkServiceProviderVO.class);
		query.add(NetworkServiceProviderVO_.type, Op.EQ, VirtualRouterConstant.VIRTUAL_ROUTER_PROVIDER_TYPE);
		return query.find();
	}

	@Override
	public void beforeCreateL2Network(APICreateL2NetworkMsg msg) throws NetworkException {
	}

	@Override
	public void afterCreateL2Network(L2NetworkInventory l2Network) {
		if (!supportedL2NetworkTypes.contains(l2Network.getType())) {
			return;
		}

		NetworkServiceProviderVO vo = getRouterVO();
		NetworkServiceProvider router = providerFactory.getNetworkServiceProvider(vo);
		try {
			router.attachToL2Network(l2Network, null);
		} catch (NetworkException e) {
			String err = String.format("unable to attach network service provider[uuid:%s, name:%s, type:%s] to l2network[uuid:%s, name:%s, type:%s], %s",
					vo.getUuid(), vo.getName(), vo.getType(), l2Network.getUuid(), l2Network.getName(), l2Network.getType(), e.getMessage());
			logger.warn(err, e);
			return;
		}

		NetworkServiceProviderL2NetworkRefVO ref = new NetworkServiceProviderL2NetworkRefVO();
		ref.setNetworkServiceProviderUuid(vo.getUuid());
		ref.setL2NetworkUuid(l2Network.getUuid());
		dbf.persist(ref);
		String info = String.format("successfully attach network service provider[uuid:%s, name:%s, type:%s] to l2network[uuid:%s, name:%s, type:%s]",
				vo.getUuid(), vo.getName(), vo.getType(), l2Network.getUuid(), l2Network.getName(), l2Network.getType());
		logger.debug(info);
	}

	@Override
	public NetworkServiceProviderInventory getVirtualRouterProvider() {
		return virtualRouterProvider;
	}

    private void deployAnsible() {
        if (CoreGlobalProperty.UNIT_TEST_ON) {
            return;
        }

        asf.deployModule(VirtualRouterConstant.ANSIBLE_MODULE_PATH, VirtualRouterConstant.ANSIBLE_PLAYBOOK_NAME);
    }

	@Override
	public VirtualRouterHypervisorBackend getHypervisorBackend(HypervisorType hypervisorType) {
		VirtualRouterHypervisorBackend b = hypervisorBackends.get(hypervisorType.toString());
		if (b == null) {
			throw new CloudRuntimeException(String.format("unable to find VirtualRouterHypervisorBackend for hypervisorType[%s]", hypervisorType));
		}
		return b;
	}

	@Override
	public String buildUrl(String mgmtNicIp, String subPath) {
        UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
        ub.scheme(VirtualRouterGlobalProperty.AGENT_URL_SCHEME);

        if (CoreGlobalProperty.UNIT_TEST_ON) {
            ub.host("localhost");
        } else {
            ub.host(mgmtNicIp);
        }

        ub.port(VirtualRouterGlobalProperty.AGENT_PORT);
        if (!"".equals(VirtualRouterGlobalProperty.AGENT_URL_ROOT_PATH)) {
            ub.path(VirtualRouterGlobalProperty.AGENT_URL_ROOT_PATH);
        }
        ub.path(subPath);

        return ub.build().toUriString();
    }

	private void buildWorkFlowBuilder() {
        postCreateFlowsBuilder = FlowChainBuilder.newBuilder().setFlowClassNames(virtualRouterPostCreateFlows).construct();
        postStartFlowsBuilder = FlowChainBuilder.newBuilder().setFlowClassNames(virtualRouterPostStartFlows).construct();
        postRebootFlowsBuilder = FlowChainBuilder.newBuilder().setFlowClassNames(virtualRouterPostRebootFlows).construct();
        postDestroyFlowsBuilder = FlowChainBuilder.newBuilder().setFlowClassNames(virtualRouterPostDestroyFlows).construct();
        reconnectFlowsBuilder = FlowChainBuilder.newBuilder().setFlowClassNames(virtualRouterReconnectFlows).construct();
	}

    @Override
    public List<String> selectL3NetworksNeedingSpecificNetworkService(List<String> candidate, NetworkServiceType nsType) {
        if (candidate.isEmpty()) {
            return new ArrayList<>(0);
        }

        SimpleQuery<NetworkServiceL3NetworkRefVO> q = dbf.createQuery(NetworkServiceL3NetworkRefVO.class);
        q.select(NetworkServiceL3NetworkRefVO_.l3NetworkUuid);
        q.add(NetworkServiceL3NetworkRefVO_.l3NetworkUuid, Op.IN, candidate);
        q.add(NetworkServiceL3NetworkRefVO_.networkServiceType, Op.EQ, nsType.toString());
        // no need to specify provider type, L3 networks identified by candidates are served by virtual router or vyos
        return q.listValue();
    }

    @Override
    public boolean isL3NetworkNeedingNetworkServiceByVirtualRouter(String l3Uuid, String nsType) {
        SimpleQuery<NetworkServiceL3NetworkRefVO> q = dbf.createQuery(NetworkServiceL3NetworkRefVO.class);
        q.add(NetworkServiceL3NetworkRefVO_.l3NetworkUuid, Op.EQ, l3Uuid);
        q.add(NetworkServiceL3NetworkRefVO_.networkServiceType, Op.EQ, nsType);
        // no need to specify provider type, L3 networks identified by candidates are served by virtual router or vyos
        return q.isExists();
    }

    private void acquireVirtualRouterVmInternal(VirtualRouterStruct struct,  final ReturnValueCompletion<VirtualRouterVmInventory> completion) {
        final L3NetworkInventory l3Nw = struct.getL3Network();
        final VirtualRouterOfferingValidator validator = struct.getOfferingValidator();
        final VirtualRouterVmSelector selector = struct.getVirtualRouterVmSelector();

        VirtualRouterVmInventory vr = new Callable<VirtualRouterVmInventory>() {
            @Transactional(readOnly = true)
            private VirtualRouterVmVO findVR() {
                String sql = "select vr from VirtualRouterVmVO vr, VmNicVO nic where vr.uuid = nic.vmInstanceUuid and nic.l3NetworkUuid = :l3Uuid and nic.metaData in (:guestMeta)";
                TypedQuery<VirtualRouterVmVO> q = dbf.getEntityManager().createQuery(sql, VirtualRouterVmVO.class);
                q.setParameter("l3Uuid", l3Nw.getUuid());
                q.setParameter("guestMeta", VirtualRouterNicMetaData.GUEST_NIC_MASK_STRING_LIST);
                List<VirtualRouterVmVO> vrs = q.getResultList();

                if (vrs.isEmpty()) {
                    return null;
                }

                if (selector == null) {
                    return findTheEarliestOne(vrs);
                } else {
                    return selector.select(vrs);
                }
            }

            private VirtualRouterVmVO findTheEarliestOne(List<VirtualRouterVmVO> vrs) {
                VirtualRouterVmVO vr = null;
                for (VirtualRouterVmVO v : vrs) {
                    if (vr == null) {
                        vr = v;
                        continue;
                    }

                    vr = vr.getCreateDate().before(v.getCreateDate()) ? vr : v;
                }
                return vr;
            }

            @Override
            public VirtualRouterVmInventory call() {
                VirtualRouterVmVO vr = findVR();
                if (vr != null && !VmInstanceState.Running.equals(vr.getState())) {
                    throw new OperationFailureException(errf.stringToOperationError(
                            String.format("virtual router[uuid:%s] for l3 network[uuid:%s] is not in Running state, current state is %s. We don't have HA feature now(it's coming soon), please restart it from UI and then try starting this vm again",
                                    vr.getUuid(), l3Nw.getUuid(), vr.getState())
                    ));
                }

                return vr == null ? null : new VirtualRouterVmInventory(vr);
            }
        }.call();

        if (vr != null) {
            completion.success(vr);
            return;
        }

        List<VirtualRouterOfferingInventory> offerings = findOfferingByGuestL3Network(l3Nw);
        if (offerings == null) {
            String err = String.format("unable to find a virtual router offering for l3Network[uuid:%s] in zone[uuid:%s], please at least create a default virtual router offering in that zone",
                    l3Nw.getUuid(), l3Nw.getZoneUuid());
            logger.warn(err);
            completion.fail(errf.instantiateErrorCode(VirtualRouterErrors.NO_DEFAULT_OFFERING, err));
            return;
        }

        if (struct.getVirtualRouterOfferingSelector() == null) {
            struct.setVirtualRouterOfferingSelector(new VirtualRouterOfferingSelector() {
                @Override
                public VirtualRouterOfferingInventory selectVirtualRouterOffering(L3NetworkInventory l3, List<VirtualRouterOfferingInventory> candidates) {
                    Optional<VirtualRouterOfferingInventory> opt = candidates.stream().filter(VirtualRouterOfferingInventory::isDefault).findAny();
                    return !opt.isPresent() ? candidates.get(0) : opt.get();
                }
            });
        }

        VirtualRouterOfferingInventory offering = struct.getVirtualRouterOfferingSelector().selectVirtualRouterOffering(l3Nw, offerings);

        if (validator != null) {
            validator.validate(offering);
        }

        CreateVirtualRouterVmMsg msg = new CreateVirtualRouterVmMsg();
        msg.setNotGatewayForGuestL3Network(struct.isNotGatewayForGuestL3Network());
        msg.setL3Network(l3Nw);
        msg.setOffering(offering);
        msg.setInherentSystemTags(struct.getInherentSystemTags());
        msg.setProviderType(struct.getProviderType());
        msg.setApplianceVmType(struct.getApplianceVmType());
        msg.setApplianceVmAgentPort(struct.getApplianceVmAgentPort());
        bus.makeTargetServiceIdByResourceUuid(msg, VirtualRouterConstant.SERVICE_ID, l3Nw.getUuid());
        bus.send(msg, new CloudBusCallBack(completion) {
            @Override
            public void run(MessageReply reply) {
                if (!reply.isSuccess()) {
                    completion.fail(reply.getError());
                } else {
                    completion.success(((CreateVirtualRouterVmReply) reply).getInventory());
                }
            }
        });
    }

    @Override
    public void acquireVirtualRouterVm(VirtualRouterStruct struct, final ReturnValueCompletion<VirtualRouterVmInventory> completion) {
        //TODO: find a way to remove the GLock
        final GLock lock = new GLock(String.format("glock-vr-l3-%s", struct.getL3Network().getUuid()), TimeUnit.HOURS.toSeconds(1));
        lock.setSeparateThreadEnabled(false);
        lock.lock();
        acquireVirtualRouterVmInternal(struct, new ReturnValueCompletion<VirtualRouterVmInventory>(completion) {
            @Override
            public void success(VirtualRouterVmInventory returnValue) {
                lock.unlock();
                completion.success(returnValue);
            }

            @Override
            public void fail(ErrorCode errorCode) {
                lock.unlock();
                completion.fail(errorCode);
            }
        });
    }

    @Override
    @Transactional(readOnly = true)
    public VirtualRouterVmInventory getVirtualRouterVm(L3NetworkInventory l3Nw) {
        String sql = "select vm from VirtualRouterVmVO vm, VmNicVO nic where vm.uuid = nic.vmInstanceUuid and nic.l3NetworkUuid = :l3Uuid and nic.metaData in (:guestMeta)";
        TypedQuery<VirtualRouterVmVO> q = dbf.getEntityManager().createQuery(sql, VirtualRouterVmVO.class);
        q.setParameter("l3Uuid", l3Nw.getUuid());
        q.setParameter("guestMeta", VirtualRouterNicMetaData.GUEST_NIC_MASK_STRING_LIST);
        List<VirtualRouterVmVO> vos = q.getResultList();
        if (vos.isEmpty()) {
            return null;
        }
        return VirtualRouterVmInventory.valueOf(vos.get(0));
    }

    @Override
    public boolean isVirtualRouterRunningForL3Network(String l3Uuid) {
        return countVirtualRouterRunningForL3Network(l3Uuid) > 0;
    }

    @Override
    @Transactional(readOnly = true)
    public long countVirtualRouterRunningForL3Network(String l3Uuid) {
        String sql = "select count(vm) from ApplianceVmVO vm, VmNicVO nic where vm.uuid = nic.vmInstanceUuid and vm.state = :vmState and nic.l3NetworkUuid = :l3Uuid and nic.metaData in (:guestMeta)";
        TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class);
        q.setParameter("l3Uuid", l3Uuid);
        q.setParameter("vmState", VmInstanceState.Running);
        q.setParameter("guestMeta", VirtualRouterNicMetaData.GUEST_NIC_MASK_STRING_LIST);
        return q.getSingleResult();
    }

    @Override
    @Transactional(readOnly = true)
    public boolean isVirtualRouterForL3Network(String l3Uuid) {
        String sql = "select vm from ApplianceVmVO vm, VmNicVO nic where vm.uuid = nic.vmInstanceUuid and nic.l3NetworkUuid = :l3Uuid and nic.metaData in (:guestMeta)";
        TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class);
        q.setParameter("l3Uuid", l3Uuid);
        q.setParameter("guestMeta", VirtualRouterNicMetaData.GUEST_NIC_MASK_STRING_LIST);
        Long count = q.getSingleResult();
        return count > 0;
    }

    @Transactional(readOnly = true)
    private List<VirtualRouterOfferingInventory> findOfferingByGuestL3Network(L3NetworkInventory guestL3) {
        String sql = "select offering from VirtualRouterOfferingVO offering, SystemTagVO stag where offering.uuid = stag.resourceUuid and stag.resourceType = :type and offering.zoneUuid = :zoneUuid and stag.tag = :tag";
        TypedQuery<VirtualRouterOfferingVO> q = dbf.getEntityManager().createQuery(sql, VirtualRouterOfferingVO.class);
        q.setParameter("type", InstanceOfferingVO.class.getSimpleName());
        q.setParameter("zoneUuid", guestL3.getZoneUuid());
        q.setParameter("tag", VirtualRouterSystemTags.VR_OFFERING_GUEST_NETWORK.instantiateTag(map(e(VirtualRouterSystemTags.VR_OFFERING_GUEST_NETWORK_TOKEN, guestL3.getUuid()))));
        List<VirtualRouterOfferingVO> vos = q.getResultList();
        if (!vos.isEmpty()) {
            return VirtualRouterOfferingInventory.valueOf1(vos);
        }

        sql ="select offering from VirtualRouterOfferingVO offering where offering.zoneUuid = :zoneUuid";
        q = dbf.getEntityManager().createQuery(sql, VirtualRouterOfferingVO.class);
        q.setParameter("zoneUuid", guestL3.getZoneUuid());
        vos = q.getResultList();
        return vos.isEmpty() ? null : VirtualRouterOfferingInventory.valueOf1(vos);
    }

    @Override
    public List<Flow> getPostCreateFlows() {
        List<Flow> flows = new ArrayList<>();
        flows.addAll(postCreateFlowsBuilder.getFlows());
        flows.addAll(postCreateFlowExtensionPoints.stream().map(VirtualRouterPostCreateFlowExtensionPoint::virtualRouterPostCreateFlow).collect(Collectors.toList()));
        return flows;
    }

    @Override
    public List<Flow> getPostStartFlows() {
        List<Flow> flows = new ArrayList<>();
        flows.addAll(postStartFlowsBuilder.getFlows());
        flows.addAll(postStartFlowExtensionPoints.stream().map(VirtualRouterPostStartFlowExtensionPoint::virtualRouterPostStartFlow).collect(Collectors.toList()));
        return flows;
    }

    @Override
    public List<Flow> getPostRebootFlows() {
        List<Flow> flows = new ArrayList<>();
        flows.addAll(postRebootFlowsBuilder.getFlows());
        flows.addAll(postRebootFlowExtensionPoints.stream().map(VirtualRouterPostRebootFlowExtensionPoint::virtualRouterPostRebootFlow).collect(Collectors.toList()));
        return flows;
    }

    @Override
    public List<Flow> getPostStopFlows() {
        return null;
    }

    @Override
    public List<Flow> getPostMigrateFlows() {
        return null;
    }

    @Override
    public List<Flow> getPostDestroyFlows() {
        List<Flow> flows = new ArrayList<>();
        flows.addAll(postDestroyFlowsBuilder.getFlows());
        flows.addAll(postDestroyFlowExtensionPoints.stream().map(VirtualRouterPostDestroyFlowExtensionPoint::virtualRouterPostDestroyFlow).collect(Collectors.toList()));
        return flows;
    }

    @Override
    public FlowChain getReconnectFlowChain() {
        FlowChain chain = reconnectFlowsBuilder.build();
        for (VirtualRouterPostReconnectFlowExtensionPoint ext : postReconnectFlowExtensionPoints) {
            chain.then(ext.virtualRouterPostReconnectFlow());
        }
        return chain;
    }

    @Override
    public int getParallelismDegree(String vrUuid) {
        Integer degree = vrParallelismDegrees.get(vrUuid);
        return degree == null ? VirtualRouterGlobalConfig.COMMANDS_PARALELLISM_DEGREE.value(Integer.class) : degree;
    }

    public void setVirtualRouterPostStartFlows(List<String> virtualRouterPostStartFlows) {
        this.virtualRouterPostStartFlows = virtualRouterPostStartFlows;
    }

    public void setVirtualRouterPostRebootFlows(List<String> virtualRouterPostRebootFlows) {
        this.virtualRouterPostRebootFlows = virtualRouterPostRebootFlows;
    }

    public void setVirtualRouterPostDestroyFlows(List<String> virtualRouterPostDestroyFlows) {
        this.virtualRouterPostDestroyFlows = virtualRouterPostDestroyFlows;
    }

    public void setVirtualRouterPostCreateFlows(List<String> virtualRouterPostCreateFlows) {
        this.virtualRouterPostCreateFlows = virtualRouterPostCreateFlows;
    }

    public void setVirtualRouterReconnectFlows(List<String> virtualRouterReconnectFlows) {
        this.virtualRouterReconnectFlows = virtualRouterReconnectFlows;
    }

    @Override
    public List<Class> getMessageClassToIntercept() {
        List<Class> classes = new ArrayList<Class>();
        classes.add(APIAttachNetworkServiceToL3NetworkMsg.class);
        return classes;
    }

    @Override
    public InterceptorPosition getPosition() {
        return InterceptorPosition.END;
    }

    @Override
    public APIMessage intercept(APIMessage msg) throws ApiMessageInterceptionException {
        if (msg instanceof APIAttachNetworkServiceToL3NetworkMsg) {
            validate((APIAttachNetworkServiceToL3NetworkMsg) msg);
        }
        return msg;
    }

    private void validate(APIAttachNetworkServiceToL3NetworkMsg msg) {
        List<String> services = msg.getNetworkServices().get(virtualRouterProvider.getUuid());
        if (services == null) {
            return;
        }

        boolean snat = false;
        boolean portForwarding = false;
        boolean eip = false;

        SimpleQuery<NetworkServiceL3NetworkRefVO> q = dbf.createQuery(NetworkServiceL3NetworkRefVO.class);
        q.add(NetworkServiceL3NetworkRefVO_.l3NetworkUuid, Op.EQ, msg.getL3NetworkUuid());
        List<NetworkServiceL3NetworkRefVO> refs = q.list();
        for (NetworkServiceL3NetworkRefVO ref : refs) {
            if (ref.getNetworkServiceType().equals(NetworkServiceType.SNAT.toString())) {
                snat = true;
            }
        }

        for (String s : services) {
            if (NetworkServiceType.PortForwarding.toString().equals(s)) {
                portForwarding = true;
            }
            if (NetworkServiceType.SNAT.toString().equals(s)) {
                snat = true;
            }
            if (EipConstant.EIP_NETWORK_SERVICE_TYPE.equals(s)) {
                eip = true;
            }
        }

        if (!snat && eip) {
            throw new ApiMessageInterceptionException(errf.stringToInvalidArgumentError(
                    String.format("failed tot attach virtual router network services to l3Network[uuid:%s]. When eip is selected, snat must be selected too", msg.getL3NetworkUuid())
            ));
        }

        if (!snat && portForwarding) {
            throw new ApiMessageInterceptionException(errf.stringToInvalidArgumentError(
                    String.format("failed tot attach virtual router network services to l3Network[uuid:%s]. When port forwarding is selected, snat must be selected too", msg.getL3NetworkUuid())
            ));
        }
    }

    @Override
    public List<ExpandedQueryStruct> getExpandedQueryStructs() {
        List<ExpandedQueryStruct> structs = new ArrayList<ExpandedQueryStruct>();

        ExpandedQueryStruct struct = new ExpandedQueryStruct();
        struct.setExpandedField("virtualRouterEipRef");
        struct.setExpandedInventoryKey("virtualRouterVmUuid");
        struct.setHidden(true);
        struct.setForeignKey("uuid");
        struct.setInventoryClass(VirtualRouterEipRefInventory.class);
        struct.setInventoryClassToExpand(ApplianceVmInventory.class);
        structs.add(struct);

        struct = new ExpandedQueryStruct();
        struct.setExpandedField("virtualRouterVipRef");
        struct.setExpandedInventoryKey("virtualRouterVmUuid");
        struct.setHidden(true);
        struct.setForeignKey("uuid");
        struct.setInventoryClass(VirtualRouterVipInventory.class);
        struct.setInventoryClassToExpand(ApplianceVmInventory.class);
        structs.add(struct);

        struct = new ExpandedQueryStruct();
        struct.setExpandedField("virtualRouterPortforwardingRef");
        struct.setExpandedInventoryKey("virtualRouterVmUuid");
        struct.setHidden(true);
        struct.setForeignKey("uuid");
        struct.setInventoryClass(VirtualRouterPortForwardingRuleRefInventory.class);
        struct.setInventoryClassToExpand(ApplianceVmInventory.class);
        structs.add(struct);

        struct = new ExpandedQueryStruct();
        struct.setExpandedField("virtualRouterOffering");
        struct.setExpandedInventoryKey("uuid");
        struct.setForeignKey("instanceOfferingUuid");
        struct.setInventoryClass(VirtualRouterOfferingInventory.class);
        struct.setInventoryClassToExpand(ApplianceVmInventory.class);
        struct.setSuppressedInventoryClass(InstanceOfferingInventory.class);
        structs.add(struct);

        return structs;
    }

    @Override
    public List<ExpandedQueryAliasStruct> getExpandedQueryAliasesStructs() {
        List<ExpandedQueryAliasStruct> aliases = new ArrayList<ExpandedQueryAliasStruct>();

        ExpandedQueryAliasStruct as = new ExpandedQueryAliasStruct();
        as.setInventoryClass(ApplianceVmInventory.class);
        as.setAlias("eip");
        as.setExpandedField("virtualRouterEipRef.eip");
        aliases.add(as);

        as = new ExpandedQueryAliasStruct();
        as.setInventoryClass(ApplianceVmInventory.class);
        as.setAlias("vip");
        as.setExpandedField("virtualRouterVipRef.vip");
        aliases.add(as);

        as = new ExpandedQueryAliasStruct();
        as.setInventoryClass(ApplianceVmInventory.class);
        as.setAlias("portForwarding");
        as.setExpandedField("virtualRouterPortforwardingRef.portForwarding");
        aliases.add(as);
        return aliases;
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2beta1/dlp.proto

namespace Google\Cloud\Dlp\V2beta1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Specifies the location of a finding within its source item.
 *
 * Generated from protobuf message google.privacy.dlp.v2beta1.Location
 */
class Location extends \Google\Protobuf\Internal\Message
{
    /**
     * Zero-based byte offsets within a content item.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.Range byte_range = 1;
     */
    private $byte_range = null;
    /**
     * Character offsets within a content item, included when content type
     * is a text. Default charset assumed to be UTF-8.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.Range codepoint_range = 2;
     */
    private $codepoint_range = null;
    /**
     * Location within an image's pixels.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2beta1.ImageLocation image_boxes = 3;
     */
    private $image_boxes;
    /**
     * Key of the finding.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.RecordKey record_key = 4;
     */
    private $record_key = null;
    /**
     * Field id of the field containing the finding.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.FieldId field_id = 5;
     */
    private $field_id = null;
    /**
     * Location within a `ContentItem.Table`.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.TableLocation table_location = 6;
     */
    private $table_location = null;

    public function __construct() {
        \GPBMetadata\Google\Privacy\Dlp\V2Beta1\Dlp::initOnce();
        parent::__construct();
    }

    /**
     * Zero-based byte offsets within a content item.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.Range byte_range = 1;
     * @return \Google\Cloud\Dlp\V2beta1\Range
     */
    public function getByteRange()
    {
        return $this->byte_range;
    }

    /**
     * Zero-based byte offsets within a content item.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.Range byte_range = 1;
     * @param \Google\Cloud\Dlp\V2beta1\Range $var
     * @return $this
     */
    public function setByteRange($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\Range::class);
        $this->byte_range = $var;

        return $this;
    }

    /**
     * Character offsets within a content item, included when content type
     * is a text. Default charset assumed to be UTF-8.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.Range codepoint_range = 2;
     * @return \Google\Cloud\Dlp\V2beta1\Range
     */
    public function getCodepointRange()
    {
        return $this->codepoint_range;
    }

    /**
     * Character offsets within a content item, included when content type
     * is a text. Default charset assumed to be UTF-8.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.Range codepoint_range = 2;
     * @param \Google\Cloud\Dlp\V2beta1\Range $var
     * @return $this
     */
    public function setCodepointRange($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\Range::class);
        $this->codepoint_range = $var;

        return $this;
    }

    /**
     * Location within an image's pixels.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2beta1.ImageLocation image_boxes = 3;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getImageBoxes()
    {
        return $this->image_boxes;
    }

    /**
     * Location within an image's pixels.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2beta1.ImageLocation image_boxes = 3;
     * @param \Google\Cloud\Dlp\V2beta1\ImageLocation[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setImageBoxes($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dlp\V2beta1\ImageLocation::class);
        $this->image_boxes = $arr;

        return $this;
    }

    /**
     * Key of the finding.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.RecordKey record_key = 4;
     * @return \Google\Cloud\Dlp\V2beta1\RecordKey
     */
    public function getRecordKey()
    {
        return $this->record_key;
    }

    /**
     * Key of the finding.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.RecordKey record_key = 4;
     * @param \Google\Cloud\Dlp\V2beta1\RecordKey $var
     * @return $this
     */
    public function setRecordKey($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\RecordKey::class);
        $this->record_key = $var;

        return $this;
    }

    /**
     * Field id of the field containing the finding.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.FieldId field_id = 5;
     * @return \Google\Cloud\Dlp\V2beta1\FieldId
     */
    public function getFieldId()
    {
        return $this->field_id;
    }

    /**
     * Field id of the field containing the finding.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.FieldId field_id = 5;
     * @param \Google\Cloud\Dlp\V2beta1\FieldId $var
     * @return $this
     */
    public function setFieldId($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\FieldId::class);
        $this->field_id = $var;

        return $this;
    }

    /**
     * Location within a `ContentItem.Table`.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.TableLocation table_location = 6;
     * @return \Google\Cloud\Dlp\V2beta1\TableLocation
     */
    public function getTableLocation()
    {
        return $this->table_location;
    }

    /**
     * Location within a `ContentItem.Table`.
     *
     * Generated from protobuf field .google.privacy.dlp.v2beta1.TableLocation table_location = 6;
     * @param \Google\Cloud\Dlp\V2beta1\TableLocation $var
     * @return $this
     */
    public function setTableLocation($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\TableLocation::class);
        $this->table_location = $var;

        return $this;
    }

}


text:
package com.helen.obfuscatordemo;

import com.helen.obfuscator.ObfuscateKeepThisField;

public class TestAnnotationKeepThisField {

    public String sName;
    public static String sSName;
    private int iValue;
    @ObfuscateKeepThisField
    private static int iSValue;
    @ObfuscateKeepThisField
    private void tFunc(){
    }

    public boolean isbValue() {
        return bValue;
    }

    public void setbValue(boolean bValue) {
        this.bValue = bValue;
    }

    protected  boolean bValue;

    public String getsName() {
        return sName;
    }

    public void setsName(String sName) {
        this.sName = sName;
    }

    public static String getsSName() {
        return sSName;
    }

    public static void setsSName(String sSName) {
        TestAnnotationKeepThisField.sSName = sSName;
    }

    public int getiValue() {
        return iValue;
    }

    public void setiValue(int iValue) {
        this.iValue = iValue;
    }

    public static int getiSValue() {
        return iSValue;
    }

    public static void setiSValue(int iSValue) {
        TestAnnotationKeepThisField.iSValue = iSValue;
    }
}


text:
require "test_helper"

class StatisticalDataSetTest < ActiveSupport::TestCase
  should_allow_inline_attachments

  test "should include the Edition::HasDocumentCollections behaviour" do
    assert StatisticalDataSet.ancestors.include?(Edition::HasDocumentCollections)
  end

  test "specifically limit access" do
    data_set = build(:statistical_data_set, access_limited: true)
    assert data_set.access_limited?
  end

  test "specifically do not limit access" do
    data_set = build(:statistical_data_set, access_limited: false)
    assert_not data_set.access_limited?
  end

  test "limit access by default" do
    data_set = build(:statistical_data_set)
    assert data_set.access_limited?
  end

  test "search_format_types tags the data set as a statistical-data-set and publicationesque-statistics" do
    statistical_data_set = build(:statistical_data_set)
    assert statistical_data_set.search_format_types.include?("statistical-data-set")
    assert statistical_data_set.search_format_types.include?("publicationesque-statistics")
  end

  test "specifies rendering app to be government frontend" do
    statistical_data_set = StatisticalDataSet.new
    assert statistical_data_set.rendering_app.include?(Whitehall::RenderingApp::GOVERNMENT_FRONTEND)
  end
end


text:
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @file HelloWorld_main.cpp
 *
 */

#include <limits>
#include <sstream>

#include "HelloWorldPublisher.h"
#include "HelloWorldSubscriber.h"

#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastrtps/log/Log.h>

#include <optionparser.hpp>

using eprosima::fastdds::dds::Log;

namespace option = eprosima::option;

struct Arg : public option::Arg
{
    static void print_error(
            const char* msg1,
            const option::Option& opt,
            const char* msg2)
    {
        fprintf(stderr, "%s", msg1);
        fwrite(opt.name, opt.namelen, 1, stderr);
        fprintf(stderr, "%s", msg2);
    }

    static option::ArgStatus Unknown(
            const option::Option& option,
            bool msg)
    {
        if (msg)
        {
            print_error("Unknown option '", option, "'\n");
        }
        return option::ARG_ILLEGAL;
    }

    static option::ArgStatus Required(
            const option::Option& option,
            bool msg)
    {
        if (option.arg != 0 && option.arg[0] != 0)
        {
            return option::ARG_OK;
        }

        if (msg)
        {
            print_error("Option '", option, "' requires an argument\n");
        }
        return option::ARG_ILLEGAL;
    }

    static option::ArgStatus Numeric(
            const option::Option& option,
            bool msg)
    {
        char* endptr = 0;
        if ( option.arg != nullptr )
        {
            strtol(option.arg, &endptr, 10);
            if (endptr != option.arg && *endptr == 0)
            {
                return option::ARG_OK;
            }
        }

        if (msg)
        {
            print_error("Option '", option, "' requires a numeric argument\n");
        }
        return option::ARG_ILLEGAL;
    }

    template<long min = 0, long max = std::numeric_limits<long>::max()>
    static option::ArgStatus NumericRange(
            const option::Option& option,
            bool msg)
    {
        static_assert(min <= max, "NumericRange: invalid range provided.");

        char* endptr = 0;
        if ( option.arg != nullptr )
        {
            long value = strtol(option.arg, &endptr, 10);
            if ( endptr != option.arg && *endptr == 0 &&
                    value >= min && value <= max)
            {
                return option::ARG_OK;
            }
        }

        if (msg)
        {
            std::ostringstream os;
            os << "' requires a numeric argument in range ["
               << min << ", " << max << "]" << std::endl;
            print_error("Option '", option, os.str().c_str());
        }

        return option::ARG_ILLEGAL;
    }

    static option::ArgStatus String(
            const option::Option& option,
            bool msg)
    {
        if (option.arg != 0)
        {
            return option::ARG_OK;
        }
        if (msg)
        {
            print_error("Option '", option, "' requires an argument\n");
        }
        return option::ARG_ILLEGAL;
    }

};

enum  optionIndex
{
    UNKNOWN_OPT,
    HELP,
    SAMPLES,
    INTERVAL,
    ENVIRONMENT
};

const option::Descriptor usage[] = {
    { UNKNOWN_OPT, 0, "", "",                Arg::None,
      "Usage: HelloWorldExample <publisher|subscriber>\n\nGeneral options:" },
    { HELP,    0, "h", "help",               Arg::None,      "  -h \t--help  \tProduce help message." },
    { UNKNOWN_OPT, 0, "", "",                Arg::None,      "\nPublisher options:"},
    { SAMPLES, 0, "s", "samples",            Arg::NumericRange<>,
      "  -s <num>, \t--samples=<num>  \tNumber of samples (0, default, infinite)." },
    { INTERVAL, 0, "i", "interval",          Arg::NumericRange<>,
      "  -i <num>, \t--interval=<num>  \tTime between samples in milliseconds (Default: 100)." },
    { ENVIRONMENT, 0, "e", "env",            Arg::None,       "  -e \t--env   \tLoad QoS from environment." },
    { 0, 0, 0, 0, 0, 0 }
};

int main(
        int argc,
        char** argv)
{
    int columns;

#if defined(_WIN32)
    char* buf = nullptr;
    size_t sz = 0;
    if (_dupenv_s(&buf, &sz, "COLUMNS") == 0 && buf != nullptr)
    {
        columns = strtol(buf, nullptr, 10);
        free(buf);
    }
    else
    {
        columns = 80;
    }
#else
    columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80;
#endif // if defined(_WIN32)

    std::cout << "Starting " << std::endl;

    int type = 1;
    uint32_t count = 10;
    uint32_t sleep = 100;
    bool use_environment_qos = false;

    argc -= (argc > 0);
    argv += (argc > 0); // skip program name argv[0] if present
    option::Stats stats(true, usage, argc, argv);
    std::vector<option::Option> options(stats.options_max);
    std::vector<option::Option> buffer(stats.buffer_max);
    option::Parser parse(true, usage, argc, argv, &options[0], &buffer[0]);

    try
    {
        if (parse.error())
        {
            throw 1;
        }

        if (options[HELP] || options[UNKNOWN_OPT])
        {
            throw 1;
        }

        // For backward compatibility count and sleep may be given positionally
        if (parse.nonOptionsCount() > 3 || parse.nonOptionsCount() == 0)
        {
            throw 2;
        }

        // Decide between publisher or subscriber
        const char* type_name = parse.nonOption(0);

        // make sure is the first option.
        // type_name and buffer[0].name reference the original command line char array
        // type_name must precede any other arguments in the array.
        // Note buffer[0].arg may be null for non-valued options and is not reliable for
        // testing purposes.
        if (parse.optionsCount() && type_name >= buffer[0].name)
        {
            throw 2;
        }

        if (strcmp(type_name, "publisher") == 0)
        {
            type = 1;
        }
        else if (strcmp(type_name, "subscriber") == 0)
        {
            type = 2;
        }
        else
        {
            throw 2;
        }
    }
    catch (int error)
    {
        if ( error == 2 )
        {
            std::cerr << "ERROR: first argument must be <publisher|subscriber> followed by - or -- options"
                      << std::endl;
        }
        option::printUsage(fwrite, stdout, usage, columns);
        return error;
    }

    // Decide between the old and new syntax
    if (parse.nonOptionsCount() > 1)
    {
        // old syntax, only affects publishers
        // old and new syntax cannot be mixed
        if (type != 1 || parse.optionsCount() > 0)
        {
            option::printUsage(fwrite, stdout, usage, columns);
            return 1;
        }

        count = atoi(parse.nonOption(1));

        if (parse.nonOptionsCount() == 3)
        {
            sleep = atoi(parse.nonOption(2));
        }
    }
    else
    {
        // new syntax
        option::Option* opt = options[SAMPLES];
        if (opt)
        {
            count = strtol(opt->arg, nullptr, 10);
        }

        opt = options[INTERVAL];
        if (opt)
        {
            sleep = strtol(opt->arg, nullptr, 10);
        }

        opt = options[ENVIRONMENT];
        if (opt)
        {
            use_environment_qos = true;
        }
    }

    switch (type)
    {
        case 1:
        {
            HelloWorldPublisher mypub;
            if (mypub.init(use_environment_qos))
            {
                mypub.run(count, sleep);
            }
            break;
        }
        case 2:
        {
            HelloWorldSubscriber mysub;
            if (mysub.init(use_environment_qos))
            {
                mysub.run();
            }
            break;
        }
    }
    Log::Reset();
    return 0;
}


text:
<?php

namespace ArticleBundle\Repository;

/**
 * VoteRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VoteRepository extends \Doctrine\ORM\EntityRepository
{

    	public function compte($numero,$pseudo)
		{
		  return $this->createQueryBuilder('p')
		         ->select('COUNT(p)')
		         ->where('p.pseudo = :pseudo and p.article =:article')
				 ->setParameter('pseudo',$pseudo)
				  ->setParameter('article',$numero)
				 ->getQuery()
				 //attention pas get result , il s'agit d'un count
				 ->getSingleScalarResult();
		}
}


text:
package btrfs

import (
	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/docker/daemon/graphdriver/graphtest"
	"testing"
)

// This avoids creating a new driver for each test if all tests are run
// Make sure to put new tests between TestBtrfsSetup and TestBtrfsTeardown
func TestBtrfsSetup(t *testing.T) {
	graphtest.GetDriver(t, "btrfs")
}

func TestBtrfsCreateEmpty(t *testing.T) {
	graphtest.DriverTestCreateEmpty(t, "btrfs")
}

func TestBtrfsCreateBase(t *testing.T) {
	graphtest.DriverTestCreateBase(t, "btrfs")
}

func TestBtrfsCreateSnap(t *testing.T) {
	graphtest.DriverTestCreateSnap(t, "btrfs")
}

func TestBtrfsTeardown(t *testing.T) {
	graphtest.PutDriver(t)
}


text:
import ctypes
import mock
import unittest
import libvhd.utils.utils as utils
import libvhd.utils.exceptions as exceptions
from libvhd import vhdutils

class TestCoalesce(unittest.TestCase):

    def test_no_name(self):
        mock_libvhd = mock.MagicMock()
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            self.assertRaises(exceptions.VHDUtilMissingArgument,
                              vhdutils.coalesce, name=None)

    def test_none_given_of_output_ancestor_step_parent(self):
        mock_libvhd = mock.MagicMock()
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            self.assertRaises(exceptions.VHDUtilMutuallyExclusiveArguments,
                              vhdutils.coalesce, name='fred.vhd')

    def test_too_many_given_of_output_ancestor_step_parent(self):
        mock_libvhd = mock.MagicMock()
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            self.assertRaises(exceptions.VHDUtilMutuallyExclusiveArguments,
                              vhdutils.coalesce, name='fred.vhd',
                              output='foo.vhd', ancestor='foo2.vhd',
                              step_parent='foo3.vhd')

    def test_calls_coalesce_output(self):
        name = 'fred.vhd'
        output = 'foo.vhd'

        mock_libvhd = mock.MagicMock()
        mock_libvhd.vhd_util_coalesce_out.return_value = ctypes.c_int(0)
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            vhdutils.coalesce(name=name, output=output)

        self.assertEqual(1, mock_libvhd.vhd_util_coalesce_out.call_count)
        self.assertEqual(0, mock_libvhd.vhd_util_coalesce_ancestor.call_count)
        self.assertEqual(0, mock_libvhd.vhd_util_coalesce_parent.call_count)

    def test_calls_coalesce_ancestor(self):
        name = 'fred.vhd'
        ancestor = 'foo.vhd'

        mock_libvhd = mock.MagicMock()
        mock_libvhd.vhd_util_coalesce_ancestor.return_value = ctypes.c_int(0)
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            vhdutils.coalesce(name=name, ancestor=ancestor)

        self.assertEqual(0, mock_libvhd.vhd_util_coalesce_out.call_count)
        self.assertEqual(1, mock_libvhd.vhd_util_coalesce_ancestor.call_count)
        self.assertEqual(0, mock_libvhd.vhd_util_coalesce_parent.call_count)

    def test_calls_coalesce_parent(self):
        name = 'fred.vhd'
        step_parent = 'foo.vhd'

        mock_libvhd = mock.MagicMock()
        mock_libvhd.vhd_util_coalesce_parent.return_value = ctypes.c_int(0)
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            vhdutils.coalesce(name=name, step_parent=step_parent)

        self.assertEqual(0, mock_libvhd.vhd_util_coalesce_out.call_count)
        self.assertEqual(0, mock_libvhd.vhd_util_coalesce_ancestor.call_count)
        self.assertEqual(1, mock_libvhd.vhd_util_coalesce_parent.call_count)

    def test_raises_error_on_nonzero_return(self):
        name = 'fred.vhd'
        output = 'foo.vhd'

        mock_libvhd = mock.MagicMock()
        mock_libvhd.vhd_util_coalesce_out.return_value = ctypes.c_int(1)
        with mock.patch.object(utils, '_get_libvhd_handle',
                               return_value=mock_libvhd):
            self.assertRaises(exceptions.VHDUtilCoalesceError,
                              callableObj=vhdutils.coalesce,
                              name=name, output=output)


text:
package cz.brmlab.yodaqa.analysis.ansscore;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;

import org.apache.uima.UimaContext;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cz.brmlab.yodaqa.model.Question.QuestionInfo;
import cz.brmlab.yodaqa.model.AnswerHitlist.Answer;
import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerFeature;
import cz.brmlab.yodaqa.analysis.ansscore.AF;

/**
 * Record the answer confidence in the feature vector.
 */

public class AnswerScoreToFV extends JCasAnnotator_ImplBase {
	final Logger logger = LoggerFactory.getLogger(AnswerScoreToFV.class);

	/**
	 * Pipeline phase in which we are scoring.  We may be scoring
	 * multiple times and will use different features to differentiate
	 * the model scores.
	 */
	public static final String PARAM_SCORING_PHASE = "SCORING_PHASE";
	@ConfigurationParameter(name = PARAM_SCORING_PHASE, mandatory = true)
	protected String scoringPhase;

	public void initialize(UimaContext aContext) throws ResourceInitializationException {
		super.initialize(aContext);
	}

	public void process(JCas jcas) throws AnalysisEngineProcessException {
		if (scoringPhase.equals("2"))
			return;

		ArrayList<Answer> answers = new ArrayList<Answer>();
		for (Answer a : JCasUtil.select(jcas, Answer.class)) {
			answers.add(a);
		}

		for (Answer a : answers) {
			a.removeFromIndexes();

			AnswerFV fv = new AnswerFV(a);
			if (scoringPhase.equals(""))
				fv.setFeature(AF.Phase0Score, a.getConfidence());
			else if (scoringPhase.equals("1"))
				fv.setFeature(AF.Phase1Score, a.getConfidence());

			for (FeatureStructure af : a.getFeatures().toArray())
				((AnswerFeature) af).removeFromIndexes();
			a.setFeatures(fv.toFSArray(jcas));

			a.addToIndexes();
		}
	}
}


text:
<?php
namespace Vivo\Indexer\Query\Parser\Exception;

/**
 * UnsupportedQueryTypeException
 */
class UnsupportedQueryTypeException extends \Exception implements ExceptionInterface
{
}


text:
namespace aura {
class Window;
}

namespace ui {
class Event;
}

namespace ash {

namespace wm {

// Utility functions for window activation.
ASH_EXPORT void ActivateWindow(aura::Window* window);
ASH_EXPORT void DeactivateWindow(aura::Window* window);
ASH_EXPORT bool IsActiveWindow(aura::Window* window);
ASH_EXPORT aura::Window* GetActiveWindow();
ASH_EXPORT bool CanActivateWindow(aura::Window* window);

// Retrieves the activatable window for |window|. If |window| is activatable,
// this will just return it, otherwise it will climb the parent/transient parent
// chain looking for a window that is activatable, per the ActivationController.
// If you're looking for a function to get the activatable "top level" window,
// this is probably what you're looking for.
ASH_EXPORT aura::Window* GetActivatableWindow(aura::Window* window);

// Returns true if |window|'s location can be controlled by the user.
ASH_EXPORT bool IsWindowUserPositionable(aura::Window* window);

// Pins the window on top of other windows.
ASH_EXPORT void PinWindow(aura::Window* window, bool trusted);

// Moves |window| to the root window where the |event| occured if it is not
// already in the same root window. Returns true if |window| was moved.
ASH_EXPORT bool MoveWindowToEventRoot(aura::Window* window,
                                      const ui::Event& event);

// Snap the window's layer to physical pixel boundary.
void SnapWindowToPixelBoundary(aura::Window* window);

// Mark the container window so that InstallSnapLayoutManagerToContainers
// installs the SnapToPixelLayoutManager.
ASH_EXPORT void SetSnapsChildrenToPhysicalPixelBoundary(
    aura::Window* container);

}  // namespace wm
}  // namespace ash

#endif  // ASH_WM_WINDOW_UTIL_H_


text:
package es.itecban.deployment.executionmanager.manager.queryprovider;

import javax.xml.datatype.XMLGregorianCalendar;

import es.itecban.deployment.executionmanager.elements.PlanFilter;

/**
 *
 * @author mjblazquez
 *
 */

public interface QueryProvider {

//	Plan Manager Queries

	/**
	 *
	 * @param name
	 * @return
	 */
	public abstract String getDeploymentPlan(String name);

	/**
	 *
	 * @return
	 */
	public abstract String getAllDeploymentPlans();

	/**
	 *
	 * @param filter
	 * @param name
	 * @return
	 */
	public abstract String getDeploymentList(PlanFilter filter, String name);

	/**
	 *
	 * @param id
	 * @return
	 */
	public abstract String findPlanById(String id);

//	Report Manager Queries

	/**
	 * This query is not strict match
	 * @param planName
	 * @param endTimeMin
	 * @param endTimeMax
	 * @param creationUserId
	 * @param launchUserId
	 * @param environment
	 * @return
	 */
	public abstract String findReportsByParameters(String planName,
			XMLGregorianCalendar endTimeMin, XMLGregorianCalendar endTimeMax,
			String creationUserId, String launchUserId, String environment);

	/**
	 * It is strict match in both the name and the date
	 * @param planName
	 * @param calendar
	 * @return
	 */
	public abstract String findReport(String planName, XMLGregorianCalendar calendar);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
KeepAliveOutputStream (Apache Ant API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.tools.ant.util.KeepAliveOutputStream class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.tools.ant.util

Class KeepAliveOutputStream

java.lang.Object
  java.io.OutputStream
      java.io.FilterOutputStream
          org.apache.tools.ant.util.KeepAliveOutputStream

All Implemented Interfaces:
java.io.Closeable, java.io.Flushable

public class KeepAliveOutputStream
extends java.io.FilterOutputStream

Class that can be used to wrap <tt>System.out</tt> and <tt>System.err</tt>
 without getting anxious about any client closing the stream.

 In code-language it means that it is not necessary to do:

 if (out != System.out && out!= System.err) {
   out.close();
 }

Field Summary

Fields inherited from class java.io.FilterOutputStream

out

Constructor Summary

KeepAliveOutputStream(java.io.OutputStream out)

          Constructor of KeepAliveOutputStream.

Method Summary

 void
close()

          This method does nothing.

static java.io.PrintStream
wrapSystemErr()

          Convenience factory method that returns a non-closing
 PrintStream around System.err.

static java.io.PrintStream
wrapSystemOut()

          Convenience factory method that returns a non-closing
 PrintStream around System.out.

Methods inherited from class java.io.FilterOutputStream

flush, write, write, write

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

KeepAliveOutputStream

public KeepAliveOutputStream(java.io.OutputStream out)

Constructor of KeepAliveOutputStream.

Parameters:
out - an OutputStream value, it shoudl be standard output.

Method Detail

close

public void close()
           throws java.io.IOException

This method does nothing.

Specified by:
close in interface java.io.Closeable
Overrides:
close in class java.io.FilterOutputStream

Throws:

java.io.IOException - as we are overridding FilterOutputStream.

wrapSystemOut

public static java.io.PrintStream wrapSystemOut()

Convenience factory method that returns a non-closing
 PrintStream around System.out.

Since:

Ant 1.8.0

wrapSystemErr

public static java.io.PrintStream wrapSystemErr()

Convenience factory method that returns a non-closing
 PrintStream around System.err.

Since:

Ant 1.8.0

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD