text:
package com.criteo.dev.cluster.aws

import java.util
import java.util.Properties

import com.criteo.dev.cluster.aws.AwsUtilities.NodeRole.NodeRole
import com.criteo.dev.cluster.s3.BucketUtilities
import com.criteo.dev.cluster.{GeneralConstants, GeneralUtilities}
import com.google.common.base.Predicate
import com.google.common.collect.ImmutableSetMultimap
import org.jclouds.aws.ec2.AWSEC2Api
import org.jclouds.compute.config.ComputeServiceProperties
import org.jclouds.compute.domain.NodeMetadata.Status
import org.jclouds.compute.domain.{ComputeMetadata, NodeMetadata}
import org.jclouds.compute.{ComputeService, ComputeServiceContext}
import org.jclouds.ec2.EC2Api
import org.jclouds.ec2.domain.Image
import org.jclouds.ec2.features.TagApi
import org.jclouds.{Constants, ContextBuilder}
import org.joda.time.DateTime
import org.scala_tools.time.Imports._
import org.slf4j.LoggerFactory

import scala.collection.JavaConverters._
import scala.collection.JavaConversions._
import scala.util.Random

/**
  * Generic utilities for accessing AWS nodes.
  */
object AwsUtilities {

  private val logger = LoggerFactory.getLogger(AwsUtilities.getClass)

  def getAwsProp(conf: Map[String, String], propKey: String) : String = {
    GeneralUtilities.getConfStrict(conf, s"${AwsConstants.awsKeyPrefix}.$propKey", GeneralConstants.targetAwsProps)
  }

  //--- AWS API---

  def getComputeService(conf: Map[String, String]) : ComputeService = {

    val keyid = getAwsProp(conf, AwsConstants.accessId)
    val key = getAwsProp(conf, AwsConstants.accessKey)
    val region = getAwsProp(conf, AwsConstants.region)
    val overrides = getEc2Overrides(region)

    logger.info(s"Connecting to AWS in region ${region}")

    //create the node using jcloud
    val mComputeServiceContext = ContextBuilder
      .newBuilder("aws-ec2")
      .credentials(keyid, key)
        .endpoint(s"https://ec2.${region}.amazonaws.com")
      .overrides(overrides)
      .buildView(classOf[ComputeServiceContext])
    mComputeServiceContext.getComputeService()
  }

  def getEc2Api(conf: Map[String, String]) : AWSEC2Api = {

    val keyid = getAwsProp(conf, AwsConstants.accessId)
    val key = getAwsProp(conf, AwsConstants.accessKey)
    val region = getAwsProp(conf, AwsConstants.region)
    val overrides = getEc2Overrides(region)

    logger.info(s"Connecting to AWS in region ${region}")

    ContextBuilder
      .newBuilder("aws-ec2")
      .credentials(keyid, key)
      .overrides(overrides)
      .buildApi(classOf[AWSEC2Api])
  }

  def getEc2Overrides (region: String) : Properties = {
    //set some jcloud properties
    val overrides = new Properties
    overrides.put(ComputeServiceProperties.POLL_INITIAL_PERIOD, String.valueOf(60L * 1000L))
    overrides.put(ComputeServiceProperties.POLL_MAX_PERIOD, String.valueOf(600L * 1000L))
    overrides.put(Constants.PROPERTY_MAX_RETRIES, String.valueOf(60))
    overrides.put("jclouds.regions", region)
    overrides
  }

  //Queries for AWS Nodes

  val predicate = {
    new Predicate[ComputeMetadata]() {
      def apply(computeMetadata: ComputeMetadata): Boolean = {
        System.getenv("USER").equals(getUser(computeMetadata)) &&
          computeMetadata.getTags().contains(AwsConstants.groupTag)
      }
    }
  }

  val allUserPredicate = {
    new Predicate[ComputeMetadata]() {
      def apply(computeMetadata: ComputeMetadata): Boolean = {
        computeMetadata.getTags().contains(AwsConstants.groupTag)
      }
    }
  }

  def getUserClusters(conf: Map[String, String]) : Iterable[JcloudCluster] = {
    val computeService = getComputeService(conf)
    //in theory, jclouds should retry this as it is a GET request, but we can use the 'retryAwsAction'
    //if this does not prove the case
    val javaSet = computeService.listNodesDetailsMatching(predicate)
    getClustersFromNodeMetas(conf, javaSet.toSet)
  }

  def getUserCluster(conf: Map[String, String], id: String) : JcloudCluster = {
    val clusters = getUserClusters(conf)
    val matches = clusters.filter(_.master.getId().equals(AwsUtilities.getFullId(conf, id)))
    require(matches.size == 1, s"No instances found matching $id")
    val result = matches.last
    result
  }

  def getUser(computeMetadata: ComputeMetadata) : String = {
    computeMetadata.getUserMetadata().get(AwsConstants.userTagKey)
  }

  def getCluster(conf: Map[String, String], instanceId: String) : JcloudCluster = {
    val computeService = getComputeService(conf)
    //in theory, jclouds should retry this as it is a GET request, but we can use the 'retryAwsAction'
    //if this does not prove the case
    val javaSet = computeService.listNodesDetailsMatching(allUserPredicate)
    val clusters = getClustersFromNodeMetas(conf, javaSet.toSet)
    val matches = clusters.filter(_.master.getId().equals(AwsUtilities.getFullId(conf, instanceId)))
    require(matches.size == 1, s"No instances found matching $instanceId")
    val result = matches.last
    result
  }

  def getAllClusters(conf: Map[String, String]) : Iterable[JcloudCluster] = {
    val computeService = getComputeService(conf)
    //in theory, jclouds should retry this as it is a GET request, but we can use the 'retryAwsAction'
    //if this does not prove the case
    val javaSet = computeService.listNodesDetailsMatching(allUserPredicate)
    getClustersFromNodeMetas(conf, javaSet.toSet)
  }

  def getClustersFromNodeMetas(conf: Map[String, String], nodes: Set[NodeMetadata]) : Iterable[JcloudCluster] = {
    val clusterMasters = nodes.filter(!_.getUserMetadata.containsKey(AwsConstants.master))
      .map(nm => (AwsUtilities.stripRegion(conf, nm.getId), new JcloudCluster(nm, collection.mutable.Set()))).toMap

    nodes.filter(_.getUserMetadata.containsKey(AwsConstants.master)).foreach(s => {
      val masterId = s.getUserMetadata.get(AwsConstants.master)
      val master = clusterMasters.get(masterId)
      if (master.isEmpty) {
        val slaveId = AwsUtilities.stripRegion(conf, s.getId)
        logger.warn(s"Error, master node of $slaveId master not found: $masterId, ignoring node.")
      } else {
        master.get.slaves.add(s)
      }
    })
    clusterMasters.values
  }

  //Helper methods for NodeMeta.  TODO- use AwsNodeMeta modeled class instead of jclouds class internally.

  def ipAddress(nm : NodeMetadata) : String = {
    val publicAddresses = nm.getPublicAddresses
    if (publicAddresses.size() == 0) {
      ""
    } else {
      nm.getPublicAddresses.iterator().next()
    }
  }

  def privateIp(nm: NodeMetadata) : String = {
    val privateAddresses = nm.getPrivateAddresses
    if (privateAddresses.size() == 0) {
      ""
    } else {
      privateAddresses.iterator.next
    }
  }

  def stripRegion(conf: Map[String, String], idString: String) : String = {
    val region = getAwsProp(conf, AwsConstants.region)
    idString.stripPrefix(s"$region/")
  }

  def getFullId(conf: Map[String, String], idString: String) : String = {
    val region = getAwsProp(conf, AwsConstants.region)
    s"$region/$idString"
  }

  /**
    * Somewhat hacky, instead of passing address everywhere, we pass it through a configuration
    * even if it provided programatically and not read from the user config.
    *
    * That way, we have less code, and just have one code path that reads from configuration.
    * Anyway it's hidden through Node Factory API's
    *
    */
  def getConfWithIp(conf: Map[String, String], ipAddress: String) : Map[String, String] = {
    val newConfMutable = collection.mutable.Map[String, String] (conf.toArray:_*)
    newConfMutable.+= (AwsConstants.getAddressFull -> ipAddress)
    newConfMutable.toMap
  }

  //Helper method for user-facing AwsNodeMeta class

  private def getAwsNodeMeta(conf: Map[String, String], nm: NodeMetadata) : AwsNodeMeta = {
    AwsNodeMeta(id = stripRegion(conf, nm.getId),
      publicIp = ipAddress(nm),
      privateIp = privateIp(nm),
      status = getStatus(nm.getStatus),
      shortHostName = nm.getUserMetadata.get(AwsConstants.hostName)
    )
  }

  private def getStatus(status: NodeMetadata.Status) : AwsNodeState = {
    status match {
      case Status.ERROR => AwsError
      case Status.PENDING => AwsPending
      case Status.RUNNING => AwsRunning
      case Status.TERMINATED => AwsTerminated
      case Status.SUSPENDED => AwsSuspended
      case _ => new OtherAwsState(status.toString)
    }
  }

  def getAwsCluster(conf: Map[String, String], cluster: JcloudCluster) : AwsCluster = {
    val master = getAwsNodeMeta(conf, cluster.master)
    val slaves = cluster.slaves.map(s => getAwsNodeMeta(conf, s)).toSet

    val createTime = cluster.master.getUserMetadata.get(AwsConstants.createTime)
    val expireTime = cluster.master.getUserMetadata.get(AwsConstants.expireTime)
    val user = cluster.master.getUserMetadata.get(AwsConstants.userTagKey)
    val tags = getTags(cluster.master)
    AwsCluster(master, slaves, createTime, expireTime, tags, user)
  }

  def setTag(conf: Map[String, String], cluster: JcloudCluster, tagName: String, tagValue: Option[String]) = {
    val region = AwsUtilities.getAwsProp(conf, AwsConstants.region)
    val tagApi = AwsUtilities.getEc2Api(conf).getTagApiForRegion(region).get()
    val masterId = AwsUtilities.stripRegion(conf, cluster.master.getId)
    val meta = cluster.master.getUserMetadata
    tagValue match {
      case None => {
        tagApi.deleteFromResources(List(tagName).asJava, List(masterId).asJava)
      }
      case Some(v) => {
        meta.put(tagName, v)
        tagApi.applyToResources(meta, List(masterId).asJava)
      }
    }
  }

  def getTags(awsNode: NodeMetadata) : Map[String, String] = {
    val meta = awsNode.getUserMetadata.toMap
    val tags = meta.filter{case (k,v) => k.startsWith(AwsConstants.userTagPrefix)}
    tags.map{case(k,v) => (k.stripPrefix(AwsConstants.userTagPrefix), v)}
  }

  //-----
  //AWS instance timestamp.  All timestamps stored in UTC.
  //-----

  def updateExpireTime(dtString : String) : String = {
    val dt = stringToDt(dtString)
    val expiryTime = dt + AwsConstants.extensionTime
    dtToString(expiryTime)
  }

  def getCurrentTime() : String = {
    val dt = DateTime.now(DateTimeZone.UTC)
    dtToString(dt)
  }

  def dtToString(dt: DateTime) : String = {
    DateTimeFormat.forPattern(AwsConstants.dateTimeFormat).print(dt)
  }

  def stringToDt(dtString: String) : DateTime = {
    //Important to parse the string as UTC, so the miliseconds value is correct!
    DateTimeFormat.forPattern(AwsConstants.dateTimeFormat).withZoneUTC().parseDateTime(dtString)
  }

  //--- Printing some help commands for AWS nodes.

  def printImageInfo(imageGroup: ImageGroup) = {
    val master = imageGroup.master

    val user = master.getTags.get(AwsConstants.userTagKey)
    val createTime = BucketUtilities.getReadableFromSortableDt(master.getTags.get(AwsConstants.createTime))
    println(s"Master Image ${master.getId}, RawState=${master.getRawState}")
    println(s"\tCreated by: $user at $createTime (UTC)")
    println(s"\tDescription: ${master.getDescription}")

    val slaveOption = imageGroup.slave
    if (slaveOption.isDefined) {
      val slave = slaveOption.get
      println(s"\tWith Slave Image ${slave.getId}, RawState=${slave.getRawState}")
    }
  }

  def printClusterInfo(conf: Map[String, String], cluster: JcloudCluster, includeOwner: Boolean = false) = {
    val id = AwsUtilities.stripRegion(conf, cluster.master.getId())
    println(s"Cluster [$id], size = ${cluster.size} node(s)")

    //print tags
    if (includeOwner) {
      val owner = cluster.master.getUserMetadata.get(AwsConstants.userTagKey)
      if (owner != null) {
        println(s"Owned by: $owner")
      }
    }
    val tags = getTags(cluster.master)
    if (tags.size > 0) {
      println("Tags")
    }
    tags.foreach{case(k,v) => println(s"\t$k = $v")}

    //print cluster
    print("Master ")
    println(AwsUtilities.nodeInformation(conf, cluster.master))

    if (cluster.master.getStatus().equals(NodeMetadata.Status.RUNNING)) {
      AwsUtilities.printNodeInfoFull(conf, cluster.master, NodeRole.Master)
    }

    cluster.slaves.foreach(s => {
      println("\tSlave " + AwsUtilities.nodeInformation(conf, s))
      if (s.getStatus().equals(NodeMetadata.Status.RUNNING)) {
        AwsUtilities.printNodeInfoFull(conf, s, NodeRole.Slave)
      }
      println
    })
  }

  def nodeInformation(conf: Map[String, String], u : NodeMetadata) : String = {
    val sb = new StringBuilder(s"Instance id: [${AwsUtilities.stripRegion(conf, u.getId())}], state: ${u.getStatus()}")
    val shortHostName = u.getUserMetadata.get(AwsConstants.hostName)
    val isSlave = u.getUserMetadata.get(AwsConstants.master) != null
    if (shortHostName != null) {
      sb.append(s", hostName: [$shortHostName]")
    }
    if (u.getStatus() == Status.RUNNING) {
      val ip = ipAddress(u)
      sb.append(s", ip: [$ip]")
      if (!isSlave) {
        sb.append(s", created: ${u.getUserMetadata.get(AwsConstants.createTime)} (UTC)" +
          s", expires: ${u.getUserMetadata.get(AwsConstants.expireTime)} (UTC)")
      }
    }
    sb.toString
  }

  def printNodeInfoFull(conf: Map[String, String], nodeMeta: NodeMetadata, nodeRole: NodeRole) = {
    val shortId = stripRegion(conf, nodeMeta.getId)
    val ipAddr = ipAddress(nodeMeta)
    val user = AwsUtilities.getAwsProp(conf, GeneralConstants.user)
    val key = AwsUtilities.getAwsProp(conf, GeneralConstants.keyFile)

    //when printing out slave, tab so it is under the master.
    val tab = nodeRole match {
      case NodeRole.Slave => "\t"
      case _ => ""
    }

    println(tab + "%-20s%s".format("SSH command:", s"ssh -i $key $user@$ipAddr"))

    val ports = nodeRole match {
      case NodeRole.Slave => GeneralConstants.slavePorts
      case _ => GeneralConstants.masterPorts
    }

    ports.foreach(p => {
      println(tab + "%-20s%s".format(s"${p._2}:", s"$ipAddr:${p._1}"))
    })
  }

  //--- For create-image-aws

  def getImageName: String = {
    val random = new Random()
    val randomInt = random.nextInt(10000)
    s"dev_cluster_image_${randomInt}"
  }

  def getUserImagesRaw(conf: Map[String, String], ec2Api: EC2Api) : Iterable[Image] = {
    val region = AwsUtilities.getAwsProp(conf, AwsConstants.region)
    val amiApi = ec2Api.getAMIApi.get
    val ownerId = AwsUtilities.getAwsProp(conf, AwsConstants.accountId)
    val mm = ImmutableSetMultimap.of("owner-id", ownerId)
    val images = amiApi.describeImagesInRegionWithFilter(region, mm)
    val user = System.getenv("USER")
    images.asScala.filter(i => {
      val tags = i.getTags
      tags.containsKey(AwsConstants.groupTag) && tags.containsKey(AwsConstants.userTagKey) && tags.get(AwsConstants.userTagKey).equals(user)
    })
  }

  def getUserImages(conf: Map[String, String], ec2Api: EC2Api) : Iterable[ImageGroup] = {
    val images = getUserImagesRaw(conf, ec2Api)

    //create image-group using the list of master images (images without 'master' pointer tag)
    val imageMap = images.filter(i => !isSlaveImage(i)).map(m =>
      (m.getId, new ImageGroup(m, None))).toMap

    //populate with slave image (images with 'master' pointer tag)
    images.filter(i => isSlaveImage(i)).filter(s => imageMap.get(getMasterImage(s)).isDefined)
      .foreach(s => {
        val imageGroup = imageMap.get(getMasterImage(s)).get
        imageGroup.slave = Some(s)
    })

    //add slaves without masters (images with 'master' pointer tag, but whose master does not exist)
    val orphans = images.filter(i => isSlaveImage(i)).filter(s =>
      !imageMap.containsKey(s.getTags.get(AwsConstants.master))).map(s => new ImageGroup(s, None))
    (imageMap.map(_._2) ++ orphans)
  }

  def getUserImage(conf: Map[String, String], ec2Api: EC2Api, tgtImage: String) : ImageGroup = {
    val userImages = getUserImages(conf, ec2Api)
    val result = userImages.filter(ui => ui.master.getId.equals(tgtImage))
    require (result.size == 1, "Image ids are unique")
    result.last
  }

  def isSlaveImage(i: Image) = {
    i.getTags.containsKey(AwsConstants.master)
  }

  def getMasterImage(slaveImage : Image) = {
    slaveImage.getTags.get(AwsConstants.master)
  }

  def isImageReady(i: ImageGroup) = {
    val available = "available"  //hope AWS state stays like this.  Not sure why JClouds doesn't offer an enum..
    i.master.getRawState.equalsIgnoreCase(available) &&
      i.slave.isDefined && i.slave.get.getRawState.equalsIgnoreCase(available)
  }

  //Generic setup stuff

  def getOsSetupScript(conf: Map[String, String], nodeRole: NodeRole) = {
    val osString = GeneralUtilities.getConfStrict(conf, GeneralConstants.os, GeneralConstants.targetCommonProps)
    osString match {
      case GeneralConstants.ubuntu_trusty => {
        nodeRole match {
          case NodeRole.Master => "ubuntu/setup-master.sh"
          case NodeRole.Slave => "ubuntu/setup-slave.sh"
          case _ => throw new IllegalArgumentException("Internal error, undefined node type")
        }
      }
      case _ => throw new IllegalArgumentException(s"Sorry only ${GeneralConstants.ubuntu_trusty} images are generated for now.")
    }
  }

  def getStartServiceScript(conf: Map[String, String], nodeRole: NodeRole) = {
    nodeRole match {
      case NodeRole.Master => "start/start-master.sh"
      case NodeRole.Slave => "start/start-slave.sh"
      case _ => throw new IllegalArgumentException("Internal error, undefined node type")
    }
  }

  object NodeRole extends Enumeration {
    type NodeRole = Value
    val Master = Value("master")
    val Slave = Value("slave")
  }

  /**
    * AWS is flaky, so retry some of the actions.
    *
    * @param retryable retryable action
    * @tparam A
    * @return
    */
  def retryAwsAction[A >: Null <: Any] (retryable : Retryable[A]) : A = {
    //try 3 times, delay 30 seconds
    var retries = 3
    var delay = 5000

    var res : A = null
    while(res == null) {
      retries = retries - 1
      try {
        res = retryable.action()
      } catch {
        case t: Throwable if retries > 0 => {
          logger.info(s"Recevied error $t, retrying in $delay ms")
          Thread.sleep(delay)
        }
      }
    }
    res
  }
}

trait Retryable[A >: Null] {
  def action() : A
}

case class JcloudCluster(master: NodeMetadata, slaves: scala.collection.mutable.Set[NodeMetadata] = scala.collection.mutable.Set[NodeMetadata]()) {
  def size = 1 + slaves.size
}

class ImageGroup(var master: Image, var slave: Option[Image])


text:
<?php

namespace Michaeljennings\Laralastica;

use Elastica\Client;
use Illuminate\Support\Manager;
use Michaeljennings\Laralastica\Drivers\ArrayDriver;
use Michaeljennings\Laralastica\Drivers\ElasticaDriver;
use Michaeljennings\Laralastica\Drivers\NullDriver;
use Michaeljennings\Laralastica\Exceptions\DriverNotSetException;
use Michaeljennings\Laralastica\Exceptions\IndexNotSetException;

class ClientManager extends Manager
{
    /**
     * The laralastica config.
     *
     * @var array
     */
    protected $config;

    public function __construct(array $config)
    {
        $this->config = $config;
    }

    /**
     * @inheritDoc
     */
    public function driver($driver = null)
    {
        $driver = $driver ?: $this->getDefaultDriver();

        // By default illuminate manager's will create one version of the driver
        // and share that in the application. We want to create a new driver
        // instance each time it is called so here we override that functionality
        if (isset($this->drivers[$driver])) {
            return $this->createDriver($driver);
        }

        return parent::driver($driver);
    }

    /**
     * Create the elastica driver.
     *
     * @return Client
     * @throws IndexNotSetException
     */
    protected function createElasticaDriver()
    {
        $config = isset($this->config['drivers']['elastica']) ? $this->config['drivers']['elastica'] : [];
        $client = new Client($config);

        return new ElasticaDriver($client, new IndexPrefixer(), $config);
    }

    /**
     * Create the null driver.
     *
     * @return ArrayDriver
     */
    protected function createNullDriver()
    {
        return new NullDriver();
    }

    /**
     * Get the default driver name.
     *
     * @return string
     * @throws DriverNotSetException
     */
    public function getDefaultDriver()
    {
        if ( ! array_key_exists('driver', $this->config)) {
            throw new DriverNotSetException("You must set the default driver to connect to in the laralastica config.");
        }

        if (is_null($this->config['driver'])) {
            $this->config['driver'] = 'null';
        }

        return $this->config['driver'];
    }
}

redpajama_set_name: RedPajamaGithub


text:
Add a jQuery .ready() handler that will execute before existing .ready() handlers.

jQuery exeutes .ready() functions in source code order.  Sometimes we need to execute a .ready() function early.

Instructions

Load jquery-before-ready.js immediatley after jQuery, or as as early as possible.

Use .beforeReady() instead of .ready().  You should still use .ready() as normal for scripts that do not need early execution.

Example

```javascript
$.beforeReady(function() {
    alert("Ere I am JH")
});
```


text:
<?php

/**
 * @author MGriesbach@gmail.com
 * @package QueuePlugin
 * @subpackage QueuePlugin.Tasks
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link http://github.com/MSeven/cakephp_queue
 */

/**
 * A Simple QueueTask example.
 *
 */
class ExampleTask extends QueueShell {
	/**
	 * Adding the QueueTask Model
	 *
	 * @var array
	 */
	public $uses = array(
		'CakeQueue.QueuedTask'
	);

	/**
	 * ZendStudio Codecomplete Hint
	 *
	 * @var QueuedTask
	 */
	public $QueuedTask;

	/**
	 * Timeout f�r run, after which the Task is reassigned to a new worker.
	 *
	 * @var integer
	 */
	public $timeout = 10;
	/**
	 * Number of times a failed instance of this task should be restarted before giving up.
	 *
	 * @var integer
	 */
	public $retries = 0;
	/**
	 * Stores any failure messages triggered during run()
	 *
	 * @var string
	 */
	public $failureMessage = '';

	/**
	 * Example add functionality.
	 * Will create one example job in the queue, which later will be executed using run();
	 */
	public function add() {
		$this->out('CakePHP Queue Example task.');
		$this->hr();
		$this->out('This is a very simple example of a queueTask.');
		$this->out('I will now add an example Job into the Queue.');
		$this->out('This job will only produce some console output on the worker that it runs on.');
		$this->out(' ');
		$this->out('To run a Worker use:');
		$this->out('	cake queue runworker');
		$this->out(' ');
		$this->out('You can find the sourcecode of this task in: ');
		$this->out(__FILE__);
		$this->out(' ');
		/**
		 * Adding a task of type 'example' with no additionally passed data
		 */
		if ($this->QueuedTask->createJob('Example', null)) {
			$this->out('OK, job created, now run the worker');
		} else {
			$this->err('Could not create Job');
		}
	}

	/**
	 * Example run function.
	 * This function is executed, when a worker is executing a task.
	 * The return parameter will determine, if the task will be marked completed, or be requeued.
	 *
	 * @param array $data the array passed to QueuedTask->createJob()
	 * @return bool Success
	 */
	public function run($data) {

		$this->hr();
		$this->out('CakePHP Queue Example task.');
		$this->hr();
		$this->out(' ->Success, the Example Job was run.<-');
		$this->out(' ');
		$this->out(' ');
		return true;
	}
}
?>


text:
package org.springframework.boot.actuate.autoconfigure.integrationtest;

import java.util.function.Consumer;

import org.junit.jupiter.api.Test;

import org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener;
import org.springframework.boot.test.context.assertj.ApplicationContextAssertProvider;
import org.springframework.boot.test.context.runner.AbstractApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;

/**
 * Abstract base class for health groups with an additional path.
 *
 * @param <T> the runner
 * @param <C> the application context type
 * @param <A> the assertions
 * @author Madhura Bhave
 */
abstract class AbstractHealthEndpointAdditionalPathIntegrationTests<T extends AbstractApplicationContextRunner<T, C, A>, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider<C>> {

	private final T runner;

	AbstractHealthEndpointAdditionalPathIntegrationTests(T runner) {
		this.runner = runner;
	}

	@Test
	void groupIsAvailableAtAdditionalPath() {
		this.runner
				.withPropertyValues("management.endpoint.health.group.live.include=diskSpace",
						"management.endpoint.health.group.live.additional-path=server:/healthz",
						"management.endpoint.health.group.live.show-components=always")
				.run(withWebTestClient(this::testResponse, "local.server.port"));
	}

	@Test
	void groupIsAvailableAtAdditionalPathWithoutSlash() {
		this.runner
				.withPropertyValues("management.endpoint.health.group.live.include=diskSpace",
						"management.endpoint.health.group.live.additional-path=server:healthz",
						"management.endpoint.health.group.live.show-components=always")
				.run(withWebTestClient(this::testResponse, "local.server.port"));
	}

	@Test
	void groupIsAvailableAtAdditionalPathOnManagementPort() {
		this.runner.withPropertyValues("management.endpoint.health.group.live.include=diskSpace",
				"management.server.port=0", "management.endpoint.health.group.live.additional-path=management:healthz",
				"management.endpoint.health.group.live.show-components=always")
				.run(withWebTestClient(this::testResponse, "local.management.port"));
	}

	@Test
	void groupIsAvailableAtAdditionalPathOnServerPortWithDifferentManagementPort() {
		this.runner.withPropertyValues("management.endpoint.health.group.live.include=diskSpace",
				"management.server.port=0", "management.endpoint.health.group.live.additional-path=server:healthz",
				"management.endpoint.health.group.live.show-components=always")
				.withInitializer(new ConditionEvaluationReportLoggingListener())
				.run(withWebTestClient(this::testResponse, "local.server.port"));
	}

	@Test
	void groupsAreNotConfiguredWhenHealthEndpointIsNotExposed() {
		this.runner
				.withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health",
						"management.server.port=0", "management.endpoint.health.group.live.include=diskSpace",
						"management.endpoint.health.group.live.additional-path=server:healthz",
						"management.endpoint.health.group.live.show-components=always")
				.withInitializer(new ConditionEvaluationReportLoggingListener())
				.run(withWebTestClient((client) -> client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON)
						.exchange().expectStatus().isNotFound(), "local.server.port"));
	}

	private void testResponse(WebTestClient client) {
		client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody()
				.jsonPath("status").isEqualTo("UP").jsonPath("components.diskSpace").exists();
	}

	private ContextConsumer<A> withWebTestClient(Consumer<WebTestClient> consumer, String property) {
		return (context) -> {
			String port = context.getEnvironment().getProperty(property);
			WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build();
			consumer.accept(client);
		};
	}

}


text:
This is a simple minimalistic implementation of the
[Atmel QTouch library](http://www.atmel.com/tools/QTOUCHLIBRARY.aspx) for the Atmega8 chips.

## Setup

 * Connect an LED from `PB2` to ground.
 * Connect a 22nF capacitor between `PC0` and `PC1`.
 * Connect a 1k resistor between `PC1` and the sensor.
   * The sensor can be a wire or sheet of metal or foil.

## Use

When power is supplied, the LED will turn on until it detects something come within range
of the sensor.

## Configuration

Define your settings in `touch.h` and `touch_control.cpp` based on the settings defined
in the [QTouch Library Documentation](http://www.atmel.com/Images/doc8207.pdf).

## IMPORTANT

When you compile this you MUST include the `-fshort-enums` compilation flag.


text:
namespace Stripe
{
    public class ChargePaymentMethodDetailsCardWalletGooglePay : StripeEntity<ChargePaymentMethodDetailsCardWalletGooglePay>
    {
    }
}


text:
<!DOCTYPE html>

    <title>aui-image-cropper</title>

    <link rel="stylesheet" href="../../../../build/aui-css/css/bootstrap.css">

    <meta charset="utf-8" />


text:
require_relative './spec_helper'

require 'capybara'
require 'capybara/dsl'

Capybara.app = CdnApp::Application.new

class MiniTest::Spec
  include Capybara::DSL
end


text:
var CocosBuilderTestScene = TestScene.extend({
     runThisTest:function(){
         /* Create an autorelease CCNodeLoaderLibrary. */
         var ccNodeLoaderLibrary = cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary();

         ccNodeLoaderLibrary.registerCCNodeLoader("HelloCocosBuilderLayer", new HelloCocosBuilderLayerLoader());

         /* Create an autorelease CCBReader. */
         var ccbReader = new cc.BuilderReader(ccNodeLoaderLibrary);
         ccbReader.setCCBRootPath("res/");

         /* Read a ccbi file. */
         var node = ccbReader.readNodeGraphFromFile("res/ccb/HelloCocosBuilder.ccbi", this);

         if(node != null) {
             this.addChild(node);
         }

         cc.Director.getInstance().replaceScene(this);
     }
});


text:
using Portal.Infractructure.Helper;
using Portal.Infractructure.Utility;
using Portal.Service.Implements;
using Portal.Service.Interfaces;
using Site.OnlineStore.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Site.OnlineStore.Areas.Admin.Controllers
{
    //[Authorize(Roles = "Administrator")]
    public class BaseManagementController : BaseController
    {
        #region Properties

        #endregion

        #region Constructures

        public BaseManagementController()
        {
        }

        #endregion

        #region Private functions

        /// <summary>
        /// Create list country items using for Country Dropdownlist
        /// </summary>
        /// <param name="selectedCountry"></param>
        /// <returns></returns>
        protected IEnumerable<SelectListItem> GetCountriesList(string selectedCountry = null)
        {
            IEnumerable<SelectListItem> countries = new List<SelectListItem>()
            {
                new SelectListItem() {Text="Alabama", Value="AL"},
                new SelectListItem() {Value="US", Text="United States"},
                new SelectListItem() {Value="AF", Text="Afghanistan"},
                new SelectListItem() {Value="AX", Text="Åland Islands"},
                new SelectListItem() {Value="AL", Text="Albania"},
                new SelectListItem() {Value="DZ", Text="Algeria"},
                new SelectListItem() {Value="AS", Text="American Samoa"},
                new SelectListItem() {Value="AD", Text="Andorra"},
                new SelectListItem() {Value="AO", Text="Angola"},
                new SelectListItem() {Value="AI", Text="Anguilla"},
                new SelectListItem() {Value="AQ", Text="Antarctica"},
                new SelectListItem() {Value="AG", Text="Antigua and Barbuda"},
                new SelectListItem() {Value="AR", Text="Argentina"},
                new SelectListItem() {Value="AM", Text="Armenia"},
                new SelectListItem() {Value="AW", Text="Aruba"},
                new SelectListItem() {Value="AU", Text="Australia"},
                new SelectListItem() {Value="AT", Text="Austria"},
                new SelectListItem() {Value="AZ", Text="Azerbaijan"},
                new SelectListItem() {Value="BS", Text="Bahamas"},
                new SelectListItem() {Value="BH", Text="Bahrain"},
                new SelectListItem() {Value="BD", Text="Bangladesh"},
                new SelectListItem() {Value="BB", Text="Barbados"},
                new SelectListItem() {Value="BY", Text="Belarus"},
                new SelectListItem() {Value="BE", Text="Belgium"},
                new SelectListItem() {Value="BZ", Text="Belize"},
                new SelectListItem() {Value="BJ", Text="Benin"},
                new SelectListItem() {Value="BM", Text="Bermuda"},
                new SelectListItem() {Value="BT", Text="Bhutan"},
                new SelectListItem() {Value="BO", Text="Bolivia, Plurinational State of"},
                new SelectListItem() {Value="BQ", Text="Bonaire, Sint Eustatius and Saba"},
                new SelectListItem() {Value="BA", Text="Bosnia and Herzegovina"},
                new SelectListItem() {Value="BW", Text="Botswana"},
                new SelectListItem() {Value="BV", Text="Bouvet Island"},
                new SelectListItem() {Value="BR", Text="Brazil"},
                new SelectListItem() {Value="IO", Text="British Indian Ocean Territory"},
                new SelectListItem() {Value="BN", Text="Brunei Darussalam"},
                new SelectListItem() {Value="BG", Text="Bulgaria"},
                new SelectListItem() {Value="BF", Text="Burkina Faso"},
                new SelectListItem() {Value="BI", Text="Burundi"},
                new SelectListItem() {Value="KH", Text="Cambodia"},
                new SelectListItem() {Value="CM", Text="Cameroon"},
                new SelectListItem() {Value="CA", Text="Canada"},
                new SelectListItem() {Value="CV", Text="Cape Verde"},
                new SelectListItem() {Value="KY", Text="Cayman Islands"},
                new SelectListItem() {Value="CF", Text="Central African Republic"},
                new SelectListItem() {Value="TD", Text="Chad"},
                new SelectListItem() {Value="CL", Text="Chile"},
                new SelectListItem() {Value="CN", Text="China"},
                new SelectListItem() {Value="CX", Text="Christmas Island"},
                new SelectListItem() {Value="CC", Text="Cocos (Keeling) Islands"},
                new SelectListItem() {Value="CO", Text="Colombia"},
                new SelectListItem() {Value="KM", Text="Comoros"},
                new SelectListItem() {Value="CG", Text="Congo"},
                new SelectListItem() {Value="CD", Text="Congo, The Democratic Republic of the"},
                new SelectListItem() {Value="CK", Text="Cook Islands"},
                new SelectListItem() {Value="CR", Text="Costa Rica"},
                new SelectListItem() {Value="CI", Text="Côte d'Ivoire"},
                new SelectListItem() {Value="HR", Text="Croatia"},
                new SelectListItem() {Value="CW", Text="Curaçao"},
                new SelectListItem() {Value="CY", Text="Cyprus"},
                new SelectListItem() {Value="CZ", Text="Czech Republic"},
                new SelectListItem() {Value="DK", Text="Denmark"},
                new SelectListItem() {Value="DJ", Text="Djibouti"},
                new SelectListItem() {Value="DM", Text="Dominica"},
                new SelectListItem() {Value="DO", Text="Dominican Republic"},
                new SelectListItem() {Value="EC", Text="Ecuador"},
                new SelectListItem() {Value="EG", Text="Egypt"},
                new SelectListItem() {Value="SV", Text="El Salvador"},
                new SelectListItem() {Value="GQ", Text="Equatorial Guinea"},
                new SelectListItem() {Value="ER", Text="Eritrea"},
                new SelectListItem() {Value="EE", Text="Estonia"},
                new SelectListItem() {Value="ET", Text="Ethiopia"},
                new SelectListItem() {Value="FK", Text="Falkland Islands (Malvinas)"},
                new SelectListItem() {Value="FO", Text="Faroe Islands"},
                new SelectListItem() {Value="FJ", Text="Fiji"},
                new SelectListItem() {Value="FI", Text="Finland"},
                new SelectListItem() {Value="FR", Text="France"},
                new SelectListItem() {Value="GF", Text="French Guiana"},
                new SelectListItem() {Value="PF", Text="French Polynesia"},
                new SelectListItem() {Value="TF", Text="French Southern Territories"},
                new SelectListItem() {Value="GA", Text="Gabon"},
                new SelectListItem() {Value="GM", Text="Gambia"},
                new SelectListItem() {Value="GE", Text="Georgia"},
                new SelectListItem() {Value="DE", Text="Germany"},
                new SelectListItem() {Value="GH", Text="Ghana"},
                new SelectListItem() {Value="GI", Text="Gibraltar"},
                new SelectListItem() {Value="GR", Text="Greece"},
                new SelectListItem() {Value="GL", Text="Greenland"},
                new SelectListItem() {Value="GD", Text="Grenada"},
                new SelectListItem() {Value="GP", Text="Guadeloupe"},
                new SelectListItem() {Value="GU", Text="Guam"},
                new SelectListItem() {Value="GT", Text="Guatemala"},
                new SelectListItem() {Value="GG", Text="Guernsey"},
                new SelectListItem() {Value="GN", Text="Guinea"},
                new SelectListItem() {Value="GW", Text="Guinea-Bissau"},
                new SelectListItem() {Value="GY", Text="Guyana"},
                new SelectListItem() {Value="HT", Text="Haiti"},
                new SelectListItem() {Value="HM", Text="Heard Island and McDonald Islands"},
                new SelectListItem() {Value="VA", Text="Holy See (Vatican City State)"},
                new SelectListItem() {Value="HN", Text="Honduras"},
                new SelectListItem() {Value="HK", Text="Hong Kong"},
                new SelectListItem() {Value="HU", Text="Hungary"},
                new SelectListItem() {Value="IS", Text="Iceland"},
                new SelectListItem() {Value="IN", Text="India"},
                new SelectListItem() {Value="ID", Text="Indonesia"},
                new SelectListItem() {Value="IQ", Text="Iraq"},
                new SelectListItem() {Value="IE", Text="Ireland"},
                new SelectListItem() {Value="IM", Text="Isle of Man"},
                new SelectListItem() {Value="IL", Text="Israel"},
                new SelectListItem() {Value="IT", Text="Italy"},
                new SelectListItem() {Value="JM", Text="Jamaica"},
                new SelectListItem() {Value="JP", Text="Japan"},
                new SelectListItem() {Value="JE", Text="Jersey"},
                new SelectListItem() {Value="JO", Text="Jordan"},
                new SelectListItem() {Value="KZ", Text="Kazakhstan"},
                new SelectListItem() {Value="KE", Text="Kenya"},
                new SelectListItem() {Value="KI", Text="Kiribati"},
                new SelectListItem() {Value="KR", Text="Korea, Republic of"},
                new SelectListItem() {Value="KW", Text="Kuwait"},
                new SelectListItem() {Value="KG", Text="Kyrgyzstan"},
                new SelectListItem() {Value="LA", Text="Lao People's Democratic Republic"},
                new SelectListItem() {Value="LV", Text="Latvia"},
                new SelectListItem() {Value="LB", Text="Lebanon"},
                new SelectListItem() {Value="LS", Text="Lesotho"},
                new SelectListItem() {Value="LR", Text="Liberia"},
                new SelectListItem() {Value="LY", Text="Libya"},
                new SelectListItem() {Value="LI", Text="Liechtenstein"},
                new SelectListItem() {Value="LT", Text="Lithuania"},
                new SelectListItem() {Value="LU", Text="Luxembourg"},
                new SelectListItem() {Value="MO", Text="Macao"},
                new SelectListItem() {Value="MK", Text="Macedonia, Republic of"},
                new SelectListItem() {Value="MG", Text="Madagascar"},
                new SelectListItem() {Value="MW", Text="Malawi"},
                new SelectListItem() {Value="MY", Text="Malaysia"},
                new SelectListItem() {Value="MV", Text="Maldives"},
                new SelectListItem() {Value="ML", Text="Mali"},
                new SelectListItem() {Value="MT", Text="Malta"},
                new SelectListItem() {Value="MH", Text="Marshall Islands"},
                new SelectListItem() {Value="MQ", Text="Martinique"},
                new SelectListItem() {Value="MR", Text="Mauritania"},
                new SelectListItem() {Value="MU", Text="Mauritius"},
                new SelectListItem() {Value="YT", Text="Mayotte"},
                new SelectListItem() {Value="MX", Text="Mexico"},
                new SelectListItem() {Value="FM", Text="Micronesia, Federated States of"},
                new SelectListItem() {Value="MD", Text="Moldova, Republic of"},
                new SelectListItem() {Value="MC", Text="Monaco"},
                new SelectListItem() {Value="MN", Text="Mongolia"},
                new SelectListItem() {Value="ME", Text="Montenegro"},
                new SelectListItem() {Value="MS", Text="Montserrat"},
                new SelectListItem() {Value="MA", Text="Morocco"},
                new SelectListItem() {Value="MZ", Text="Mozambique"},
                new SelectListItem() {Value="MM", Text="Myanmar"},
                new SelectListItem() {Value="NA", Text="Namibia"},
                new SelectListItem() {Value="NR", Text="Nauru"},
                new SelectListItem() {Value="NP", Text="Nepal"},
                new SelectListItem() {Value="NL", Text="Netherlands"},
                new SelectListItem() {Value="NC", Text="New Caledonia"},
                new SelectListItem() {Value="NZ", Text="New Zealand"},
                new SelectListItem() {Value="NI", Text="Nicaragua"},
                new SelectListItem() {Value="NE", Text="Niger"},
                new SelectListItem() {Value="NG", Text="Nigeria"},
                new SelectListItem() {Value="NU", Text="Niue"},
                new SelectListItem() {Value="NF", Text="Norfolk Island"},
                new SelectListItem() {Value="MP", Text="Northern Mariana Islands"},
                new SelectListItem() {Value="NO", Text="Norway"},
                new SelectListItem() {Value="OM", Text="Oman"},
                new SelectListItem() {Value="PK", Text="Pakistan"},
                new SelectListItem() {Value="PW", Text="Palau"},
                new SelectListItem() {Value="PS", Text="Palestine, State of"},
                new SelectListItem() {Value="PA", Text="Panama"},
                new SelectListItem() {Value="PG", Text="Papua New Guinea"},
                new SelectListItem() {Value="PY", Text="Paraguay"},
                new SelectListItem() {Value="PE", Text="Peru"},
                new SelectListItem() {Value="PH", Text="Philippines"},
                new SelectListItem() {Value="PN", Text="Pitcairn"},
                new SelectListItem() {Value="PL", Text="Poland"},
                new SelectListItem() {Value="PT", Text="Portugal"},
                new SelectListItem() {Value="PR", Text="Puerto Rico"},
                new SelectListItem() {Value="QA", Text="Qatar"},
                new SelectListItem() {Value="RE", Text="Réunion"},
                new SelectListItem() {Value="RO", Text="Romania"},
                new SelectListItem() {Value="RU", Text="Russian Federation"},
                new SelectListItem() {Value="RW", Text="Rwanda"},
                new SelectListItem() {Value="BL", Text="Saint Barthélemy"},
                new SelectListItem() {Value="SH", Text="Saint Helena, Ascension and Tristan da Cunha"},
                new SelectListItem() {Value="KN", Text="Saint Kitts and Nevis"},
                new SelectListItem() {Value="LC", Text="Saint Lucia"},
                new SelectListItem() {Value="MF", Text="Saint Martin (French part)"},
                new SelectListItem() {Value="PM", Text="Saint Pierre and Miquelon"},
                new SelectListItem() {Value="VC", Text="Saint Vincent and the Grenadines"},
                new SelectListItem() {Value="WS", Text="Samoa"},
                new SelectListItem() {Value="SM", Text="San Marino"},
                new SelectListItem() {Value="ST", Text="Sao Tome and Principe"},
                new SelectListItem() {Value="SA", Text="Saudi Arabia"},
                new SelectListItem() {Value="SN", Text="Senegal"},
                new SelectListItem() {Value="RS", Text="Serbia"},
                new SelectListItem() {Value="SC", Text="Seychelles"},
                new SelectListItem() {Value="SL", Text="Sierra Leone"},
                new SelectListItem() {Value="SG", Text="Singapore"},
                new SelectListItem() {Value="SX", Text="Sint Maarten (Dutch part)"},
                new SelectListItem() {Value="SK", Text="Slovakia"},
                new SelectListItem() {Value="SI", Text="Slovenia"},
                new SelectListItem() {Value="SB", Text="Solomon Islands"},
                new SelectListItem() {Value="SO", Text="Somalia"},
                new SelectListItem() {Value="ZA", Text="South Africa"},
                new SelectListItem() {Value="GS", Text="South Georgia and the South Sandwich Islands"},
                new SelectListItem() {Value="SS", Text="South Sudan"},
                new SelectListItem() {Value="ES", Text="Spain"},
                new SelectListItem() {Value="LK", Text="Sri Lanka"},
                new SelectListItem() {Value="SR", Text="Suriname"},
                new SelectListItem() {Value="SJ", Text="Svalbard and Jan Mayen"},
                new SelectListItem() {Value="SZ", Text="Swaziland"},
                new SelectListItem() {Value="SE", Text="Sweden"},
                new SelectListItem() {Value="CH", Text="Switzerland"},
                new SelectListItem() {Value="TW", Text="Taiwan, Province of China"},
                new SelectListItem() {Value="TJ", Text="Tajikistan"},
                new SelectListItem() {Value="TZ", Text="Tanzania, United Republic of"},
                new SelectListItem() {Value="TH", Text="Thailand"},
                new SelectListItem() {Value="TL", Text="Timor-Leste"},
                new SelectListItem() {Value="TG", Text="Togo"},
                new SelectListItem() {Value="TK", Text="Tokelau"},
                new SelectListItem() {Value="TO", Text="Tonga"},
                new SelectListItem() {Value="TT", Text="Trinidad and Tobago"},
                new SelectListItem() {Value="TN", Text="Tunisia"},
                new SelectListItem() {Value="TR", Text="Turkey"},
                new SelectListItem() {Value="TM", Text="Turkmenistan"},
                new SelectListItem() {Value="TC", Text="Turks and Caicos Islands"},
                new SelectListItem() {Value="TV", Text="Tuvalu"},
                new SelectListItem() {Value="UG", Text="Uganda"},
                new SelectListItem() {Value="UA", Text="Ukraine"},
                new SelectListItem() {Value="AE", Text="United Arab Emirates"},
                new SelectListItem() {Value="GB", Text="United Kingdom"},
                new SelectListItem() {Value="UM", Text="United States Minor Outlying Islands"},
                new SelectListItem() {Value="UY", Text="Uruguay"},
                new SelectListItem() {Value="UZ", Text="Uzbekistan"},
                new SelectListItem() {Value="VU", Text="Vanuatu"},
                new SelectListItem() {Value="VE", Text="Venezuela, Bolivarian Republic of"},
                new SelectListItem() {Value="VN", Text="Viet Nam"},
                new SelectListItem() {Value="VG", Text="Virgin Islands, British"},
                new SelectListItem() {Value="VI", Text="Virgin Islands, U.S."},
                new SelectListItem() {Value="WF", Text="Wallis and Futuna"},
                new SelectListItem() {Value="EH", Text="Western Sahara"},
                new SelectListItem() {Value="YE", Text="Yemen"},
                new SelectListItem() {Value="ZM", Text="Zambia"},
                new SelectListItem() {Value="ZW", Text="Zimbabwe"}
            };

            if (selectedCountry != null)
            {
                var selected = countries.Where(x => x.Value == selectedCountry.Trim()).First();
                selected.Selected = true;
            }

            return countries;
        }

        /// <summary>
        /// Create list event type items using for EventType Dropdownlist
        /// </summary>
        /// <param name="selectedType"></param>
        /// <returns></returns>
        protected IEnumerable<SelectListItem> GetEventTypeList(int? selectedType = null)
        {
            IEnumerable<SelectListItem> types = new List<SelectListItem>
            {
                new SelectListItem() {Value="19", Text="Appearance or Signing"},
                new SelectListItem() {Value="17", Text="Attraction"},
                new SelectListItem() {Value="18", Text="Camp, Trip, or Retreat"},
                new SelectListItem() {Value="9", Text="Class, Training, or Workshop"},
                new SelectListItem() {Value="6", Text="Concert or Performance"},
                new SelectListItem() {Value="1", Text="Conference"},
                new SelectListItem() {Value="4", Text="Convention"},
                new SelectListItem() {Value="8", Text="Dinner or Gala"},
                new SelectListItem() {Value="5", Text="Festival or Fair"},
                new SelectListItem() {Value="14", Text="Game or Competition"},
                new SelectListItem() {Value="10", Text="Meeting or Networking Event"},
                new SelectListItem() {Value="100", Text="Other"},
                new SelectListItem() {Value="11", Text="Party or Social Gathering"},
                new SelectListItem() {Value="15", Text="Race or Endurance Event"},
                new SelectListItem() {Value="12", Text="Rally"},
                new SelectListItem() {Value="7", Text="Screening"},
                new SelectListItem() {Value="2", Text="Seminar or Talk"},
                new SelectListItem() {Value="16", Text="Tour"},
                new SelectListItem() {Value="13", Text="Tournament"},
                new SelectListItem() {Value="3", Text="Tradeshow, Consumer Show, or Expo"}
            };

            if (selectedType != null)
            {
                var selected = types.Where(x => x.Value == selectedType.ToString()).First();
                selected.Selected = true;
            }

            return types;
        }

        /// <summary>
        /// Create list event topic items using for EventTopic Dropdownlist
        /// </summary>
        /// <param name="selectedTopic"></param>
        /// <returns></returns>
        protected IEnumerable<SelectListItem> GetEventTopicList(int? selectedTopic = null)
        {
            IEnumerable<SelectListItem> topics = new List<SelectListItem>
            {
                new SelectListItem() {Value="118",Text="Auto, Boat & Air"},
                new SelectListItem() {Value="101",Text="Business & Professional"},
                new SelectListItem() {Value="111",Text="Charity & Causes"},
                new SelectListItem() {Value="113",Text="Community & Culture"},
                new SelectListItem() {Value="115",Text="Family & Education"},
                new SelectListItem() {Value="106",Text="Fashion & Beauty"},
                new SelectListItem() {Value="104",Text="Film, Media & Entertainment"},
                new SelectListItem() {Value="110",Text="Food & Drink"},
                new SelectListItem() {Value="112",Text="Government & Politics"},
                new SelectListItem() {Value="107",Text="Health & Wellness"},
                new SelectListItem() {Value="119",Text="Hobbies & Special Interest"},
                new SelectListItem() {Value="117",Text="Home & Lifestyle"},
                new SelectListItem() {Value="103",Text="Music"},
                new SelectListItem() {Value="199",Text="Other"},
                new SelectListItem() {Value="105",Text="Performing & Visual Arts"},
                new SelectListItem() {Value="114",Text="Religion & Spirituality"},
                new SelectListItem() {Value="102",Text="Science & Technology"},
                new SelectListItem() {Value="116",Text="Seasonal & Holiday"},
                new SelectListItem() {Value="108",Text="Sports & Fitness"},
                new SelectListItem() {Value="109",Text="Travel & Outdoor"}
            };

            if (selectedTopic != null)
            {
                var selected = topics.Where(x => x.Value == selectedTopic.ToString()).First();
                selected.Selected = true;
            }

            return topics;
        }

        /// <summary>
        /// Create list ticket types using for TicketType Dropdownlist
        /// </summary>
        /// <param name="selectedTopic"></param>
        /// <returns></returns>
        protected IEnumerable<SelectListItem> GetTicketTypeList(string selectedType = null)
        {
            IEnumerable<SelectListItem> types = new List<SelectListItem>
            {
                new SelectListItem() {Value="0",Text="Free"},
                new SelectListItem() {Value="1",Text="Paid"},
                new SelectListItem() {Value="2",Text="Donation"}
            };

            if (selectedType != null)
            {
                var selected = types.Where(x => x.Value == selectedType.Trim()).First();
                selected.Selected = true;
            }

            return types;
        }

        #endregion

        #region Public functions

        /// <summary>
        /// Get list options for Status dropdownlist and assign to Variable in ViewBag of view
        /// </summary>
        /// <param name="status"></param>
        protected virtual void PopulateStatusDropDownList(Define.Status status = Define.Status.Active)
        {
            IEnumerable<Define.Status> values = Enum.GetValues(typeof(Define.Status)).Cast<Define.Status>();
            IEnumerable<SelectListItem> items = from value in values
                                                where value != Define.Status.Delete
                                                select new SelectListItem
                                                {
                                                    Text = EnumHelper.GetDescriptionFromEnum((Define.Status)value),
                                                    Value = ((int)value).ToString(),
                                                    Selected = value == status,
                                                };

            ViewBag.Status = items;
        }

        /// <summary>
        /// Get list options for Region dropdownlist and assign to Variable in ViewBag of view
        /// </summary>
        /// <param name="status"></param>
        protected virtual void PopulateRegionDropDownList(Define.Region region = Define.Region.North)
        {
            IEnumerable<Define.Region> values = Enum.GetValues(typeof(Define.Region)).Cast<Define.Region>();
            IEnumerable<SelectListItem> items = from value in values
                                                select new SelectListItem
                                                {
                                                    Text = EnumHelper.GetDescriptionFromEnum((Define.Region)value),
                                                    Value = ((int)value).ToString(),
                                                    Selected = value == region,
                                                };

            ViewBag.Region = items;
        }

        /// <summary>
        /// Get list options for progress status dropdownlist and assign to Variable in ViewBag of view
        /// </summary>
        /// <param name="progressStatus"></param>
        protected virtual void PopulateProgressStatusDropDownList(Define.ProgressStatus progressStatus = Define.ProgressStatus.InProgress)
        {
            IEnumerable<Define.ProgressStatus> values = Enum.GetValues(typeof(Define.ProgressStatus)).Cast<Define.ProgressStatus>();
            IEnumerable<SelectListItem> items = from value in values
                                                select new SelectListItem
                                                {
                                                    Text = EnumHelper.GetDescriptionFromEnum((Define.ProgressStatus)value),
                                                    Value = ((int)value).ToString(),
                                                    Selected = value == progressStatus,
                                                };

            ViewBag.ProgressStatus = items;
        }

        /// <summary>
        /// Get list options for project type dropdownlist and assign to Variable in ViewBag of view
        /// </summary>
        /// <param name="projectType"></param>
        protected virtual void PopulateProjectTypeDropDownList(Define.ProjectType projectType = Define.ProjectType.DesignAndConstruction)
        {
            IEnumerable<Define.ProjectType> values = Enum.GetValues(typeof(Define.ProjectType)).Cast<Define.ProjectType>();
            IEnumerable<SelectListItem> items = from value in values
                                                select new SelectListItem
                                                {
                                                    Text = EnumHelper.GetDescriptionFromEnum((Define.ProjectType)value),
                                                    Value = ((int)value).ToString(),
                                                    Selected = value == projectType
                                                };

            ViewBag.Type = items;
        }

        /// <summary>
        /// Get list options for banner types dropdownlist and assign to Variable in ViewBag of view
        /// </summary>
        /// <param name="status"></param>
        protected virtual void PopulateBannerTypesDropDownList(Define.BannerTypes banner = Define.BannerTypes.SpringSeason)
        {
            IEnumerable<Define.BannerTypes> values = Enum.GetValues(typeof(Define.BannerTypes)).Cast<Define.BannerTypes>();
            IEnumerable<SelectListItem> items = from value in values
                                                select new SelectListItem
                                                {
                                                    Text = EnumHelper.GetDescriptionFromEnum((Define.BannerTypes)value),
                                                    Value = ((int)value).ToString(),
                                                    Selected = value == banner,
                                                };

            ViewBag.Type = items;
        }

        #endregion

        #region Release resources

        /// <summary>
        /// Dispose database connection
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        #endregion
    }
}


text:
module Unparser
  class Emitter
    # Emitter for regexp literals
    class Regexp < self
      handle :regexp

      define_group(:body, 0..-2)

    private

      def dispatch
        parentheses('/', '/') do
          body.each(&method(:emit_body))
        end
        emit_options
      end

      def emit_options
        write(children.last.children.join)
      end

      def emit_body(node)
        if n_begin?(node)
          write('#{')
          node.children.each(&method(:visit))
          write('}')
        else
          buffer.append_without_prefix(node.children.first.gsub('/', '\/'))
        end
      end
    end # Regexp
  end # Emitter
end # Unparser


text:
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union

import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
import google.auth  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.cloud.location import locations_pb2  # type: ignore
from google.iam.v1 import iam_policy_pb2  # type: ignore
from google.iam.v1 import policy_pb2  # type: ignore
from google.oauth2 import service_account  # type: ignore
from google.protobuf import empty_pb2  # type: ignore
import pkg_resources

from google.cloud.bigquery_data_exchange_v1beta1.types import dataexchange

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-cloud-bigquery-data-exchange",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

class AnalyticsHubServiceTransport(abc.ABC):
    """Abstract transport class for AnalyticsHubService."""

    AUTH_SCOPES = (
        "https://www.googleapis.com/auth/bigquery",
        "https://www.googleapis.com/auth/cloud-platform",
    )

    DEFAULT_HOST: str = "analyticshub.googleapis.com"

    def __init__(
        self,
        *,
        host: str = DEFAULT_HOST,
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
        **kwargs,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is mutually exclusive with credentials.
            scopes (Optional[Sequence[str]]): A list of scopes.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
        """

        scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}

        # Save the scopes.
        self._scopes = scopes

        # If no credentials are provided, then determine the appropriate
        # defaults.
        if credentials and credentials_file:
            raise core_exceptions.DuplicateCredentialArgs(
                "'credentials_file' and 'credentials' are mutually exclusive"
            )

        if credentials_file is not None:
            credentials, _ = google.auth.load_credentials_from_file(
                credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
            )
        elif credentials is None:
            credentials, _ = google.auth.default(
                **scopes_kwargs, quota_project_id=quota_project_id
            )
            # Don't apply audience if the credentials file passed from user.
            if hasattr(credentials, "with_gdch_audience"):
                credentials = credentials.with_gdch_audience(
                    api_audience if api_audience else host
                )

        # If the credentials are service account credentials, then always try to use self signed JWT.
        if (
            always_use_jwt_access
            and isinstance(credentials, service_account.Credentials)
            and hasattr(service_account.Credentials, "with_always_use_jwt_access")
        ):
            credentials = credentials.with_always_use_jwt_access(True)

        # Save the credentials.
        self._credentials = credentials

        # Save the hostname. Default to port 443 (HTTPS) if none is specified.
        if ":" not in host:
            host += ":443"
        self._host = host

    def _prep_wrapped_messages(self, client_info):
        # Precompute the wrapped methods.
        self._wrapped_methods = {
            self.list_data_exchanges: gapic_v1.method.wrap_method(
                self.list_data_exchanges,
                default_timeout=None,
                client_info=client_info,
            ),
            self.list_org_data_exchanges: gapic_v1.method.wrap_method(
                self.list_org_data_exchanges,
                default_timeout=None,
                client_info=client_info,
            ),
            self.get_data_exchange: gapic_v1.method.wrap_method(
                self.get_data_exchange,
                default_timeout=None,
                client_info=client_info,
            ),
            self.create_data_exchange: gapic_v1.method.wrap_method(
                self.create_data_exchange,
                default_timeout=None,
                client_info=client_info,
            ),
            self.update_data_exchange: gapic_v1.method.wrap_method(
                self.update_data_exchange,
                default_timeout=None,
                client_info=client_info,
            ),
            self.delete_data_exchange: gapic_v1.method.wrap_method(
                self.delete_data_exchange,
                default_timeout=None,
                client_info=client_info,
            ),
            self.list_listings: gapic_v1.method.wrap_method(
                self.list_listings,
                default_timeout=None,
                client_info=client_info,
            ),
            self.get_listing: gapic_v1.method.wrap_method(
                self.get_listing,
                default_timeout=None,
                client_info=client_info,
            ),
            self.create_listing: gapic_v1.method.wrap_method(
                self.create_listing,
                default_timeout=None,
                client_info=client_info,
            ),
            self.update_listing: gapic_v1.method.wrap_method(
                self.update_listing,
                default_timeout=None,
                client_info=client_info,
            ),
            self.delete_listing: gapic_v1.method.wrap_method(
                self.delete_listing,
                default_timeout=None,
                client_info=client_info,
            ),
            self.subscribe_listing: gapic_v1.method.wrap_method(
                self.subscribe_listing,
                default_timeout=None,
                client_info=client_info,
            ),
            self.get_iam_policy: gapic_v1.method.wrap_method(
                self.get_iam_policy,
                default_timeout=None,
                client_info=client_info,
            ),
            self.set_iam_policy: gapic_v1.method.wrap_method(
                self.set_iam_policy,
                default_timeout=None,
                client_info=client_info,
            ),
            self.test_iam_permissions: gapic_v1.method.wrap_method(
                self.test_iam_permissions,
                default_timeout=None,
                client_info=client_info,
            ),
        }

    def close(self):
        """Closes resources associated with the transport.

        .. warning::
             Only call this method if the transport is NOT shared
             with other clients - this may cause errors in other clients!
        """
        raise NotImplementedError()

    @property
    def list_data_exchanges(
        self,
    ) -> Callable[
        [dataexchange.ListDataExchangesRequest],
        Union[
            dataexchange.ListDataExchangesResponse,
            Awaitable[dataexchange.ListDataExchangesResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def list_org_data_exchanges(
        self,
    ) -> Callable[
        [dataexchange.ListOrgDataExchangesRequest],
        Union[
            dataexchange.ListOrgDataExchangesResponse,
            Awaitable[dataexchange.ListOrgDataExchangesResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_data_exchange(
        self,
    ) -> Callable[
        [dataexchange.GetDataExchangeRequest],
        Union[dataexchange.DataExchange, Awaitable[dataexchange.DataExchange]],
    ]:
        raise NotImplementedError()

    @property
    def create_data_exchange(
        self,
    ) -> Callable[
        [dataexchange.CreateDataExchangeRequest],
        Union[dataexchange.DataExchange, Awaitable[dataexchange.DataExchange]],
    ]:
        raise NotImplementedError()

    @property
    def update_data_exchange(
        self,
    ) -> Callable[
        [dataexchange.UpdateDataExchangeRequest],
        Union[dataexchange.DataExchange, Awaitable[dataexchange.DataExchange]],
    ]:
        raise NotImplementedError()

    @property
    def delete_data_exchange(
        self,
    ) -> Callable[
        [dataexchange.DeleteDataExchangeRequest],
        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
    ]:
        raise NotImplementedError()

    @property
    def list_listings(
        self,
    ) -> Callable[
        [dataexchange.ListListingsRequest],
        Union[
            dataexchange.ListListingsResponse,
            Awaitable[dataexchange.ListListingsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_listing(
        self,
    ) -> Callable[
        [dataexchange.GetListingRequest],
        Union[dataexchange.Listing, Awaitable[dataexchange.Listing]],
    ]:
        raise NotImplementedError()

    @property
    def create_listing(
        self,
    ) -> Callable[
        [dataexchange.CreateListingRequest],
        Union[dataexchange.Listing, Awaitable[dataexchange.Listing]],
    ]:
        raise NotImplementedError()

    @property
    def update_listing(
        self,
    ) -> Callable[
        [dataexchange.UpdateListingRequest],
        Union[dataexchange.Listing, Awaitable[dataexchange.Listing]],
    ]:
        raise NotImplementedError()

    @property
    def delete_listing(
        self,
    ) -> Callable[
        [dataexchange.DeleteListingRequest],
        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
    ]:
        raise NotImplementedError()

    @property
    def subscribe_listing(
        self,
    ) -> Callable[
        [dataexchange.SubscribeListingRequest],
        Union[
            dataexchange.SubscribeListingResponse,
            Awaitable[dataexchange.SubscribeListingResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_iam_policy(
        self,
    ) -> Callable[
        [iam_policy_pb2.GetIamPolicyRequest],
        Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
    ]:
        raise NotImplementedError()

    @property
    def set_iam_policy(
        self,
    ) -> Callable[
        [iam_policy_pb2.SetIamPolicyRequest],
        Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
    ]:
        raise NotImplementedError()

    @property
    def test_iam_permissions(
        self,
    ) -> Callable[
        [iam_policy_pb2.TestIamPermissionsRequest],
        Union[
            iam_policy_pb2.TestIamPermissionsResponse,
            Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_location(
        self,
    ) -> Callable[
        [locations_pb2.GetLocationRequest],
        Union[locations_pb2.Location, Awaitable[locations_pb2.Location]],
    ]:
        raise NotImplementedError()

    @property
    def list_locations(
        self,
    ) -> Callable[
        [locations_pb2.ListLocationsRequest],
        Union[
            locations_pb2.ListLocationsResponse,
            Awaitable[locations_pb2.ListLocationsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def kind(self) -> str:
        raise NotImplementedError()

__all__ = ("AnalyticsHubServiceTransport",)


text:
package org.codemucker.jmutate.builder;

import static org.codemucker.lang.Check.checkNotBlank;
import static org.codemucker.lang.Check.checkNotNull;
import static org.codemucker.lang.Check.checkTrue;

import org.codemucker.jmutate.SourceTemplate;
import org.codemucker.jmutate.ast.JAccess;
import org.codemucker.jmutate.ast.JField;
import org.codemucker.jmutate.ast.JMethod;
import org.codemucker.jmutate.ast.JType;
import org.codemucker.jmutate.util.NameUtil;
import org.codemucker.jpattern.Pattern;
import org.codemucker.lang.ClassNameUtil;
import org.codemucker.lang.annotation.Optional;
import org.codemucker.lang.annotation.Required;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Type;

public final class JMethodSetterBuilder extends AbstractBuilder<JMethodSetterBuilder,JMethod> {

	public static enum RETURNS {
		VOID, TARGET, ARG;
	}

	private RETURNS returnType = RETURNS.VOID;
	private JAccess access = JAccess.PUBLIC;

	@Optional
	private String methodName;//defaults if not set

	@Required
	private String fieldName;
	@Required
    private String fieldType;
	@Required
    private JType target;

	public static JMethodSetterBuilder with() {
		return new JMethodSetterBuilder();
	}

	public JMethodSetterBuilder(){
		pattern("bean.setter");
	}

	@Override
	public JMethod build() {
		checkFieldsSet();

		checkNotNull("target", target);
		checkNotBlank("name", fieldName);
		checkNotBlank("type", fieldType);

		return JMethod.from(toMethod());
	}

	private MethodDeclaration toMethod() {
		SourceTemplate template = getContext().newSourceTemplate();

		String setterName = methodName;
		if(setterName == null){
            setterName = "set" + ClassNameUtil.upperFirstChar(fieldName);
        }

		template
			.setVar("methodName", setterName)
			.setVar("argType", fieldType)
			.setVar("argName", fieldName)
		    .setVar("fieldName", fieldName);

		if (isMarkedGenerated()) {
			template.p('@')
    			.p(Pattern.class.getName())
    			.p("(name=\"")
    			.p(getPattern())
    			.pl("\")");
		}
		template.print(access.toCode());
		template.println(" ${returnType} ${methodName}(${argType} ${argName}) {");
		template.println("this.${fieldName} = ${argName};");
		switch (returnType) {
		case ARG:
			template.setVar("returnType", fieldType);
			template.println("return ${argName};");
			break;
		case TARGET:
			template.setVar("returnType", target.getSimpleName());
			template.println("return this;");
			break;
		case VOID:
			template.setVar("returnType", "void");
			break;
		default:
			checkTrue("returnType",returnType, false, "unknown type");
		}
		template.println("}");

		return template.asResolvedMethodNode();
	}

	@Optional
	public JMethodSetterBuilder methodAccess(JAccess access) {
		this.access = access;
		return this;
	}

	/**
	 * Sets both {@link #fieldName(String)}} and {@link #fieldType(String)}} at once
	 */
	public JMethodSetterBuilder field(JField f) {
		fieldName(f.getName());
		fieldType(f.getTypeSignature());
		return this;
	}

	@Required
	public JMethodSetterBuilder fieldName(String name) {
		this.fieldName = name;
		return this;
	}

	@Required
	public JMethodSetterBuilder fieldType(Type type) {
		fieldType(NameUtil.resolveQualifiedName(type));
		return this;
	}

	@Required
	public JMethodSetterBuilder fieldType(String type) {
		this.fieldType = NameUtil.toShortNameIfDefaultImport(type);
		return this;
	}

	@Optional
    public JMethodSetterBuilder methodName(String name) {
        this.methodName = name;
        return this;
    }

	@Optional
	public JMethodSetterBuilder returns(RETURNS returnType) {
		this.returnType = returnType;
		return this;
	}

	@Required
	public JMethodSetterBuilder target(JType target) {
		this.target = target;
		return this;
	}
}


text:
package com.github.jvmgo.clazz;

import com.github.jvmgo.clazz.attribute.Attribute_info;
import com.github.jvmgo.clazz.constant.CONSTANT;
import com.github.jvmgo.clazz.constant.CONSTANT_Utf8_info;
import com.github.jvmgo.clazz.field.Field_info;
import com.github.jvmgo.clazz.method.Method_info;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ClassFile {

    private String magic;

    private int minorVersion;

    private int majorVersion;

    private int constantPoolCount;

    private CONSTANT[] constantPool;

    private String accessFlags;

    private String thisClass;

    private String superClass;

    private int interfacesCount;

    private CONSTANT_Utf8_info[] interfaces;

    private int fieldsCount;

    private Field_info[] fields;

    private int methodsCount;

    private Method_info[] methods;

    private int attributesCount;

    private Attribute_info[] attributes;

    public Method_info getMainMethod() {
        for (Method_info m : methods) {
            if ("main".equals(m.getName()) && "([Ljava/lang/String;)V".equals(m.getDescriptor())) {
                return m;
            }
        }
        return null;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Open SCAP Library: unix Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Open SCAP Library

Main Page

Related Pages

Modules

Data Structures

Files

src

OVAL

probes

unix

unix Directory Reference

Directories

directory  	linux

directory  	solaris

Files

file  	dnscache.c

file  	file.c

 	file probe

file  	fileextendedattribute.c

 	fileextendedattribute probe

file  	gconf.c

 	gconf probe implementation

file  	interface.c

 	interface probe

file  	password.c

 	password probe

file  	process.c

 	process probe

file  	process58-capability.h [code]

file  	process58-devname.c

file  	process58-devname.h [code]

file  	process58.c

 	process58 probe

file  	routingtable.c

 	routingtable probe

file  	runlevel.c

 	runlevel probe

file  	shadow.c

 	shadow probe

file  	sysctl.c

 	implementation of the sysctl_object

file  	uname.c

 	uname probe

file  	xinetd.c

 	xinetd probe

<address class="footer">
Generated by

 1.8.6
</address>


text:
PROJECT=/tmp/bp-project.yml

cp projects/51-red.yml $PROJECT
bp -sv "$PROJECT" &
echo "showing red"
sleep 1
echo "red steady"
sleep 10

cp projects/52-green.yml $PROJECT
killall -SIGHUP %1
echo "showing green?"

sleep 1000


text:
package com.eharmony.pho.query.criterion;

/**
 * Enclosing type for all Query criterion components
 */
public interface Criterion {
}


text:
var _ = require('underscore'),
    feo = require('feo'),
    async = require('async');

module.exports = function(grunt) {
  'use strict';

  grunt.registerMultiTask('feo', 'optimize front-end', function() {
    var done = this.async(),
        options = this.options({
        }),
        args = [];

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        var arg = _.extend({}, options);
        arg.url = filepath;
        arg.dist = f.dest;
        args.push(arg);
      });
    });

    async.mapSeries(args, function(arg, callback){
      feo.on('exit', function(err){
        callback(err);
      });
      feo.cli(arg);
    }, function(err){
      done(!err);
    });
  });

};


text:
#!/bin/bash
mkdir -p target/classes
javac -d target/classes -sourcepath src/main/java src/main/java/io/mset/**/*.java


text:
#include "Utils\Utility.h"

#include "TestParser.h"

#include "Parser.h"
#include "Script.h"

#ifdef _DEBUG
extern vrDumpContext tracer;
#endif

//------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------
vrParser::vrParser(void)
{
	curLine           = 0;
	fileName          = nullString;
	nextFieldType     = 0;
	multiField        = FALSE;
	needsClear        = FALSE;
	nComponentsFound  = 0;
	nComponentsNeeded = 0;
	top               = NULL;
	lastType          = nullString;
	lastName          = nullString;
	viewpoint         = FALSE;
	console           = NULL;
	nextName          = nullString;
}

//------------------------------------------------------------------
// PROTO or EXTERNPROTO is encountered.  Create a new name space
// and push the new prototype onto the proto stack.
//------------------------------------------------------------------
void vrParser::BeginPrototype(const SFString& protoName, SFBool isExtern)
{
#ifdef _DEBUG
	tracer << endl << tracer.Indent() << "-->>BeginPrototype( \"" << protoName << "\" )" << endl;
	tracer.m_nIndents++;
#endif
	// The parser should not return a non-valid prototype name
	ASSERT(vrIsValidName(protoName));

	protoStack.Push(PushNameSpace(protoName));
}

//------------------------------------------------------------------
// PROTO or EXTERNPROTO is completed.  Pop the name space and add
// this PROTO to the available types.
//------------------------------------------------------------------
void vrParser::EndPrototype(void)
{
#ifdef _DEBUG
	tracer.m_nIndents--;
	tracer << tracer.Indent() << "<<--EndPrototype()" << endl;
#endif
	PopNameSpace();
  ASSERT(protoStack.Peek());
	AddProto(protoStack.Pop());
}

//------------------------------------------------------------------
// A node definition is encountered.  May be during the parsing of
// a PROTO or just a regular node.
//------------------------------------------------------------------
void vrParser::BeginNode(const SFString& nodeName)
{
#ifdef _DEBUG
	if (!nodeStack.Peek())
		tracer << endl;
	tracer << tracer.Indent() << "-->>BeginNode( \"" << nodeName << "\" )" << endl;
	tracer.m_nIndents++;
#endif

//if (nodeName=="Cone")
//{
//	printf("Hello");
//}
	// Don't move this -- CreateNewNode changes the stack
	vrNode *parent = GetCurrentNode();
	ASSERT(parent);
	vrBaseNode *node = CreateNewNode(nodeName);
	ASSERT(node->IsKindOf(GETRUNTIME_CLASS(vrNode)));
	vrNode *child = (vrNode*)node;
	ASSERT(parent == GetCurrentNode());

	if (child)
	{
		PushNode(child);

		if (nextName != nullString)
			child->SetName(nextName);
		nextName = nullString;

		if (InProto())
		{
			vrRuntimeClass *pClass = protoStack.Peek();
			ASSERT(pClass);
			pClass->AddChild(child);
#ifdef _DEBUG
			tracer << tracer.Indent() << "adding to proto" << endl;
#endif
		} else
		{
			ASSERT(parent);
			ASSERT(parent != child);
			parent->AddChild(child);
		}
	} else
	{
		Error("Node type: " + nodeName + " not found");
	}
}

void vrParser::EndNode(void)
{
#ifdef _DEBUG
	tracer.m_nIndents--;
	tracer << tracer.Indent() << "<<--EndNode()" << endl;
#endif

	vrNode *node = GetCurrentNode();
	ASSERT(node);
	// let the node complete its own creation (i.e. bind for binding nodes)
	node->CompleteNode(top);
	// for error reporting only
	lastType = node->ClassName();
	lastName = node->GetName();

	// Clean up the node state
	if (nodeStack.Peek())
		delete nodeStack.Pop();
}

//-----------------------------------------------------------------------
void vrParser::BeginField(const SFString& fieldName)
{
#ifdef _DEBUG
	tracer << tracer.Indent() << "-->>BeginField( \"" << fieldName << "\" )" << endl;
	tracer.m_nIndents++;
#endif

//if (fieldName == "bottom")
//{
//printf("Hello");
//}

	SetCurrentFieldName(fieldName);

	SFNode node = GetCurrentNode();
	ASSERT(node);
	SFInt32 fieldType = node->GetFieldType(fieldName);

	if (fieldType == 0)
	{
		vrRuntimeClass *pClass = Lookup(node->ClassName());
		if (pClass)
		{
			vrFieldList *list = pClass->GetFieldList();
			ASSERT(list);
			LISTPOS pos = list->GetHeadPosition();
			while (pos)
			{
				vrField *field = list->GetNext(pos);
				if (field->GetName() == fieldName)
				{
					fieldType = field->GetType();
				}
			}
			if (fieldType == 0)
				printf("Field type not found in proto" + fieldName);
		} else
			printf("No proto found");
/*
		if (fieldType == 0)
		{
			ASSERT(node && node->IsKindOf(GETRUNTIME_CLASS(vrScript)));
			if (node && node->IsKindOf(GETRUNTIME_CLASS(vrScript)))
			{
				vrFieldList *list = ((vrScript*)node)->GetFieldList();
				ASSERT(list);
				if (list)
				{
					LISTPOS pos = list->GetHeadPosition();
					while (pos)
					{
						vrField *field = list->GetNext(pos);
						if (field->GetName() == fieldName)
						{
							fieldType = field->GetType();
						}
					}
				}
			}
		}
		if (fieldType == 0)
			Error("Field type not found in proto");
printf("Hello");
*/
	}
	nextFieldType = fieldType;
}

void vrParser::EndField(void)
{
#ifdef _DEBUG
	tracer.m_nIndents--;
	tracer << tracer.Indent() << "<<--EndField()" << endl;
#endif
	// do nothing
}

//------------------------------------------------------------------
// Currently parsing either a script node or a PROTO or EXTERNPROTO.
// This is called when a interface declaration is encountered.
//------------------------------------------------------------------
SFInt32 vrParser::DeclareInterface(vrEventType eventType, const SFString& fieldType, const SFString& fieldName)
{
#ifdef _DEBUG
	tracer << tracer.Indent() << "AddField( \"" + GetEventTypeName(eventType) + "\", \"" <<
				fieldType << "\", \"" << fieldName << "\" )" << endl;
#endif

	// May return zero if .wrl file has an invalid field type.
	SFInt32 type = ::GetFieldType(fieldType);
	if (type)
	{
		if (IsScript())
		{
			SetCurrentFieldName(fieldName);
			// This field is being added to a script node
			vrScript *script = (vrScript *)GetCurrentNode();
			ASSERT(script);
			script->AddField(eventType, type, fieldName, -1);
		} else if (InProto())
		{
			vrRuntimeClass *pClass = protoStack.Peek();
			ASSERT(pClass);
			pClass->AddField(fieldName, type, eventType, -1);
		} else
		{
			Error(SFString("Invalid interface declaration: ") + GetEventTypeName(type) + ":" + fieldType + ":" + fieldName);
			type = 0;
		}
	} else
	{
		Error(SFString("Invalid field type: ") + fieldType);
	}
	return type;
}

//-----------------------------------------------------------------------
void vrParser::AddRoute(const SFString& fromNode, const SFString& fromField, const SFString& toNode, const SFString& toField)
{
#ifdef _DEBUG
	static int nRoutes=0;
	if (!nRoutes)
		tracer << endl;
	nRoutes++;
	tracer << tracer.Indent() << "ROUTE " << fromNode << "." << fromField
					<< " TO " << toNode << "." << toField << endl;
#endif

	SFBool valid = FALSE;

	SFNode from = top->FindByName(fromNode);
	SFNode to   = top->FindByName(toNode);

	if (from && to)
		valid = (SFBool)from->AddRoute(fromField, to, toField);

	if (!valid)
		Error("Invalid ROUTE " + fromNode + " TO " + toNode);
}

void vrParser::MapFieldName(const SFString& to)
{
	vrRuntimeClass *pClass = protoStack.Peek();
	ASSERT(pClass);

	vrNodeStackItem *ns = nodeStack.Peek();
	//Must chech that IS maps two identical field types.
#ifdef _DEBUG
	tracer << tracer.Indent() << pClass->ClassName() << ": "
			<< ns->curField << " IS " << to << endl;
#endif
}

void vrParser::DefineCurrentNode(const SFString& name)
{
#ifdef _DEBUG
	tracer << tracer.Indent() << "DefineCurrentNode( \"" << name << "\" )" << endl;
#endif

	ASSERT(top);

	// If this name already exists we must remove the name
	SFNode node = top->FindByName(name);
	if (node)
		node->SetName(nullString);
	ASSERT(!top->FindByName(name));
	nextName = name;
}

//------------------------------------------------------------------
void vrParser::UseDefinedNode(const SFString& name)
{
#ifdef _DEBUG
	tracer << tracer.Indent() << "UseDefinedNode( \"" << name << "\" )" << endl;
#endif

	ASSERT(top);
	SFNode node = top->FindByName(name);
	if (node)
	{
		SFNode parent = top;
		if (nodeStack.Peek())
			parent = nodeStack.Peek()->curNode;
		ASSERT(parent);
		parent->AddChild(node);
	} else
	{
		Error("USE " + name + " encountered.  No corresponding DEF found.");
	}
}

//-----------------------------------------------------------------------
void vrParser::Error(const SFString& msg)
{
	vrDumpString ds;
	ds.m_nIndents++;

	ds << ds.Indent() << "\nError In File:      " << fileName << endl;
	ds << ds.Indent() << "Error Line Number:  " << curLine+1 << endl;
	ds << ds.Indent() << "Error Message:      " << msg << endl;

	ds << ds.Indent() << "Last Good Node:     " << lastType <<
		"( \"" << lastName << "\" )" << endl;

	vrNodeStackItem *ns = nodeStack.Peek();
	if (ns)
	{
		if (ns->curField != nullString)
		{
			ds << ds.Indent() << "Current Field:      " << ns->curField << endl;
			if (ns->curNode)
				ds << ds.Indent() << "Current Node:       " << ns->curNode->ClassName() << endl;
		} else if (ns->curNode)
		{
			ds << ds.Indent() << "Current Node:       " << ns->curNode->ClassName() << endl;
		}
	}

	if (console)
		console->Error(ds.string);

	nextFieldType = 0;
}

void vrParser::Clear(void)
{
	curLine = 1;
	while (nodeStack.Peek())
		delete nodeStack.Pop();
	while (protoStack.Peek())
		delete protoStack.Pop();
	ASSERT(nodeStack.Empty());
	ASSERT(protoStack.Empty());
}

SFBool vrParser::IsScript(void) const
{
	if (!IsNode())
		return FALSE;
	ASSERT(nodeStack.Peek());
	ASSERT(nodeStack.Peek()->curNode);
	return (nodeStack.Peek()->curNode->IsKindOf(GETRUNTIME_CLASS(vrScript)));
}

//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
vrPrototypeList m_PrototypeList;
//-------------------------------------------------------------------------
void AddProto(vrRuntimeClass *pClass)
{
	// already defined?
	if (Lookup(pClass->ClassName()))
    return;
  m_PrototypeList.AddHead(pClass);
}

vrRuntimeClass *PushNameSpace(const SFString& className)
{
	m_PrototypeList.AddHead((vrRuntimeClass *)NULL);

	vrRuntimeClass *pClass = vrLookupBuiltin("vr"+className);
	if (pClass)
		return pClass;

  pClass = new vrRuntimeClass();
	ASSERT(pClass);
	pClass->Initialize(className);
	return pClass;
}

void PopNameSpace()
{
	LISTPOS pos = m_PrototypeList.GetHeadPosition();
	while (pos)
	{
		LISTPOS p = pos;
		vrRuntimeClass *pClass = m_PrototypeList.GetNext(pos);
    m_PrototypeList.RemoveAt(p);
    if (!pClass)
			break;
		delete pClass;
	}
}

vrRuntimeClass *Lookup(const SFString& name)
{
	vrRuntimeClass *pClass = vrLookupBuiltin("vr"+name);
	if (pClass)
		return pClass;

	LISTPOS pos = m_PrototypeList.GetHeadPosition();
	while (pos)
	{
		pClass = m_PrototypeList.GetNext(pos);
    if (pClass && name == pClass->ClassName())
			return pClass;
  }
  return NULL;
}

//------------------------------------------------------------------
// The parser used to parse the file.  Should be a pointer
// that is created and destroyed at each parse to clean up memory.
//------------------------------------------------------------------
static vrParser parser;
vrParser *GetParser(void)
{
	return &parser;
}


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

<title>Model (playframework)</title>
<meta name="date" content="2013-04-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

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

play.db.ebean

Class Model

java.lang.Object

play.db.ebean.Model

public class Model
extends java.lang.Object

Base-class for Ebean-mapped models that provides convenience methods.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
Model.Finder<I,T>

Helper for Ebean queries.

Constructor Summary

Constructors

Constructor and Description

Model()

Method Summary

Methods

Modifier and Type
Method and Description

void
delete()

Deletes this entity.

void
delete(java.lang.String server)

Deletes this entity, using a specific Ebean server.

void
deleteManyToManyAssociations(java.lang.String path)

Deletes a many-to-many association

boolean
equals(java.lang.Object other)

int
hashCode()

void
refresh()

Refreshes this entity from the database.

void
refresh(java.lang.String server)

Refreshes this entity from the database, using a specific Ebean server.

void
save()

Saves (inserts) this entity.

void
save(java.lang.String server)

Saves (inserts) this entity.

void
saveManyToManyAssociations(java.lang.String path)

Persist a many-to-many association.

void
saveManyToManyAssociations(java.lang.String server,
                          java.lang.String path)

Persist a many-to-many association.

void
update()

Updates this entity.

void
update(java.lang.Object id)

Updates this entity, by specifying the entity ID.

void
update(java.lang.Object id,
      java.lang.String server)

Updates this entity, by specifying the entity ID, using a specific Ebean server.

void
update(java.lang.String server)

Updates this entity, using a specific Ebean server.

Methods inherited from class java.lang.Object

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

Constructor Detail

Model

public Model()

Method Detail

save

public void save()

Saves (inserts) this entity.

save

public void save(java.lang.String server)

Saves (inserts) this entity.

Parameters:

server - the Ebean server to use

saveManyToManyAssociations

public void saveManyToManyAssociations(java.lang.String path)

Persist a many-to-many association.

saveManyToManyAssociations

public void saveManyToManyAssociations(java.lang.String server,
                              java.lang.String path)

Persist a many-to-many association.

Parameters:

server - the Ebean server to use

deleteManyToManyAssociations

public void deleteManyToManyAssociations(java.lang.String path)

Deletes a many-to-many association

update

public void update()

Updates this entity.

update

public void update(java.lang.String server)

Updates this entity, using a specific Ebean server.

Parameters:

server - the Ebean server to use

update

public void update(java.lang.Object id)

Updates this entity, by specifying the entity ID.

update

public void update(java.lang.Object id,
          java.lang.String server)

Updates this entity, by specifying the entity ID, using a specific Ebean server.

Parameters:

server - the Ebean server to use

delete

public void delete()

Deletes this entity.

delete

public void delete(java.lang.String server)

Deletes this entity, using a specific Ebean server.

Parameters:

server - the Ebean server to use

refresh

public void refresh()

Refreshes this entity from the database.

refresh

public void refresh(java.lang.String server)

Refreshes this entity from the database, using a specific Ebean server.

Parameters:

server - the Ebean server to use

equals

public boolean equals(java.lang.Object other)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

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


text:
game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// reset the score
		game.data.score = 0;

		me.levelDirector.loadLevel("level01");	//loads level 1

		var player = me.pool.pull("player", 0, 420, {});	//loads the player to the map
		me.game.world.addChild(player, 5);	//adds the player to the world

		var gametimermanager = me.pool.pull("GameTimerManager", 0, 0, {});	//adds the game manager variable
		me.game.world.addChild(gametimermanager, 0);	//adds the game manager to the world

		var herodeathmanager = me.pool.pull("HeroDeathManager", 0, 0, {});	//adds the hero death manager variable
		me.game.world.addChild(herodeathmanager, 0);	//adds the game manager to the world

		var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {});	//adds the experience manager variable
		me.game.world.addChild(experienceManager, 0);	//adds the game manager to the world

		var spendGold = me.pool.pull("SpendGold", 0, 0, {});	//adds the experience manager variable
		me.game.world.addChild(spendGold, 0);

		me.input.bindKey(me.input.KEY.B, "buy");
		me.input.bindKey(me.input.KEY.Q, "skill1");
		me.input.bindKey(me.input.KEY.W, "skill2");
		me.input.bindKey(me.input.KEY.E, "skill3");
		me.input.bindKey(me.input.KEY.RIGHT, "right"); //sets the key to move right the right arrow
		me.input.bindKey(me.input.KEY.A, "attack");		//binds the key A for attack
		me.input.bindKey(me.input.KEY.SPACE, "jump");	//binds the key space bar for jump
		me.input.bindKey(me.input.KEY.LEFT, "left"); //sets the key to move left the left arrow
		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);

		me.audio.playTrack("cupcakes");
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
		me.audio.stopTrack();
	},

	resetPlayer: function(x, y){

		game.data.player = me.pool.pull("player", x, y, {});	//loads the player to the map
		me.game.world.addChild(game.data.player, 5);	//adds the player to the world
	}
});


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

namespace SharpShell.Attributes
{
    /// <summary>
    /// Attribute to describe handler subkey config.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field)]
    public class HandlerSubkeyAttribute : Attribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HandlerSubkeyAttribute" /> class.
        /// </summary>
        /// <param name="allowMultipleEntries">if set to <c>true</c> [allow multiple entries].</param>
        /// <param name="handlerSubkey">The handler subkey.</param>
        public HandlerSubkeyAttribute(bool allowMultipleEntries, string handlerSubkey)
        {
            AllowMultipleEntries = allowMultipleEntries;
            HandlerSubkey = handlerSubkey;
        }

        /// <summary>
        /// Gets a value indicating whether multiple entries are allowed.
        /// </summary>
        /// <value>
        /// <c>true</c> if multiple entries are allowed; otherwise, <c>false</c>.
        /// </value>
        public bool AllowMultipleEntries { get; private set; }

        /// <summary>
        /// Gets the handler subkey.
        /// </summary>
        /// <value>
        /// The handler subkey.
        /// </value>
        public string HandlerSubkey { get; private set; }
    }
}