text:
#ifndef SPMATRIX_API_H
#define SPMATRIX_API_H

/*
 * C API
 */

/* Type definitions */

#define LLMatType_NUM 0
#define CSRMatType_NUM 1
#define SSSMatType_NUM 2

/* Function definitions */

#define SpMatrix_ParseVecOpArgs_NUM 3
#define SpMatrix_ParseVecOpArgs_RET int
#define SpMatrix_ParseVecOpArgs_PROTO (PyObject *args, double **x_data, double **y_data, int n)

#define SpMatrix_GetShape_NUM 4
#define SpMatrix_GetShape_RET int
#define SpMatrix_GetShape_PROTO (PyObject *, int[])

#define SpMatrix_GetOrder_NUM 5
#define SpMatrix_GetOrder_RET int
#define SpMatrix_GetOrder_PROTO (PyObject *, int*)

#define SpMatrix_GetItem_NUM 6
#define SpMatrix_GetItem_RET double
#define SpMatrix_GetItem_PROTO (PyObject *, int, int)

#define SpMatrix_Matvec_NUM 7
#define SpMatrix_Matvec_RET int
#define SpMatrix_Matvec_PROTO (PyObject *matrix, int nx, double *x, int ny, double *y)

#define SpMatrix_Precon_NUM 8
#define SpMatrix_Precon_RET int
#define SpMatrix_Precon_PROTO (PyObject *repc, int n, double *x, double *y)

#define SpMatrix_NewLLMatObject_NUM 9
#define SpMatrix_NewLLMatObject_RET PyObject *
#define SpMatrix_NewLLMatObject_PROTO (int dim[], int sym, int sizeHint, int storeZeros)

#define SpMatrix_LLMatGetItem_NUM 10
#define SpMatrix_LLMatGetItem_RET double
#define SpMatrix_LLMatGetItem_PROTO (LLMatObject *a, int i, int j)

#define SpMatrix_LLMatSetItem_NUM 11
#define SpMatrix_LLMatSetItem_RET int
#define SpMatrix_LLMatSetItem_PROTO (LLMatObject *a, int i, int j, double x)

#define SpMatrix_LLMatUpdateItemAdd_NUM 12
#define SpMatrix_LLMatUpdateItemAdd_RET int
#define SpMatrix_LLMatUpdateItemAdd_PROTO (LLMatObject *a, int i, int j, double x)

#define SpMatrix_LLMatBuildColIndex_NUM 13
#define SpMatrix_LLMatBuildColIndex_RET int
#define SpMatrix_LLMatBuildColIndex_PROTO (struct llColIndex **idx, LLMatObject *self, int includeDiagonal)

#define SpMatrix_LLMatDestroyColIndex_NUM 14
#define SpMatrix_LLMatDestroyColIndex_RET void
#define SpMatrix_LLMatDestroyColIndex_PROTO (struct llColIndex **idx)

#define ItSolvers_Solve_NUM 15
#define ItSolvers_Solve_RET int
#define ItSolvers_Solve_PROTO (PyObject *linsolver, PyObject *A, int n, \
                double *b, double *x, double tol, int itmax, PyObject *K, \
                int *info, int *iter, double *relres)

/* Total number of C API pointers */
#define SpMatrix_API_pointers 16

#ifdef SPMATRIX_MODULE

static SpMatrix_ParseVecOpArgs_RET SpMatrix_ParseVecOpArgs SpMatrix_ParseVecOpArgs_PROTO;
static SpMatrix_GetShape_RET SpMatrix_GetShape SpMatrix_GetShape_PROTO;
static SpMatrix_GetOrder_RET SpMatrix_GetOrder SpMatrix_GetOrder_PROTO;
static SpMatrix_GetItem_RET SpMatrix_GetItem SpMatrix_GetItem_PROTO;
static SpMatrix_Matvec_RET SpMatrix_Matvec SpMatrix_Matvec_PROTO;
static SpMatrix_Precon_RET SpMatrix_Precon SpMatrix_Precon_PROTO;
static SpMatrix_NewLLMatObject_RET SpMatrix_NewLLMatObject SpMatrix_NewLLMatObject_PROTO;
static SpMatrix_LLMatGetItem_RET SpMatrix_LLMatGetItem SpMatrix_LLMatGetItem_PROTO;
static SpMatrix_LLMatSetItem_RET SpMatrix_LLMatSetItem SpMatrix_LLMatSetItem_PROTO;
static SpMatrix_LLMatUpdateItemAdd_RET SpMatrix_LLMatUpdateItemAdd SpMatrix_LLMatUpdateItemAdd_PROTO;
static SpMatrix_LLMatBuildColIndex_RET SpMatrix_LLMatBuildColIndex SpMatrix_LLMatBuildColIndex_PROTO;
static SpMatrix_LLMatDestroyColIndex_RET SpMatrix_LLMatDestroyColIndex SpMatrix_LLMatDestroyColIndex_PROTO;
static ItSolvers_Solve_RET ItSolvers_Solve ItSolvers_Solve_PROTO;

#define init_c_api(MODULE_DICT) \
{ \
  static void *SpMatrix_API[SpMatrix_API_pointers]; \
  PyObject *c_api_object; \
\
  /* initialize C API pointer array */ \
  SpMatrix_API[LLMatType_NUM] = (void *) &LLMatType; \
  SpMatrix_API[CSRMatType_NUM] = (void *) &CSRMatType; \
  SpMatrix_API[SSSMatType_NUM] = (void *) &SSSMatType; \
  SpMatrix_API[SpMatrix_ParseVecOpArgs_NUM] = (void *) SpMatrix_ParseVecOpArgs; \
  SpMatrix_API[SpMatrix_GetShape_NUM] = (void *) SpMatrix_GetShape; \
  SpMatrix_API[SpMatrix_GetOrder_NUM] = (void *) SpMatrix_GetOrder; \
  SpMatrix_API[SpMatrix_GetItem_NUM] = (void *) SpMatrix_GetItem; \
  SpMatrix_API[SpMatrix_Matvec_NUM] = (void *) SpMatrix_Matvec; \
  SpMatrix_API[SpMatrix_Precon_NUM] = (void *) SpMatrix_Precon; \
  SpMatrix_API[SpMatrix_NewLLMatObject_NUM] = (void *) SpMatrix_NewLLMatObject; \
  SpMatrix_API[SpMatrix_LLMatGetItem_NUM] = (void *) SpMatrix_LLMatGetItem; \
  SpMatrix_API[SpMatrix_LLMatSetItem_NUM] = (void *) SpMatrix_LLMatSetItem; \
  SpMatrix_API[SpMatrix_LLMatUpdateItemAdd_NUM] = (void *) SpMatrix_LLMatUpdateItemAdd; \
  SpMatrix_API[SpMatrix_LLMatBuildColIndex_NUM] = (void *) SpMatrix_LLMatBuildColIndex; \
  SpMatrix_API[SpMatrix_LLMatDestroyColIndex_NUM] = (void *) SpMatrix_LLMatDestroyColIndex; \
  SpMatrix_API[ItSolvers_Solve_NUM] = (void *) ItSolvers_Solve; \
\
  /* Create a CObject containing the API pointer array s address */ \
  c_api_object = PyCObject_FromVoidPtr((void *)SpMatrix_API, NULL); \
\
  /* create a name for this object in the module's namespace */ \
  if (c_api_object != NULL) { \
    PyDict_SetItemString((MODULE_DICT), "_C_API", c_api_object); \
    Py_DECREF(c_api_object); \
  } \
}

#else

#ifdef SPMATRIX_UNIQUE_SYMBOL
#define SpMatrix_API SPMATRIX_UNIQUE_SYMBOL
#endif

/* C API address pointer */
#ifdef NO_IMPORT_SPMATRIX
extern void **SpMatrix_API;
#else
#ifdef SPMATRIX_UNIQUE_SYMBOL
extern void **SpMatrix_API;
#else
static void **SpMatrix_API;
#endif
#endif

#define LLMatType *(PyTypeObject *)SpMatrix_API[LLMatType_NUM]
#define CSRMatType *(PyTypeObject *)SpMatrix_API[CSRMatType_NUM]
#define SSSMatType *(PyTypeObject *)SpMatrix_API[SSSMatType_NUM]

#define SpMatrix_ParseVecOpArgs \
  (*(SpMatrix_ParseVecOpArgs_RET (*)SpMatrix_ParseVecOpArgs_PROTO) \
  SpMatrix_API[SpMatrix_ParseVecOpArgs_NUM])

#define SpMatrix_GetShape \
  (*(SpMatrix_GetShape_RET (*)SpMatrix_GetShape_PROTO) \
  SpMatrix_API[SpMatrix_GetShape_NUM])

#define SpMatrix_GetOrder \
  (*(SpMatrix_GetOrder_RET (*)SpMatrix_GetOrder_PROTO) \
  SpMatrix_API[SpMatrix_GetOrder_NUM])

#define SpMatrix_GetItem \
  (*(SpMatrix_GetItem_RET (*)SpMatrix_GetItem_PROTO) \
  SpMatrix_API[SpMatrix_GetItem_NUM])

#define SpMatrix_Matvec \
  (*(SpMatrix_Matvec_RET (*)SpMatrix_Matvec_PROTO) \
  SpMatrix_API[SpMatrix_Matvec_NUM])

#define SpMatrix_Precon \
  (*(SpMatrix_Precon_RET (*)SpMatrix_Precon_PROTO) \
  SpMatrix_API[SpMatrix_Precon_NUM])

#define SpMatrix_NewLLMatObject \
  (*(SpMatrix_NewLLMatObject_RET (*)SpMatrix_NewLLMatObject_PROTO) \
  SpMatrix_API[SpMatrix_NewLLMatObject_NUM])

#define SpMatrix_LLMatGetItem \
  (*(SpMatrix_LLMatGetItem_RET (*)SpMatrix_LLMatGetItem_PROTO) \
  SpMatrix_API[SpMatrix_LLMatGetItem_NUM])

#define SpMatrix_LLMatSetItem \
  (*(SpMatrix_LLMatSetItem_RET (*)SpMatrix_LLMatSetItem_PROTO) \
  SpMatrix_API[SpMatrix_LLMatSetItem_NUM])

#define SpMatrix_LLMatUpdateItemAdd \
  (*(SpMatrix_LLMatUpdateItemAdd_RET (*)SpMatrix_LLMatUpdateItemAdd_PROTO) \
  SpMatrix_API[SpMatrix_LLMatUpdateItemAdd_NUM])

#define SpMatrix_LLMatBuildColIndex \
  (*(SpMatrix_LLMatBuildColIndex_RET (*)SpMatrix_LLMatBuildColIndex_PROTO) \
  SpMatrix_API[SpMatrix_LLMatBuildColIndex_NUM])

#define SpMatrix_LLMatDestroyColIndex \
  (*(SpMatrix_LLMatDestroyColIndex_RET (*)SpMatrix_LLMatDestroyColIndex_PROTO) \
  SpMatrix_API[SpMatrix_LLMatDestroyColIndex_NUM])

#define ItSolvers_Solve \
  (*(ItSolvers_Solve_RET (*)ItSolvers_Solve_PROTO) \
  SpMatrix_API[ItSolvers_Solve_NUM])

#define import_spmatrix() \
{ \
  PyObject *spmatrix = PyImport_ImportModule("pysparse.sparse.spmatrix"); \
  if (spmatrix != NULL) { \
    PyObject *module_dict = PyModule_GetDict(spmatrix); \
    PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
    if (PyCObject_Check(c_api_object)) { \
      SpMatrix_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
    } \
  } \
  assert(SpMatrix_API != NULL); \
}

#endif

#endif


text:
package api

import (
	"fmt"
	"time"

	"github.com/golang/glog"
	rpc "github.com/googleapis/googleapis/google/rpc"
	opentracing "github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/log"
	legacyContext "golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"

	mixerpb "istio.io/api/mixer/v1"
	"istio.io/mixer/pkg/adapterManager"
	"istio.io/mixer/pkg/aspect"
	"istio.io/mixer/pkg/attribute"
	"istio.io/mixer/pkg/pool"
	"istio.io/mixer/pkg/status"
)

// We have a slightly messy situation around the use of context objects. gRPC stubs are
// generated to expect the old "x/net/context" types instead of the more modern "context".
// We end up doing a quick switcharoo from the gRPC defined type to the modern type so we can
// use the modern type elsewhere in the code.

type (
	// grpcServer holds the dispatchState for the gRPC API server.
	grpcServer struct {
		aspectDispatcher adapterManager.AspectDispatcher
		gp               *pool.GoroutinePool

		// the global dictionary. This will eventually be writable via config
		globalWordList []string
		globalDict     map[string]int32
	}
)

// NewGRPCServer creates a gRPC serving stack.
func NewGRPCServer(aspectDispatcher adapterManager.AspectDispatcher, gp *pool.GoroutinePool) mixerpb.MixerServer {
	globalDict := make(map[string]int32, len(globalWordList))
	for i := 0; i < len(globalWordList); i++ {
		globalDict[globalWordList[i]] = int32(i)
	}

	return &grpcServer{
		aspectDispatcher: aspectDispatcher,
		gp:               gp,
		globalWordList:   globalWordList,
		globalDict:       globalDict,
	}
}

// Check is the entry point for the external Check method
func (s *grpcServer) Check(legacyCtx legacyContext.Context, req *mixerpb.CheckRequest) (*mixerpb.CheckResponse, error) {
	// TODO: this code doesn't distinguish between RPC failures when communicating with adapters and
	//       their backend vs. semantic failures. For example, if the adapterDispatcher.Check
	//       method returns a bad status, is that because an adapter failed an RPC or because the
	//       request was denied? This will need to be addressed in the new adapter model. In the meantime,
	//       RPC failure is treated as a semantic denial.

	requestBag := attribute.NewProtoBag(&req.Attributes, s.globalDict, s.globalWordList)

	globalWordCount := int(req.GlobalWordCount)

	glog.Info("Dispatching Preprocess")
	preprocResponseBag := attribute.GetMutableBag(requestBag)
	out := s.aspectDispatcher.Preprocess(legacyCtx, requestBag, preprocResponseBag)
	glog.Info("Preprocess returned with: ", statusString(out))

	if !status.IsOK(out) {
		requestBag.Done()
		preprocResponseBag.Done()
		return nil, makeGRPCError(out)
	}

	if glog.V(2) {
		glog.Info("Dispatching to main adapters after running processors")
		for _, name := range preprocResponseBag.Names() {
			v, _ := preprocResponseBag.Get(name)
			glog.Infof("  %s: %v", name, v)
		}
	}

	responseBag := attribute.GetMutableBag(nil)

	glog.Info("Dispatching Check")
	out = s.aspectDispatcher.Check(legacyCtx, preprocResponseBag, responseBag)
	glog.Info("Check returned with: ", statusString(out))

	resp := &mixerpb.CheckResponse{}
	// TODO: these values need to initially come from config, and be modulated by the kind of attribute
	//       that was used in the check and the in-used aspects (for example, maybe an auth check has a
	//       30s TTL but a whitelist check has got a 120s TTL)
	resp.Precondition.ValidDuration = 5 * time.Second
	resp.Precondition.ValidUseCount = 10000
	resp.Precondition.Status = out
	responseBag.ToProto(&resp.Precondition.Attributes, s.globalDict, globalWordCount)
	responseBag.Done()
	resp.Precondition.ReferencedAttributes = requestBag.GetReferencedAttributes(s.globalDict, globalWordCount)
	requestBag.ClearReferencedAttributes()

	if len(req.Quotas) > 0 {
		resp.Quotas = make(map[string]mixerpb.CheckResponse_QuotaResult, len(req.Quotas))

		// TODO: should dispatch this loop in parallel
		// WARNING: if this is dispatched in parallel, then we need to do
		//          use a different protoBag for each individual goroutine
		//          such that we can get valid usage info for individual attributes.
		for name, param := range req.Quotas {
			qma := &aspect.QuotaMethodArgs{
				Quota:           name,
				Amount:          param.Amount,
				DeduplicationID: req.DeduplicationId + name,
				BestEffort:      param.BestEffort,
			}

			glog.Info("Dispatching Quota")
			qmr, out := s.aspectDispatcher.Quota(legacyCtx, preprocResponseBag, qma)
			glog.Infof("Quota returned with status '%v' and quota response '%v'", statusString(out), qmr)

			if qmr == nil {
				qmr = &aspect.QuotaMethodResp{}
			}

			qr := mixerpb.CheckResponse_QuotaResult{
				GrantedAmount:        qmr.Amount,
				ValidDuration:        qmr.Expiration,
				ReferencedAttributes: requestBag.GetReferencedAttributes(s.globalDict, globalWordCount),
			}
			resp.Quotas[name] = qr
			requestBag.ClearReferencedAttributes()
		}
	}

	requestBag.Done()
	preprocResponseBag.Done()

	return resp, nil
}

var reportResp = &mixerpb.ReportResponse{}

// Report is the entry point for the external Report method
func (s *grpcServer) Report(legacyCtx legacyContext.Context, req *mixerpb.ReportRequest) (*mixerpb.ReportResponse, error) {
	if len(req.Attributes) == 0 {
		// early out
		return reportResp, nil
	}

	// apply the request-level word list to each attribute message if needed
	for i := 0; i < len(req.Attributes); i++ {
		if len(req.Attributes[i].Words) == 0 {
			req.Attributes[i].Words = req.DefaultWords
		}
	}

	protoBag := attribute.NewProtoBag(&req.Attributes[0], s.globalDict, s.globalWordList)
	requestBag := attribute.GetMutableBag(protoBag)
	preprocResponseBag := attribute.GetMutableBag(requestBag)

	var err error
	for i := 0; i < len(req.Attributes); i++ {
		span, newctx := opentracing.StartSpanFromContext(legacyCtx, fmt.Sprintf("Attributes %d", i))

		// the first attribute block is handled by the protoBag as a foundation,
		// deltas are applied to the child bag (i.e. requestBag)
		if i > 0 {
			err = requestBag.UpdateBagFromProto(&req.Attributes[i], s.globalWordList)
			if err != nil {
				msg := "Request could not be processed due to invalid attributes."
				glog.Error(msg, "\n", err)
				details := status.NewBadRequest("attributes", err)
				err = makeGRPCError(status.InvalidWithDetails(msg, details))
				break
			}
		}

		glog.Info("Dispatching Preprocess")
		out := s.aspectDispatcher.Preprocess(newctx, requestBag, preprocResponseBag)
		glog.Info("Preprocess returned with: ", statusString(out))

		if !status.IsOK(out) {
			err = makeGRPCError(out)
			span.LogFields(log.String("error", err.Error()))
			span.Finish()
			break
		}

		if glog.V(2) {
			glog.Info("Dispatching to main adapters after running processors")
			for _, name := range preprocResponseBag.Names() {
				v, _ := preprocResponseBag.Get(name)
				glog.Infof("  %s: %v", name, v)
			}
		}

		glog.Info("Dispatching Report")
		out = s.aspectDispatcher.Report(legacyCtx, preprocResponseBag)
		glog.Info("Report returned with: ", statusString(out))

		if !status.IsOK(out) {
			err = makeGRPCError(out)
			span.LogFields(log.String("error", err.Error()))
			span.Finish()
			break
		}

		span.LogFields(log.String("success", fmt.Sprintf("finished Report for attribute bag %d", i)))
		span.Finish()
		preprocResponseBag.Reset()
	}

	preprocResponseBag.Done()
	requestBag.Done()
	protoBag.Done()

	if err != nil {
		return nil, err
	}

	return reportResp, nil
}

func makeGRPCError(status rpc.Status) error {
	return grpc.Errorf(codes.Code(status.Code), status.Message)
}

func statusString(status rpc.Status) string {
	if name, ok := rpc.Code_name[status.Code]; ok {
		return fmt.Sprintf("%s %s", name, status.Message)
	}
	return "Unknown " + status.Message
}

redpajama_set_name: RedPajamaGithub


text:
shopping-cart: EJB Stateful Session Bean (SFSB) Example
=====================================
Author: Serge Pagop
Level: Intermediate
Technologies: SFSB EJB
Summary: The `shopping-cart` quickstart demonstrates how to deploy and run a simple Java EE 7 shopping cart application that uses a stateful session bean (SFSB).
Target Product: WildFly
Source: <https://github.com/wildfly/quickstart/>

What is it?
-----------

The `shopping-cart` quickstart demonstrates how to deploy and run a simple Java EE 7 application that uses a stateful session bean (SFSB) in Red Hat JBoss Enterprise Application Platform. The application allows customers to buy, checkout, and view their cart contents.

The `shopping-cart` application consists of the following:

1. A server side component:

    This standalone Java EE module is a JAR containing EJBs. It is responsible for managing the shopping cart.
2. A Java client:

    This simple Java client is launched using a "main" method. The remote client looks up a reference to the server module's API, via JNDI. It then uses this API to perform the operations the customer requests.

System requirements
-------------------

The application this project produces is designed to be run on Red Hat JBoss Enterprise Application Platform 7 or later.

All you need to build this project is Java 8.0 (Java SDK 1.8) or later and Maven 3.1.1 or later. See [Configure Maven for WildFly 10](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/CONFIGURE_MAVEN_JBOSS_EAP7.md#configure-maven-to-build-and-deploy-the-quickstarts) to make sure you are configured correctly for testing the quickstarts.

Use of WILDFLY_HOME
---------------

In the following instructions, replace `WILDFLY_HOME` with the actual path to your WildFly installation. The installation path is described in detail here: [Use of WILDFLY_HOME and JBOSS_HOME Variables](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/USE_OF_EAP7_HOME.md#use-of-eap_home-and-jboss_home-variables).

Configure the WildFly Server
---------------------------

This example quickstart purposely throws a `NoSuchEJBException` exception when the shopping cart is empty. This is the expected result because method is annotated with `@Remove`. This means the next invocation after the shopping cart checkout fails because the container has destroyed the instance and it is no longer available. If you don't run this script, you see the following ERROR in the server log, followed by the stacktrace

    ERROR [org.jboss.as.ejb3.invocation] (EJB default - 7) WFLYEJB0034: EJB Invocation failed on component ShoppingCartBean for method public abstract java.util.Map org.jboss.as.quickstarts.sfsb.ShoppingCart.getCartContents(): javax.ejb.NoSuchEJBException: WFLYEJB0168: Could not find EJB with id UnknownSessionID [5168576665505352655054705267485457555457535250485552546568575254]

Follow the steps below to suppress system exception logging.

1. Before you begin, back up your server configuration file
    * If it is running, stop the WildFly server.
    * Backup the file: `WILDFLY_HOME/standalone/configuration/standalone.xml`
    * After you have completed testing this quickstart, you can replace this file to restore the server to its original configuration.
2. Start the WildFly server by typing the following:

        For Linux:  WILDFLY_HOME/bin/standalone.sh
        For Windows:  WILDFLY_HOME\bin\standalone.bat
3. Review the `configure-system-exception.cli` file in the root of this quickstart directory. This script sets the `log-system-exceptions` attribute to `false` in the `ejb3` subsystem in the server configuration file.

4. Open a new command prompt, navigate to the root directory of this quickstart, and run the following command, replacing WILDFLY_HOME with the path to your server:

        For Linux: WILDFLY_HOME/bin/jboss-cli.sh --connect --file=configure-system-exception.cli
        For Windows: WILDFLY_HOME\bin\jboss-cli.bat --connect --file=configure-system-exception.cli
   You should see the following result when you run the script:

        {"outcome" => "success"}
5. Stop the WildFly server.

Review the Modified Server Configuration
-----------------------------------

After stopping the server, open the `WILDFLY_HOME/standalone/configuration/standalone.xml` file and review the changes.

You should see the following configuration in the `ejb3` subsystem.

      <log-system-exceptions value="false"/>

Start the WildFly Server
-------------------------

1. Open a command prompt and navigate to the root of the WildFly directory.
2. The following shows the command line to start the server:

        For Linux:   WILDFLY_HOME/bin/standalone.sh
        For Windows: WILDFLY_HOME\bin\standalone.bat

Build and Deploy the Quickstart
-------------------------

1. Make sure you have started the WildFly server. See the instructions in the previous section.

2. Open a command prompt and navigate to the `shopping-cart` quickstart directory
3. To build both the server component and the remote client program, deploy the server module, change into the examples shopping-cart directory and type the following:

        mvn clean install wildfly:deploy
4. This Maven goal will deploy `server/target/wildfly-shopping-cart-server.jar`. You can check the server console to see information messages regarding the deployment.

        INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-2) WFLYEJB0473: JNDI bindings for session bean named 'ShoppingCartBean' in deployment unit 'deployment "jboss-shopping-cart-server.jar"' are as follows:

          java:global/jboss-shopping-cart-server/ShoppingCartBean!org.jboss.as.quickstarts.sfsb.ShoppingCart
          java:app/jboss-shopping-cart-server/ShoppingCartBean!org.jboss.as.quickstarts.sfsb.ShoppingCart
          java:module/ShoppingCartBean!org.jboss.as.quickstarts.sfsb.ShoppingCart
          java:jboss/exported/jboss-shopping-cart-server/ShoppingCartBean!org.jboss.as.quickstarts.sfsb.ShoppingCart
          java:global/jboss-shopping-cart-server/ShoppingCartBean
          java:app/jboss-shopping-cart-server/ShoppingCartBean
          java:module/ShoppingCartBean

        INFO  [org.jboss.weld.deployer] (MSC service thread 1-4) WFLYWELD0006: Starting Services for CDI deployment: jboss-shopping-cart-server.jar
        INFO  [org.jboss.weld.deployer] (MSC service thread 1-8) WFLYWELD0009: Starting weld service for deployment jboss-shopping-cart-server.jar
        INFO  [org.jboss.as.server] (management-handler-thread - 3) WFLYSRV0010: Deployed "jboss-shopping-cart-server.jar" (runtime-name : "jboss-shopping-cart-server.jar")

Run the Client Application
------------------------

Now start a client that will access the beans you just deployed.

You can use the command prompt from the previous step or open a new one and navigate to the root of the `shopping-cart` quickstart directory.

Type the following command:

        mvn exec:java -f client/pom.xml

Investigate the Console Output
-------------------------------

You should see the following:

1. The client sends a remote method invocation to the stateful session bean to buy two "32 GB USB 2.0 Flash Drive" and one "Wireless Ergonomic Keyboard and Mouse".
2. The client sends a remote method invocation to get the contents of the cart and prints it to the console.
3. The client sends a remote method invocation to invoke checkout. Note the `checkout()` method in the server `ShoppingCartBean` has the `@Remove` annotation. This means the container will destroy shopping cart after the call and it will no longer be available.
4. The client calls `getCartContents()` to make sure the shopping cart was removed after checkout. This results in a `javax.ejb.NoSuchEJBException` trace in the server, proving the cart was removed.

On the client console, you should see output similar to:

    &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    Obtained the remote interface to the shopping cart
    Buying a "32 GB USB 2.0 Flash Drive".
    Buying another "32 GB USB 2.0 Flash Drive".
    Buying a "Wireless Ergonomic Keyboard and Mouse"

    Print cart:
    1     Wireless Ergonomic Keyboard and Mouse
    2     32 GB USB 2.0 Flash Drive

    Checkout
    Cart was correctly removed, as expected, after Checkout
    &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

On the server log, you should see:

    INFO  [stdout] (pool-9-thread-8) implementing checkout() left as exercise for the reader!

Restore the Server Configuration
----------------------------

You can restore the system exception configuration by running the `restore-system-exception.cli` script provided in the root directory of this quickstart or by manually restoring the back-up copy the configuration file.

### Restore the Server Configuration by Running the JBoss CLI Script

1. Start the WildFly server by typing the following:

        For Linux:  WILDFLY_HOME/bin/standalone.sh
        For Windows:  WILDFLY_HOME\bin\standalone.bat
2. Open a new command prompt, navigate to the root directory of this quickstart, and run the following command, replacing WILDFLY_HOME with the path to your server:

        For Linux: WILDFLY_HOME/bin/jboss-cli.sh --connect --file=restore-system-exception.cli
        For Windows: WILDFLY_HOME\bin\jboss-cli.bat --connect --file=restore-system-exception.cli
   This script restores the  the `log-system-exceptions` attribute value to `true`. You should see the following result when you run the script:

        The batch executed successfully.
        {"outcome" => "success"}

### Restore the Server Configuration Manually
1. If it is running, stop the WildFly server.
2. Replace the `WILDFLY_HOME/standalone/configuration/standalone.xml` file with the back-up copy of the file.

Undeploy the Archive
--------------------

1. Make sure you have started the WildFly server as described above.
2. Open a command prompt and navigate to the root directory of this quickstart.
3. When you are finished testing, type this command to undeploy the archive:

        mvn wildfly:undeploy

Run the Quickstart in Red Hat JBoss Developer Studio or Eclipse
-------------------------------------
You can also start the server and deploy the quickstarts or run the Arquillian tests from Eclipse using JBoss tools. For general information about how to import a quickstart, add a WildFly server, and build and deploy a quickstart, see [Use JBoss Developer Studio or Eclipse to Run the Quickstarts](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/USE_JBDS.md#use-jboss-developer-studio-or-eclipse-to-run-the-quickstarts)

This quickstart consists of multiple projects, so it deploys and runs differently in JBoss Developer Studio than the other quickstarts.

* To deploy the server project, right-click on the `jboss-shopping-cart-server` project and choose `Run As` --> `Run on Server`.
* To run the client, right-click on the `jboss-shopping-cart-client` project and choose `Run As` --> `Java Application`. In the `Select Java Application` window, choose `Client - org.jboss.as.quickstarts.client` and click `OK`. The client output displays in the `Console` window.

Debug the Application
---------------------

If you want to debug the source code of any library in the project, run the following command to pull the source into your local repository. The IDE should then detect it.

        mvn dependency:sources


text:
package com.eden.orchid.api.registration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IgnoreModule {
}


text:
module ZombieEpidemic
  class Void
    def nil?; true; end
    def method_missing(*args, &block)
      self
    end
  end

  class Border
    def nil?; false; end
    def method_missing(*args, &block)
      self
    end
  end

  class Obstacle
    def initialize(position)
      position.contents = self
    end
    def nil?; false; end
    def name; "Obstacle"; end
    def method_missing(*args, &block)
      self
    end
  end

end


text:
package com.trovebox.android.common.net;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.trovebox.android.common.model.Tag;

public class TagsResponse extends TroveboxResponse {
    private final List<Tag> mTags;

    public TagsResponse(JSONObject json) throws JSONException {
        super(RequestType.TAGS, json);
        JSONArray data = json.getJSONArray("result");
        mTags = new ArrayList<Tag>(data.length());
        for (int i = 0; i < data.length(); i++) {
            mTags.add(Tag.fromJson(data.getJSONObject(i)));
        }
    }

    /**
     * @return the tags retrieved from the server
     */
    public List<Tag> getTags() {
        return mTags;
    }
}


text:
title: Implement the filter Method on a Prototype
localeTitle: 在Prototype上实现过滤器方法
---
## 在Prototype上实现过滤器方法

```javascript
// the global Array
 var s = [23, 65, 98, 5];

 Array.prototype.myFilter = function(callback){
  var newArray = [];
  // Add your code below this line
  this.forEach(function(x) {
    if (callback(x) == true) {
      newArray.push(x);
    }
  })
  // Add your code above this line
  return newArray;

 };
```

## 另一个用于looop的解决方案!

```javascript
Array.prototype.myFilter = function(callback){
  var newArray = [];
  // Add your code below this line
  for (let i=0; i<this.length;i++){
    if(callback(this[i])=== true ){
 newArray.push(this[i]);
    }
  }
  // Add your code above this line
  return newArray;

 };

 var new_s = s.myFilter(function(item){
  return item % 2 === 1;
 });

```


text:
package sri.universal.apis

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport

trait PlatformSelect extends js.Object {
  val ios: js.UndefOr[js.Object] = js.undefined
  val android: js.UndefOr[js.Object] = js.undefined
}

@js.native
trait ReactPlatform extends js.Object {
  val OS: String = js.native
  val Version: Double = js.native

  def select(obj: PlatformSelect): js.Object = js.native
}

@js.native
@JSImport("react-native", "Platform")
object ReactPlatform extends ReactPlatform


text:
"""Small test utilities used by multiple tests"""

__copyright__ = "Copyright (C) 2019-present, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"

from os.path import join
from os.path import dirname
from os.path import abspath
import sys
import timeit
from datetime import timedelta
from goatools.base import get_godag as base_get_godag
from goatools.associations import dnld_annotation
from goatools.anno.factory import get_objanno as get_objanno_factory
# from goatools.gosubdag.gosubdag import GoSubDag
from goatools.semantic import TermCounts

# from goatools_alpha.geneprodsim.semanticcalcs import SemanticCalcs

DIR_TEST = dirname(abspath(__file__))
REPO = abspath(join(DIR_TEST, ".."))

def prt_hms(tic, msg, prt=sys.stdout):
    """Print elapsed time and return current time"""
    toc = timeit.default_timer()
    prt.write('{HMS} {MSG}\n'.format(HMS=str(timedelta(seconds=toc-tic)), MSG=msg))
    return toc

def repofn(fin):
    """Get a full filename, given a local file name from repo dir root"""
    return join(REPO, fin)

def get_godag(fin_godag, **kws):
    """Get GODAG containing only primary GO IDs (no alternate GO IDs)"""
    godag = base_get_godag(join(REPO, fin_godag), loading_bar=False, **kws)
    return {o.item_id:o for o in godag.values()}

def get_anno_fullname(fin_anno):
    """Get annotation filename"""
    fin_full = join(REPO, fin_anno)
    dnld_annotation(fin_full)
    return fin_full

def get_objanno(fin_anno, godag, namespace='all'):
    """Get annotation object"""
    fin_full = get_anno_fullname(fin_anno)
    return get_objanno_factory(fin_full, godag=godag, namespace=namespace)

def get_termcounts(fin_anno, godag, namespace='all', **kws):
    """Get termcounts object"""
    objanno = get_objanno(fin_anno, godag, namespace)
    id2gos = objanno.get_id2gos(namespace=namespace, **kws)
    return TermCounts(godag, id2gos)

# Copyright (C) 2019-present, DV Klopfenstein, et al. All rights reserved.


text:
export * from './adaptorUtils'
export * from './APIErrorDisplay'
export * from './browserAdaptor'
export * from './extensionAdaptor'
export * from './ExtMarkdown'
export * from './authUtils'
export * from './OAuthScene'


text:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { Alert, Button } from 'react-bootstrap'
import Header from './header'
import { setMessage } from '../actions/auth'
import { fetchBooks } from '../actions/book'

/* global styles for app */
import '../styles/app.scss';

class App extends Component {
  constructor(props) {
    super(props)
    this.fetchBooks
    this.handleDismissClick = this.handleDismissClick.bind(this)
  }

  componentWillMount() {
    this.props.fetchBooks()
  }

  handleDismissClick(event) {
    this.props.setMessage('')
    event.preventDefault()
  }

  renderErrorMessage() {
    if (!this.props.message) {
      return null
    }

    return (
      <Alert className="alert" bsStyle="danger" onDismiss={this.handleDismissClick}>

Uh oh! You got an error!

{this.props.message}

          <Button onClick={this.handleDismissClick}>OK</Button>

      </Alert>
    )
  }

  render() {
    return (

          {this.renderErrorMessage()}
          {this.props.children}

    )
  }
}

App.propTypes = {
  message: PropTypes.string,
  setMessage: PropTypes.func.isRequired,
  children: PropTypes.node,
  fetchBooks: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  return {
    message: state.message,
  }
}

export default connect(mapStateToProps, { fetchBooks, setMessage })(App)


text:
Dgameclone
==========

A simple and lightweight Dgamelaunch clone written in C++


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/* global tinyMCE */
/* global wpseoShortcodePluginL10n */
/* global ajaxurl */
/* global _ */
/* global JSON */
/* global console */
var shortcodeNameMatcher = "[^<>&/\\[\\]\x00-\x20=]+?";
var shortcodeAttributesMatcher = "( [^\\]]+?)?";

var shortcodeStartRegex = new RegExp("\\[" + shortcodeNameMatcher + shortcodeAttributesMatcher + "\\]", "g");
var shortcodeEndRegex = new RegExp("\\[/" + shortcodeNameMatcher + "\\]", "g");

(function () {
	"use strict";

	/**
  * The Yoast Shortcode plugin parses the shortcodes in a given piece of text. It analyzes multiple input fields for shortcodes which it will preload using AJAX.
  *
  * @constructor
  * @property {RegExp} keywordRegex Used to match a given string for valid shortcode keywords.
  * @property {RegExp} closingTagRegex Used to match a given string for shortcode closing tags.
  * @property {RegExp} nonCaptureRegex Used to match a given string for non capturing shortcodes.
  * @property {Array} parsedShortcodes Used to store parsed shortcodes.
  */

	var YoastShortcodePlugin = function YoastShortcodePlugin(app) {
		this._app = app;

		this._app.registerPlugin("YoastShortcodePlugin", { status: "loading" });
		this.bindElementEvents();

		var keywordRegexString = "(" + wpseoShortcodePluginL10n.wpseo_shortcode_tags.join("|") + ")";

		// The regex for matching shortcodes based on the available shortcode keywords.
		this.keywordRegex = new RegExp(keywordRegexString, "g");
		this.closingTagRegex = new RegExp("\\[\\/" + keywordRegexString + "\\]", "g");
		this.nonCaptureRegex = new RegExp("\\[" + keywordRegexString + "[^\\]]*?\\]", "g");

		this.parsedShortcodes = [];

		this.loadShortcodes(this.declareReady.bind(this));
	};

	/* YOAST SEO CLIENT */

	/**
  * Declares ready with YoastSEO.
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.declareReady = function () {
		this._app.pluginReady("YoastShortcodePlugin");
		this.registerModifications();
	};

	/**
  * Declares reloaded with YoastSEO.
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.declareReloaded = function () {
		this._app.pluginReloaded("YoastShortcodePlugin");
	};

	/**
  * Registers the modifications for the content in which we want to replace shortcodes.
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.registerModifications = function () {
		this._app.registerModification("content", this.replaceShortcodes.bind(this), "YoastShortcodePlugin");
	};

	/**
  * Removes all unknown shortcodes. Not all plugins properly registerd their shortcodes in the WordPress backend.
  * Since we cannot use the data from these shortcodes they must be removed.
  *
  * @param {string} data The text to remove unknown shortcodes.
  * @returns {string} The text with removed unknown shortcodes.
  */
	YoastShortcodePlugin.prototype.removeUnknownShortCodes = function (data) {
		data = data.replace(shortcodeStartRegex, "");
		data = data.replace(shortcodeEndRegex, "");

		return data;
	};

	/**
  * The callback used to replace the shortcodes.
  *
  * @param {string} data
  * @returns {string}
  */
	YoastShortcodePlugin.prototype.replaceShortcodes = function (data) {
		var parsedShortcodes = this.parsedShortcodes;

		if (typeof data === "string" && parsedShortcodes.length > 0) {
			for (var i = 0; i < parsedShortcodes.length; i++) {
				data = data.replace(parsedShortcodes[i].shortcode, parsedShortcodes[i].output);
			}
		}

		data = this.removeUnknownShortCodes(data);

		return data;
	};

	/* DATA SOURCING */

	/**
  * Get data from inputfields and store them in an analyzerData object. This object will be used to fill
  * the analyzer and the snippetpreview
  *
  * @param {function} callback To declare either ready or reloaded after parsing.
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.loadShortcodes = function (callback) {
		var unparsedShortcodes = this.getUnparsedShortcodes(this.getShortcodes(this.getContentTinyMCE()));
		if (unparsedShortcodes.length > 0) {
			this.parseShortcodes(unparsedShortcodes, callback);
		} else {
			return callback();
		}
	};

	/**
  * Bind elements to be able to reload the dataset if shortcodes get added.
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.bindElementEvents = function () {
		var contentElement = document.getElementById("content") || false;
		var callback = _.debounce(this.loadShortcodes.bind(this, this.declareReloaded.bind(this)), 500);

		if (contentElement) {
			contentElement.addEventListener("keyup", callback);
			contentElement.addEventListener("change", callback);
		}

		if (typeof tinyMCE !== "undefined" && typeof tinyMCE.on === "function") {
			tinyMCE.on("addEditor", function (e) {
				e.editor.on("change", callback);
				e.editor.on("keyup", callback);
			});
		}
	};

	/**
  * gets content from the content field, if tinyMCE is initialized, use the getContent function to get the data from tinyMCE
  * @returns {String}
  */
	YoastShortcodePlugin.prototype.getContentTinyMCE = function () {
		var val = document.getElementById("content") && document.getElementById("content").value || "";
		if (typeof tinyMCE !== "undefined" && typeof tinyMCE.editors !== "undefined" && tinyMCE.editors.length !== 0) {
			val = tinyMCE.get("content") && tinyMCE.get("content").getContent() || "";
		}

		return val;
	};

	/* SHORTCODE PARSING */

	/**
  * Returns the unparsed shortcodes out of a collection of shortcodes.
  *
  * @param {Array} shortcodes
  * @returns {Array}
  */
	YoastShortcodePlugin.prototype.getUnparsedShortcodes = function (shortcodes) {
		if ((typeof shortcodes === "undefined" ? "undefined" : _typeof(shortcodes)) !== "object") {
			console.error("Failed to get unparsed shortcodes. Expected parameter to be an array, instead received " + (typeof shortcodes === "undefined" ? "undefined" : _typeof(shortcodes)));
			return false;
		}

		var unparsedShortcodes = [];

		for (var i = 0; i < shortcodes.length; i++) {
			var shortcode = shortcodes[i];
			if (unparsedShortcodes.indexOf(shortcode) === -1 && this.isUnparsedShortcode(shortcode)) {
				unparsedShortcodes.push(shortcode);
			}
		}

		return unparsedShortcodes;
	};

	/**
  * Checks if a given shortcode was already parsed.
  *
  * @param {string} shortcode
  * @returns {boolean}
  */
	YoastShortcodePlugin.prototype.isUnparsedShortcode = function (shortcode) {
		var already_exists = false;

		for (var i = 0; i < this.parsedShortcodes.length; i++) {
			if (this.parsedShortcodes[i].shortcode === shortcode) {
				already_exists = true;
			}
		}

		return already_exists === false;
	};

	/**
  * Gets the shortcodes from a given piece of text.
  *
  * @param {string} text
  * @returns {array} The matched shortcodes
  */
	YoastShortcodePlugin.prototype.getShortcodes = function (text) {
		if (typeof text !== "string") {
			/* jshint ignore:start */
			console.error("Failed to get shortcodes. Expected parameter to be a string, instead received" + (typeof text === "undefined" ? "undefined" : _typeof(text)));
			/* jshint ignore:end*/
			return false;
		}

		var captures = this.matchCapturingShortcodes(text);

		// Remove the capturing shortcodes from the text before trying to match the capturing shortcodes.
		for (var i = 0; i < captures.length; i++) {
			text = text.replace(captures[i], "");
		}

		var nonCaptures = this.matchNonCapturingShortcodes(text);

		return captures.concat(nonCaptures);
	};

	/**
  * Matches the capturing shortcodes from a given piece of text.
  *
  * @param {string} text
  * @returns {Array}
  */
	YoastShortcodePlugin.prototype.matchCapturingShortcodes = function (text) {
		var captures = [];

		// First identify which tags are being used in a capturing shortcode by looking for closing tags.
		var captureKeywords = (text.match(this.closingTagRegex) || []).join(" ").match(this.keywordRegex) || [];

		// Fetch the capturing shortcodes and strip them from the text so we can easily match the non capturing shortcodes.
		for (var i = 0; i < captureKeywords.length; i++) {
			var captureKeyword = captureKeywords[i];
			var captureRegex = "\\[" + captureKeyword + "[^\\]]*?\\].*?\\[\\/" + captureKeyword + "\\]";
			var matches = text.match(new RegExp(captureRegex, "g")) || [];

			captures = captures.concat(matches);
		}

		return captures;
	};

	/**
  * Matches the non capturing shortcodes from a given piece of text.
  *
  * @param {string} text
  * @returns {Array}
  */
	YoastShortcodePlugin.prototype.matchNonCapturingShortcodes = function (text) {
		return text.match(this.nonCaptureRegex) || [];
	};

	/**
  * Parses the unparsed shortcodes through AJAX and clears them.
  *
  * @param {Array} shortcodes shortcodes to be parsed.
  * @param {function} callback function to be called in the context of the AJAX callback.
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.parseShortcodes = function (shortcodes, callback) {
		if (typeof callback !== "function") {
			/* jshint ignore:start */
			console.error("Failed to parse shortcodes. Expected parameter to be a function, instead received " + (typeof callback === "undefined" ? "undefined" : _typeof(callback)));
			/* jshint ignore:end */
			return false;
		}

		if ((typeof shortcodes === "undefined" ? "undefined" : _typeof(shortcodes)) === "object" && shortcodes.length > 0) {
			jQuery.post(ajaxurl, {
				action: "wpseo_filter_shortcodes",
				_wpnonce: wpseoShortcodePluginL10n.wpseo_filter_shortcodes_nonce,
				data: shortcodes
			}, function (shortcodeResults) {
				this.saveParsedShortcodes(shortcodeResults, callback);
			}.bind(this));
		} else {
			return callback();
		}
	};

	/**
  * Saves the shortcodes that were parsed with AJAX to `this.parsedShortcodes`
  *
  * @param {Array} shortcodeResults
  * @param {function} callback
  *
  * @returns {void}
  */
	YoastShortcodePlugin.prototype.saveParsedShortcodes = function (shortcodeResults, callback) {
		shortcodeResults = JSON.parse(shortcodeResults);
		for (var i = 0; i < shortcodeResults.length; i++) {
			this.parsedShortcodes.push(shortcodeResults[i]);
		}

		callback();
	};

	window.YoastShortcodePlugin = YoastShortcodePlugin;
})();

},{}]},{},[1]);


text:
package dhcp6_test

// Tested using dhcp6_test package to allow use of dhcp6test package.

import (
	"testing"

	"github.com/mdlayher/dhcp6"
	"github.com/mdlayher/dhcp6/dhcp6test"
)

// TestServeMuxHandleNoResponse verifies that no Handler is invoked when a
// ServeMux does not have a Handler registered for a given message type.
func TestServeMuxHandleNoResponse(t *testing.T) {
	mux := dhcp6.NewServeMux()

	r, err := dhcp6.ParseRequest([]byte{1, 1, 2, 3}, nil)
	if err != nil {
		t.Fatal(err)
	}

	w := dhcp6test.NewRecorder(r.TransactionID)
	mux.ServeDHCP(w, r)

	if mt := w.MessageType; mt != dhcp6.MessageType(0) {
		t.Fatalf("reply packet empty, but got message type: %v", mt)
	}
	if l := len(w.Options()); l > 0 {
		t.Fatalf("reply packet empty, but got %d options", l)
	}
}

// TestServeMuxHandleOK verifies that a Handler is invoked when a ServeMux
// has a Handler registered for a given message type.
func TestServeMuxHandleOK(t *testing.T) {
	mux := dhcp6.NewServeMux()
	mt := dhcp6.MessageTypeSolicit

	mux.Handle(mt, &solicitHandler{})

	r, err := dhcp6.ParseRequest([]byte{byte(mt), 0, 1, 2}, nil)
	if err != nil {
		t.Fatal(err)
	}

	w := dhcp6test.NewRecorder(r.TransactionID)
	mux.ServeDHCP(w, r)

	if want, got := dhcp6.MessageTypeAdvertise, w.MessageType; want != got {
		t.Fatalf("unexpected response message type: %v != %v", want, got)
	}
}

// TestServeMuxHandleFuncOK verifies that a normal function which can be used
// as a Handler is invoked when a ServeMux has a HandlerFunc registered for
// a given message type.
func TestServeMuxHandleFuncOK(t *testing.T) {
	mux := dhcp6.NewServeMux()
	mt := dhcp6.MessageTypeSolicit

	mux.HandleFunc(mt, solicit)

	r, err := dhcp6.ParseRequest([]byte{byte(mt), 0, 1, 2}, nil)
	if err != nil {
		t.Fatal(err)
	}

	w := dhcp6test.NewRecorder(r.TransactionID)
	mux.ServeDHCP(w, r)

	if want, got := dhcp6.MessageTypeAdvertise, w.MessageType; want != got {
		t.Fatalf("unexpected response message type: %v != %v", want, got)
	}
}

// solicitHandler is a Handler which returns an Advertise in reply
// to a Solicit request.
type solicitHandler struct{}

func (h *solicitHandler) ServeDHCP(w dhcp6.ResponseSender, r *dhcp6.Request) {
	solicit(w, r)
}

// solicit is a function which can be adapted as a HandlerFunc.
func solicit(w dhcp6.ResponseSender, r *dhcp6.Request) {
	w.Send(dhcp6.MessageTypeAdvertise)
}


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<html>
<head>

  <title>iron-meta-basic</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
  <script src="../../web-component-tester/browser.js"></script>

  <link rel="import" href="../iron-meta.html">

</head>
<body>
  <iron-meta key="info" value="foo/bar"></iron-meta>

  <script>

    suite('basic', function() {

      test('byKey', function() {
        var meta = new Polymer.IronMeta({
          key: 'info'
        });

        expect(meta.value).to.be.eql('foo/bar');
      });

      test('list', function() {
        assert.equal(document.querySelector('iron-meta').list.length, 1);
      });

      test('constructor with no arguments', function() {
        expect(function() {
          new Polymer.IronMeta();
        }).to.not.throw();
      });

    });

  </script>

</body>
</html>


text:
package org.takes.facets.auth.codecs;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import lombok.EqualsAndHashCode;
import org.takes.facets.auth.Identity;
import org.takes.misc.Utf8String;

/**
 * Plain codec.
 *
 * <p>The class is immutable and thread-safe.
 *
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 0.1
 */
@EqualsAndHashCode
public final class CcPlain implements Codec {

    @Override
    public byte[] encode(final Identity identity) throws IOException {
        final String encoding = Charset.defaultCharset().name();
        final StringBuilder text = new StringBuilder(
            URLEncoder.encode(identity.urn(), encoding)
        );
        for (final Map.Entry<String, String> ent
            : identity.properties().entrySet()) {
            text.append(';')
                .append(ent.getKey())
                .append('=')
                .append(URLEncoder.encode(ent.getValue(), encoding));
        }
        return new Utf8String(text.toString()).bytes();
    }

    @Override
    public Identity decode(final byte[] bytes) throws IOException {
        final String[] parts = new Utf8String(bytes).string().split(";");
        final Map<String, String> map = new HashMap<>(parts.length);
        for (int idx = 1; idx < parts.length; ++idx) {
            final String[] pair = parts[idx].split("=");
            try {
                map.put(pair[0], CcPlain.decode(pair[1]));
            } catch (final IllegalArgumentException ex) {
                throw new DecodingException(ex);
            }
        }
        return new Identity.Simple(CcPlain.decode(parts[0]), map);
    }

    /**
     * Decode from URL.
     * @param text The text
     * @return Decoded
     * @throws UnsupportedEncodingException If fails
     */
    private static String decode(final String text)
        throws UnsupportedEncodingException {
        try {
            return URLDecoder.decode(text, Charset.defaultCharset().name());
        } catch (final IllegalArgumentException ex) {
            throw new DecodingException(ex);
        }
    }

}


text:
class Ghee

  # API module encapsulates all of API endpoints
  # implemented thus far
  #
  module API

    module Repos
      module Issues
        class Proxy < ::Ghee::ResourceProxy
          def search(term, state = "open")
            url = "./legacy/issues/search/#{@repo.repo_name}/#{state}/#{term}"
            Ghee::API::Search::Issues::Proxy.new(connection, url)
          end
        end
      end
    end

    # The Search module handles all of the Github Search
    # API endpoints
    #
    module Search
      module Issues
        class Proxy < ::Ghee::ResourceProxy
        end
      end
      class Proxy < ::Ghee::ResourceProxy
        def issues(repo, term, state = "open")
            url = "./legacy/issues/search/#{repo}/#{state}/#{term}"
            Issues::Proxy.new(connection, url)
        end
      end
    end
  end

  def search
    API::Search::Proxy.new(connection,"")
  end
end


text:
package org.apache.cloudstack.network.element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import org.apache.cloudstack.api.command.admin.internallb.ConfigureInternalLoadBalancerElementCmd;
import org.apache.cloudstack.api.command.admin.internallb.CreateInternalLoadBalancerElementCmd;
import org.apache.cloudstack.api.command.admin.internallb.ListInternalLoadBalancerElementsCmd;
import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager;

import com.cloud.agent.api.to.LoadBalancerTO;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PublicIpAddress;
import com.cloud.network.VirtualRouterProvider;
import com.cloud.network.VirtualRouterProvider.Type;
import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.VirtualRouterProviderDao;
import com.cloud.network.element.IpDeployer;
import com.cloud.network.element.LoadBalancingServiceProvider;
import com.cloud.network.element.VirtualRouterElement;
import com.cloud.network.element.VirtualRouterProviderVO;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.rules.LoadBalancerContainer;
import com.cloud.network.rules.LoadBalancerContainer.Scheme;
import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.QueryBuilder;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.Ip;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.DomainRouterDao;

public class InternalLoadBalancerElement extends AdapterBase implements LoadBalancingServiceProvider, InternalLoadBalancerElementService, IpDeployer {
    private static final Logger s_logger = Logger.getLogger(InternalLoadBalancerElement.class);
    protected static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
    private static InternalLoadBalancerElement internalLbElement = null;

    @Inject
    NetworkModel _ntwkModel;
    @Inject
    NetworkServiceMapDao _ntwkSrvcDao;
    @Inject
    DomainRouterDao _routerDao;
    @Inject
    VirtualRouterProviderDao _vrProviderDao;
    @Inject
    PhysicalNetworkServiceProviderDao _pNtwkSvcProviderDao;
    @Inject
    InternalLoadBalancerVMManager _internalLbMgr;
    @Inject
    ConfigurationManager _configMgr;
    @Inject
    AccountManager _accountMgr;
    @Inject
    ApplicationLoadBalancerRuleDao _appLbDao;
    @Inject
    EntityManager _entityMgr;

    protected InternalLoadBalancerElement() {
    }

    public static InternalLoadBalancerElement getInstance() {
        if (internalLbElement == null) {
            internalLbElement = new InternalLoadBalancerElement();
        }
        return internalLbElement;
    }

    private boolean canHandle(Network config, Scheme lbScheme) {
        //works in Advance zone only
        DataCenter dc = _entityMgr.findById(DataCenter.class, config.getDataCenterId());
        if (dc.getNetworkType() != NetworkType.Advanced) {
            s_logger.trace("Not hanling zone of network type " + dc.getNetworkType());
            return false;
        }
        if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) {
            s_logger.trace("Not handling network with Type  " + config.getGuestType() + " and traffic type " + config.getTrafficType());
            return false;
        }

        Map<Capability, String> lbCaps = getCapabilities().get(Service.Lb);
        if (!lbCaps.isEmpty()) {
            String schemeCaps = lbCaps.get(Capability.LbSchemes);
            if (schemeCaps != null && lbScheme != null) {
                if (!schemeCaps.contains(lbScheme.toString())) {
                    s_logger.debug("Scheme " + lbScheme.toString() + " is not supported by the provider " + getName());
                    return false;
                }
            }
        }

        if (!_ntwkModel.isProviderSupportServiceInNetwork(config.getId(), Service.Lb, getProvider())) {
            s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + Service.Lb + " in the network " + config);
            return false;
        }
        return true;
    }

    @Override
    public Map<Service, Map<Capability, String>> getCapabilities() {
        return capabilities;
    }

    @Override
    public Provider getProvider() {
        return Provider.InternalLbVm;
    }

    @Override
    public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
        ResourceUnavailableException, InsufficientCapacityException {

        if (!canHandle(network, null)) {
            s_logger.trace("No need to implement " + getName());
            return true;
        }

        return implementInternalLbVms(network, dest);
    }

    @Override
    public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
        throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {

        if (!canHandle(network, null)) {
            s_logger.trace("No need to prepare " + getName());
            return true;
        }

        if (vm.getType() == VirtualMachine.Type.User) {
            return implementInternalLbVms(network, dest);
        }
        return true;
    }

    protected boolean implementInternalLbVms(Network network, DeployDestination dest) throws ResourceUnavailableException {
        //1) Get all the Ips from the network having LB rules assigned
        List<String> ips = _appLbDao.listLbIpsBySourceIpNetworkIdAndScheme(network.getId(), Scheme.Internal);

        //2) Start internal lb vms for the ips having active rules
        for (String ip : ips) {
            Ip sourceIp = new Ip(ip);
            long active = _appLbDao.countActiveBySourceIp(sourceIp, network.getId());
            if (active > 0) {
                s_logger.debug("Have to implement internal lb vm for source ip " + sourceIp + " as a part of network " + network + " implement as there are " + active +
                    " internal lb rules exist for this ip");
                List<? extends VirtualRouter> internalLbVms;
                try {
                    internalLbVms = _internalLbMgr.deployInternalLbVm(network, sourceIp, dest, _accountMgr.getAccount(network.getAccountId()), null);
                } catch (InsufficientCapacityException e) {
                    s_logger.warn("Failed to deploy element " + getName() + " for ip " + sourceIp + " due to:", e);
                    return false;
                } catch (ConcurrentOperationException e) {
                    s_logger.warn("Failed to deploy element " + getName() + " for ip " + sourceIp + " due to:", e);
                    return false;
                }

                if (internalLbVms == null || internalLbVms.isEmpty()) {
                    throw new ResourceUnavailableException("Can't deploy " + getName() + " to handle LB rules", DataCenter.class, network.getDataCenterId());
                }
            }
        }

        return true;
    }

    @Override
    public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException,
        ResourceUnavailableException {
        return true;
    }

    @Override
    public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
        List<? extends VirtualRouter> internalLbVms = _routerDao.listByNetworkAndRole(network.getId(), Role.INTERNAL_LB_VM);
        if (internalLbVms == null || internalLbVms.isEmpty()) {
            return true;
        }
        boolean result = true;
        for (VirtualRouter internalLbVm : internalLbVms) {
            result = result && _internalLbMgr.destroyInternalLbVm(internalLbVm.getId(), context.getAccount(), context.getCaller().getId());
            if (cleanup) {
                if (!result) {
                    s_logger.warn("Failed to stop internal lb element " + internalLbVm + ", but would try to process clean up anyway.");
                }
                result = (_internalLbMgr.destroyInternalLbVm(internalLbVm.getId(), context.getAccount(), context.getCaller().getId()));
                if (!result) {
                    s_logger.warn("Failed to clean up internal lb element " + internalLbVm);
                }
            }
        }
        return result;
    }

    @Override
    public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
        List<? extends VirtualRouter> internalLbVms = _routerDao.listByNetworkAndRole(network.getId(), Role.INTERNAL_LB_VM);
        if (internalLbVms == null || internalLbVms.isEmpty()) {
            return true;
        }
        boolean result = true;
        for (VirtualRouter internalLbVm : internalLbVms) {
            result = result && (_internalLbMgr.destroyInternalLbVm(internalLbVm.getId(), context.getAccount(), context.getCaller().getId()));
        }
        return result;
    }

    @Override
    public boolean isReady(PhysicalNetworkServiceProvider provider) {
        VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.InternalLbVm);
        if (element == null) {
            return false;
        }
        return element.isEnabled();
    }

    @Override
    public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
        ResourceUnavailableException {
        VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.InternalLbVm);
        if (element == null) {
            return true;
        }
        long elementId = element.getId();
        List<DomainRouterVO> internalLbVms = _routerDao.listByElementId(elementId);
        boolean result = true;
        for (DomainRouterVO internalLbVm : internalLbVms) {
            result = result && (_internalLbMgr.destroyInternalLbVm(internalLbVm.getId(), context.getAccount(), context.getCaller().getId()));
        }
        _vrProviderDao.remove(elementId);

        return result;
    }

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

    @Override
    public boolean verifyServicesCombination(Set<Service> services) {
        return true;
    }

    @Override
    public IpDeployer getIpDeployer(Network network) {
        return this;
    }

    @Override
    public boolean applyLBRules(Network network, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
        //1) Get Internal LB VMs to destroy
        Set<Ip> vmsToDestroy = getVmsToDestroy(network, rules);

        //2) Get rules to apply
        Map<Ip, List<LoadBalancingRule>> rulesToApply = getLbRulesToApply(rules);
        s_logger.debug("Applying " + rulesToApply.size() + " on element " + getName());

        for (Ip sourceIp : vmsToDestroy) {
            //2.1 Destroy internal lb vm
            List<? extends VirtualRouter> vms = _internalLbMgr.findInternalLbVms(network.getId(), sourceIp);
            if (vms.size() > 0) {
                //only one internal lb per IP exists
                try {
                    s_logger.debug(String.format("Destroying internal lb vm for ip %s as all the rules for this vm are in Revoke state", sourceIp.addr()));
                    return _internalLbMgr.destroyInternalLbVm(vms.get(0).getId(), _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM),
                            _accountMgr.getUserIncludingRemoved(User.UID_SYSTEM).getId());
                } catch (ConcurrentOperationException e) {
                    s_logger.warn(String.format("Failed to apply lb rule(s) for ip %s on the element %s due to: ", sourceIp.addr(), getName()), e);
                    return false;
                }
            }

            rulesToApply.remove(sourceIp);
        }

        for (Map.Entry<Ip,List<LoadBalancingRule>> entry : rulesToApply.entrySet()) {
            Ip sourceIp = entry.getKey();
            //2.2 Start Internal LB vm per IP address
            List<? extends VirtualRouter> internalLbVms;
            try {
                DeployDestination dest = new DeployDestination(_entityMgr.findById(DataCenter.class, network.getDataCenterId()), null, null, null);
                internalLbVms = _internalLbMgr.deployInternalLbVm(network, sourceIp, dest, _accountMgr.getAccount(network.getAccountId()), null);
            } catch (InsufficientCapacityException e) {
                s_logger.warn(String.format("Failed to apply lb rule(s) for ip %s on the element %s due to: ", sourceIp.addr(), getName()), e);
                return false;
            } catch (ConcurrentOperationException e) {
                s_logger.warn(String.format("Failed to apply lb rule(s) for ip %s on the element %s due to: ", sourceIp.addr(), getName()), e);
                return false;
            }

            if (internalLbVms == null || internalLbVms.isEmpty()) {
                throw new ResourceUnavailableException("Can't find/deploy internal lb vm to handle LB rules",
                        DataCenter.class, network.getDataCenterId());
            }

            //2.3 Apply Internal LB rules on the VM
            if (!_internalLbMgr.applyLoadBalancingRules(network, entry.getValue(), internalLbVms)) {
                throw new CloudRuntimeException("Failed to apply load balancing rules for ip " + sourceIp.addr() +
                        " in network " + network.getId() + " on element " + getName());
            }
        }

        return true;
    }

    protected Map<Ip, List<LoadBalancingRule>> getLbRulesToApply(List<LoadBalancingRule> rules) {
        //Group rules by the source ip address as NetworkManager always passes the entire network lb config to the element
        Map<Ip, List<LoadBalancingRule>> rulesToApply = groupBySourceIp(rules);

        return rulesToApply;
    }

    protected Set<Ip> getVmsToDestroy(Network network, List<LoadBalancingRule> rules) {
        //1) Group rules by the source ip address as NetworkManager always passes the entire network lb config to the element
        Set<Ip> lbPublicIps = new HashSet<Ip>();
        Set<Ip> vmsToDestroy = new HashSet<Ip>();

        for (LoadBalancingRule rule : rules) {
            lbPublicIps.add(rule.getSourceIp());
        }

        for (Ip sourceIp : lbPublicIps) {
            //2) Check if there are non revoked rules for the source ip address
            if (_appLbDao.countBySourceIpAndNotRevoked(sourceIp, network.getId()) == 0) {
                s_logger.debug("Have to destroy internal lb vm for source ip " + sourceIp + " as it has 0 rules in non-Revoke state");
                vmsToDestroy.add(sourceIp);
            }
        }
        return vmsToDestroy;
    }

    protected Map<Ip, List<LoadBalancingRule>> groupBySourceIp(List<LoadBalancingRule> rules) {
        Map<Ip, List<LoadBalancingRule>> groupedRules = new HashMap<Ip, List<LoadBalancingRule>>();
        for (LoadBalancingRule rule : rules) {
            if (rule.getDestinations() != null && !rule.getDestinations().isEmpty()) {
                Ip sourceIp = rule.getSourceIp();
                if (!groupedRules.containsKey(sourceIp)) {
                    groupedRules.put(sourceIp, null);
                }

                List<LoadBalancingRule> rulesToApply = groupedRules.get(sourceIp);
                if (rulesToApply == null) {
                    rulesToApply = new ArrayList<LoadBalancingRule>();
                }
                rulesToApply.add(rule);
                groupedRules.put(sourceIp, rulesToApply);
            } else {
                s_logger.debug("Internal lb rule " + rule + " doesn't have any vms assigned, skipping");
            }
        }
        return groupedRules;
    }

    @Override
    public boolean validateLBRule(Network network, LoadBalancingRule rule) {
        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
        rules.add(rule);
        if (canHandle(network, rule.getScheme())) {
            List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.INTERNAL_LB_VM);
            if (routers == null || routers.isEmpty()) {
                return true;
            }
            return VirtualRouterElement.validateHAProxyLBRule(rule);
        }
        return true;
    }

    @Override
    public List<LoadBalancerTO> updateHealthChecks(Network network, List<LoadBalancingRule> lbrules) {
        return null;
    }

    @Override
    public boolean handlesOnlyRulesInTransitionState() {
        return false;
    }

    private static Map<Service, Map<Capability, String>> setCapabilities() {
        Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();

        // Set capabilities for LB service
        Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
        lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source");
        lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated");
        lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp");
        lbCapabilities.put(Capability.SupportedStickinessMethods, VirtualRouterElement.getHAProxyStickinessCapability());
        lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Internal.toString());

        capabilities.put(Service.Lb, lbCapabilities);
        return capabilities;
    }

    @Override
    public List<Class<?>> getCommands() {
        List<Class<?>> cmdList = new ArrayList<Class<?>>();
        cmdList.add(CreateInternalLoadBalancerElementCmd.class);
        cmdList.add(ConfigureInternalLoadBalancerElementCmd.class);
        cmdList.add(ListInternalLoadBalancerElementsCmd.class);
        return cmdList;
    }

    @Override
    public VirtualRouterProvider configureInternalLoadBalancerElement(long id, boolean enable) {
        VirtualRouterProviderVO element = _vrProviderDao.findById(id);
        if (element == null || element.getType() != Type.InternalLbVm) {
            throw new InvalidParameterValueException("Can't find " + getName() + " element with network service provider id " + id + " to be used as a provider for " +
                getName());
        }

        element.setEnabled(enable);
        element = _vrProviderDao.persist(element);

        return element;
    }

    @Override
    public VirtualRouterProvider addInternalLoadBalancerElement(long ntwkSvcProviderId) {
        VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(ntwkSvcProviderId, Type.InternalLbVm);
        if (element != null) {
            s_logger.debug("There is already an " + getName() + " with service provider id " + ntwkSvcProviderId);
            return null;
        }

        PhysicalNetworkServiceProvider provider = _pNtwkSvcProviderDao.findById(ntwkSvcProviderId);
        if (provider == null || !provider.getProviderName().equalsIgnoreCase(getName())) {
            throw new InvalidParameterValueException("Invalid network service provider is specified");
        }

        element = new VirtualRouterProviderVO(ntwkSvcProviderId, Type.InternalLbVm);
        element = _vrProviderDao.persist(element);
        return element;
    }

    @Override
    public VirtualRouterProvider getInternalLoadBalancerElement(long id) {
        VirtualRouterProvider provider = _vrProviderDao.findById(id);
        if (provider == null || provider.getType() != Type.InternalLbVm) {
            throw new InvalidParameterValueException("Unable to find " + getName() + " by id");
        }
        return provider;
    }

    @Override
    public List<? extends VirtualRouterProvider> searchForInternalLoadBalancerElements(Long id, Long ntwkSvsProviderId, Boolean enabled) {

        QueryBuilder<VirtualRouterProviderVO> sc = QueryBuilder.create(VirtualRouterProviderVO.class);
        if (id != null) {
            sc.and(sc.entity().getId(), Op.EQ, id);
        }
        if (ntwkSvsProviderId != null) {
            sc.and(sc.entity().getNspId(), Op.EQ, ntwkSvsProviderId);
        }
        if (enabled != null) {
            sc.and(sc.entity().isEnabled(), Op.EQ, enabled);
        }

        //return only Internal LB elements
        sc.and(sc.entity().getType(), Op.EQ, VirtualRouterProvider.Type.InternalLbVm);

        return sc.list();
    }

    @Override
    public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> services) throws ResourceUnavailableException {
        //do nothing here; this element just has to extend the ip deployer
        //as the LB service implements IPDeployerRequester
        return true;
    }

}


text:
require 'test_helper'

module Adtadmin
  class ReviewsControllerTest < ActionController::TestCase
    setup do
      @review = reviews(:one)
    end

    test "should get index" do
      get :index
      assert_response :success
      assert_not_nil assigns(:reviews)
    end

    test "should get new" do
      get :new
      assert_response :success
    end

    test "should create review" do
      assert_difference('Review.count') do
        post :create, review: { adress: @review.adress, description: @review.description, name: @review.name, phone: @review.phone, post_id: @review.post_id, typereview_id: @review.typereview_id }
      end

      assert_redirected_to review_path(assigns(:review))
    end

    test "should show review" do
      get :show, id: @review
      assert_response :success
    end

    test "should get edit" do
      get :edit, id: @review
      assert_response :success
    end

    test "should update review" do
      put :update, id: @review, review: { adress: @review.adress, description: @review.description, name: @review.name, phone: @review.phone, post_id: @review.post_id, typereview_id: @review.typereview_id }
      assert_redirected_to review_path(assigns(:review))
    end

    test "should destroy review" do
      assert_difference('Review.count', -1) do
        delete :destroy, id: @review
      end

      assert_redirected_to reviews_path
    end
  end
end


text:
package com.azure.resourcemanager.sqlvirtualmachine.generated;

import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.sqlvirtualmachine.fluent.models.SqlVirtualMachineGroupProperties;
import com.azure.resourcemanager.sqlvirtualmachine.models.ClusterSubnetType;
import com.azure.resourcemanager.sqlvirtualmachine.models.SqlVmGroupImageSku;
import com.azure.resourcemanager.sqlvirtualmachine.models.WsfcDomainProfile;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public final class SqlVirtualMachineGroupPropertiesTests {
    @Test
    public void testDeserialize() {
        SqlVirtualMachineGroupProperties model =
            BinaryData
                .fromString(
                    "{\"provisioningState\":\"g\",\"sqlImageOffer\":\"tnwu\",\"sqlImageSku\":\"Developer\",\"scaleType\":\"HA\",\"clusterManagerType\":\"WSFC\",\"clusterConfiguration\":\"Domainful\",\"wsfcDomainProfile\":{\"domainFqdn\":\"ckyfih\",\"ouPath\":\"idf\",\"clusterBootstrapAccount\":\"wdzuhtymwisd\",\"clusterOperatorAccount\":\"thwxmnteiwaopvkm\",\"sqlServiceAccount\":\"c\",\"fileShareWitnessPath\":\"xdcu\",\"storageAccountUrl\":\"fsrpymzidnse\",\"storageAccountPrimaryKey\":\"fakeStorageAccountPrimaryKeyPlaceholder\",\"clusterSubnetType\":\"MultiSubnet\"}}")
                .toObject(SqlVirtualMachineGroupProperties.class);
        Assertions.assertEquals("tnwu", model.sqlImageOffer());
        Assertions.assertEquals(SqlVmGroupImageSku.DEVELOPER, model.sqlImageSku());
        Assertions.assertEquals("ckyfih", model.wsfcDomainProfile().domainFqdn());
        Assertions.assertEquals("idf", model.wsfcDomainProfile().ouPath());
        Assertions.assertEquals("wdzuhtymwisd", model.wsfcDomainProfile().clusterBootstrapAccount());
        Assertions.assertEquals("thwxmnteiwaopvkm", model.wsfcDomainProfile().clusterOperatorAccount());
        Assertions.assertEquals("c", model.wsfcDomainProfile().sqlServiceAccount());
        Assertions.assertEquals("xdcu", model.wsfcDomainProfile().fileShareWitnessPath());
        Assertions.assertEquals("fsrpymzidnse", model.wsfcDomainProfile().storageAccountUrl());
        Assertions.assertEquals("fakeStorageAccountPrimaryKeyPlaceholder", model.wsfcDomainProfile().storageAccountPrimaryKey());
        Assertions.assertEquals(ClusterSubnetType.MULTI_SUBNET, model.wsfcDomainProfile().clusterSubnetType());
    }

    @Test
    public void testSerialize() {
        SqlVirtualMachineGroupProperties model =
            new SqlVirtualMachineGroupProperties()
                .withSqlImageOffer("tnwu")
                .withSqlImageSku(SqlVmGroupImageSku.DEVELOPER)
                .withWsfcDomainProfile(
                    new WsfcDomainProfile()
                        .withDomainFqdn("ckyfih")
                        .withOuPath("idf")
                        .withClusterBootstrapAccount("wdzuhtymwisd")
                        .withClusterOperatorAccount("thwxmnteiwaopvkm")
                        .withSqlServiceAccount("c")
                        .withFileShareWitnessPath("xdcu")
                        .withStorageAccountUrl("fsrpymzidnse")
                        .withStorageAccountPrimaryKey("fakeStorageAccountPrimaryKeyPlaceholder")
                        .withClusterSubnetType(ClusterSubnetType.MULTI_SUBNET));
        model = BinaryData.fromObject(model).toObject(SqlVirtualMachineGroupProperties.class);
        Assertions.assertEquals("tnwu", model.sqlImageOffer());
        Assertions.assertEquals(SqlVmGroupImageSku.DEVELOPER, model.sqlImageSku());
        Assertions.assertEquals("ckyfih", model.wsfcDomainProfile().domainFqdn());
        Assertions.assertEquals("idf", model.wsfcDomainProfile().ouPath());
        Assertions.assertEquals("wdzuhtymwisd", model.wsfcDomainProfile().clusterBootstrapAccount());
        Assertions.assertEquals("thwxmnteiwaopvkm", model.wsfcDomainProfile().clusterOperatorAccount());
        Assertions.assertEquals("c", model.wsfcDomainProfile().sqlServiceAccount());
        Assertions.assertEquals("xdcu", model.wsfcDomainProfile().fileShareWitnessPath());
        Assertions.assertEquals("fsrpymzidnse", model.wsfcDomainProfile().storageAccountUrl());
        Assertions.assertEquals("fakeStorageAccountPrimaryKeyPlaceholder", model.wsfcDomainProfile().storageAccountPrimaryKey());
        Assertions.assertEquals(ClusterSubnetType.MULTI_SUBNET, model.wsfcDomainProfile().clusterSubnetType());
    }
}


text:
package org.wel4j;

import org.wel4j.WindowsEvent;

public class WindowsEventLogImpl implements WindowsEventLog {

	private static final String BASE_DLL_NAME = "wel4j";

	private static final String X86_DLL_NAME = BASE_DLL_NAME + "32";

	private static final String X64_DLL_NAME = BASE_DLL_NAME + "64";

	private static final boolean DEBUG;

	private static WindowsEventLog instance;

	/**
	 * Protected constructor.
	 */
	protected WindowsEventLogImpl() {
	}

	static {
		DEBUG = (System.getProperty("org.wel4j.debug") != null);

		try {
			if (System.getProperty("os.name").toLowerCase().indexOf("win") != -1) {
				if (System.getProperty("os.arch").indexOf("64") != -1) {
					System.loadLibrary(X64_DLL_NAME);
				} else {
					System.loadLibrary(X86_DLL_NAME);
				}

				instance = new WindowsEventLogImpl();
			} else {
				// TODO print warning
			}
		} catch (Exception e) {
			System.err.println("Failed to load native JNI library.");
			e.printStackTrace();
		}
	}

	private native static void reportEvent(String sourceName, String eventMessage, int eventId, int eventSeverity, int eventCategory);

	public void log(String sourceName, String eventMessage, int eventId, int eventSeverity, int eventCategory) {
		if (sourceName == null || sourceName.length() == 0) {
			sourceName = BASE_DLL_NAME;
		}

		StringBuilder sb = null;
		if (DEBUG) {
			sb = new StringBuilder("[sourceName=")
				.append(sourceName)
				.append(",eventMessage=")
				.append(eventMessage)
				.append(",eventId=")
				.append(eventId)
				.append(",eventSeverity=")
				.append(eventSeverity)
				.append(",eventCategory=")
				.append(eventCategory)
				.append("].");

			System.out.println("Logging event " + sb.toString());
		}

		reportEvent(sourceName, eventMessage, eventId, eventSeverity, eventCategory);

		if (DEBUG) {
				System.out.println("Event logging complete for " + sb.toString());
		}
	}

	public void log(WindowsEvent windowsEvent) {
		log(windowsEvent.getSourceName(), windowsEvent.getMessage(), windowsEvent.getEventID(), windowsEvent.getEventSeverity().getSeverityCode(), windowsEvent.getEventCategory());
	}

	public static WindowsEventLog getInstance() {
		return instance;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_oauth"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hardikgoswami.oauthLibGithub.OauthActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


text:
require 'spec_helper'

describe 'admin/difficulty_levels/index' do

  it 'renders difficulty levels' do
    @difficulty_level = create(:difficulty_level)
    assign :conference, @difficulty_level.conference
    render
    expect(rendered).to include('Example Difficulty Level')
    expect(rendered).to include('Lorem Ipsum dolsum')
    expect(rendered).to include('#ffffff')
  end
end


text:
<?php
/**
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
require dirname(__DIR__) . '/vendor/cakephp/cakephp/src/basics.php';
require_once dirname(__DIR__) . '/vendor/autoload.php';

define('ROOT', dirname(__DIR__));
define('APP_DIR', 'src');

define('APP', rtrim(sys_get_temp_dir(), DS) . DS . APP_DIR . DS);
if (!is_dir(APP)) {
    mkdir(APP, 0770, true);
}

define('CONFIG', ROOT . DS . 'config' . DS);

define('TMP', ROOT . DS . 'tmp' . DS);
if (!is_dir(TMP)) {
    mkdir(TMP, 0770, true);
}

define('LOGS', TMP . 'logs' . DS);
define('CACHE', TMP . 'cache' . DS);

define('CAKE_CORE_INCLUDE_PATH', ROOT . '/vendor/cakephp/cakephp');
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);

Cake\Core\Configure::write('App', [
    'namespace' => 'App'
]);

Cake\Core\Configure::write('debug', true);

$cache = [
    'default' => [
        'engine' => 'File',
        'path' => CACHE
    ],
    '_cake_core_' => [
        'className' => 'File',
        'prefix' => 'crud_myapp_cake_core_',
        'path' => CACHE . 'persistent/',
        'serialize' => true,
        'duration' => '+10 seconds'
    ],
    '_cake_model_' => [
        'className' => 'File',
        'prefix' => 'crud_my_app_cake_model_',
        'path' => CACHE . 'models/',
        'serialize' => 'File',
        'duration' => '+10 seconds'
    ]
];

Cake\Cache\Cache::config($cache);

Cake\Core\Plugin::load('HierAuth', ['path' => ROOT]);

if (!getenv('db_class')) {
    putenv('db_class=Cake\Database\Driver\Sqlite');
    putenv('db_dsn=sqlite::memory:');
}

Cake\Datasource\ConnectionManager::config('test', [
    'className' => 'Cake\Database\Connection',
    'driver' => getenv('db_class'),
    'dsn' => getenv('db_dsn'),
    'database' => getenv('db_database'),
    'username' => getenv('db_username'),
    'password' => getenv('db_password'),
    'timezone' => 'UTC',
    'quoteIdentifiers' => true,
    'cacheMetadata' => true,
]);