text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\VehicleType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;

/**
 * Vehicletype controller.
 *
 * @Route("vehicletype")
 */
class VehicleTypeController extends Controller
{
    /**
     * Lists all vehicleType entities.
     *
     * @Route("/", name="vehicletype_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $vehicleTypes = $em->getRepository('AppBundle:VehicleType')->findAll();

        return $this->render('vehicletype/index.html.twig', array(
            'vehicleTypes' => $vehicleTypes,
        ));
    }

    /**
     * Creates a new vehicleType entity.
     *
     * @Route("/new", name="vehicletype_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $vehicleType = new Vehicletype();
        $form = $this->createForm('AppBundle\Form\VehicleTypeType', $vehicleType);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($vehicleType);
            $em->flush();

            return $this->redirectToRoute('vehicletype_show', array('id' => $vehicleType->getId()));
        }

        return $this->render('vehicletype/new.html.twig', array(
            'vehicleType' => $vehicleType,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a vehicleType entity.
     *
     * @Route("/{id}", name="vehicletype_show")
     * @Method("GET")
     */
    public function showAction(VehicleType $vehicleType)
    {
        $deleteForm = $this->createDeleteForm($vehicleType);

        return $this->render('vehicletype/show.html.twig', array(
            'vehicleType' => $vehicleType,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing vehicleType entity.
     *
     * @Route("/{id}/edit", name="vehicletype_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, VehicleType $vehicleType)
    {
        $deleteForm = $this->createDeleteForm($vehicleType);
        $editForm = $this->createForm('AppBundle\Form\VehicleTypeType', $vehicleType);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('vehicletype_edit', array('id' => $vehicleType->getId()));
        }

        return $this->render('vehicletype/edit.html.twig', array(
            'vehicleType' => $vehicleType,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a vehicleType entity.
     *
     * @Route("/{id}", name="vehicletype_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, VehicleType $vehicleType)
    {
        $form = $this->createDeleteForm($vehicleType);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($vehicleType);
            $em->flush();
        }

        return $this->redirectToRoute('vehicletype_index');
    }

    /**
     * Creates a form to delete a vehicleType entity.
     *
     * @param VehicleType $vehicleType The vehicleType entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(VehicleType $vehicleType)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('vehicletype_delete', array('id' => $vehicleType->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
package ru.alttiri.csc.testing.demo1;

import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class RuleTest {

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @Test
    @Ignore
    public void demo() throws Exception {
        tempFolder.newFile();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package obcpbft

import (
	"fmt"
	"time"

	"github.com/hyperledger/fabric/consensus"
	pb "github.com/hyperledger/fabric/protos"

	"github.com/golang/protobuf/proto"
	"github.com/spf13/viper"
	google_protobuf "google/protobuf"
)

type obcBatch struct {
	obcGeneric

	batchSize        int
	batchStore       []*Request
	batchTimer       *time.Timer
	batchTimerActive bool
	batchTimeout     time.Duration
	inViewChange     bool

	incomingChan     chan *batchMessage // Queues messages for processing by main thread
	custodyTimerChan chan custodyInfo   // Queues complaints
	execChan         chan *execInfo     // Signals an execution event
	viewChanged      chan struct{}      // Signals that a view change has occurred
	idleChan         chan struct{}      // Used in unit testing to check for idleness

	complainer   *complainer
	deduplicator *deduplicator

	persistForward
}

type custodyInfo struct {
	hash      string
	req       interface{}
	complaint bool
}

type batchMessage struct {
	msg    *pb.Message
	sender *pb.PeerID
}

type execInfo struct {
	seqNo uint64
	raw   []byte
}

func newObcBatch(id uint64, config *viper.Viper, stack consensus.Stack) *obcBatch {
	var err error

	op := &obcBatch{
		obcGeneric: obcGeneric{stack: stack},
	}

	op.persistForward.persistor = stack

	logger.Debug("Replica %d obtaining startup information", id)

	op.pbft = newPbftCore(id, config, op)

	op.batchSize = config.GetInt("general.batchSize")
	op.batchStore = nil
	op.batchTimeout, err = time.ParseDuration(config.GetString("general.timeout.batch"))
	if err != nil {
		panic(fmt.Errorf("Cannot parse batch timeout: %s", err))
	}

	op.incomingChan = make(chan *batchMessage)
	op.custodyTimerChan = make(chan custodyInfo)
	op.execChan = make(chan *execInfo)

	op.complainer = newComplainer(op, op.pbft.requestTimeout, op.pbft.requestTimeout)
	op.deduplicator = newDeduplicator()

	// create non-running timer
	op.batchTimer = time.NewTimer(100 * time.Hour) // XXX ugly
	op.batchTimer.Stop()

	op.idleChan = make(chan struct{})
	op.viewChanged = make(chan struct{})

	go op.main()
	return op
}

// RecvMsg receives both CHAIN_TRANSACTION and CONSENSUS messages from
// the stack. New transaction requests are broadcast to all replicas,
// so that the current primary will receive the request.
func (op *obcBatch) RecvMsg(ocMsg *pb.Message, senderHandle *pb.PeerID) error {
	op.incomingChan <- &batchMessage{
		msg:    ocMsg,
		sender: senderHandle,
	}

	return nil
}

// Complain is necessary to implement complaintHandler
func (op *obcBatch) Complain(hash string, req *Request, primaryFail bool) {
	logger.Debug("Replica %d processing complaint from custodian", op.pbft.id)
	op.custodyTimerChan <- custodyInfo{hash, req, primaryFail}
}

// Close tells us to release resources we are holding
func (op *obcBatch) Close() {
	op.complainer.Stop()
	op.batchTimer.Reset(0)
	op.pbft.close()
}

func (op *obcBatch) submitToLeader(req *Request) {
	// submit to current leader
	leader := op.pbft.primary(op.pbft.view)
	if leader == op.pbft.id && op.pbft.activeView {
		op.leaderProcReq(req)
	} else {
		op.unicastMsg(&BatchMessage{&BatchMessage_Request{req}}, leader)
	}
}

func (op *obcBatch) broadcastMsg(msg *BatchMessage) {
	msgPayload, _ := proto.Marshal(msg)
	ocMsg := &pb.Message{
		Type:    pb.Message_CONSENSUS,
		Payload: msgPayload,
	}
	op.stack.Broadcast(ocMsg, pb.PeerEndpoint_UNDEFINED)
}

// send a message to a specific replica
func (op *obcBatch) unicastMsg(msg *BatchMessage, receiverID uint64) {
	msgPayload, _ := proto.Marshal(msg)
	ocMsg := &pb.Message{
		Type:    pb.Message_CONSENSUS,
		Payload: msgPayload,
	}
	receiverHandle, err := getValidatorHandle(receiverID)
	if err != nil {
		return

	}
	op.stack.Unicast(ocMsg, receiverHandle)
}

// =============================================================================
// innerStack interface (functions called by pbft-core)
// =============================================================================

// multicast a message to all replicas
func (op *obcBatch) broadcast(msgPayload []byte) {
	op.stack.Broadcast(op.wrapMessage(msgPayload), pb.PeerEndpoint_UNDEFINED)
}

// send a message to a specific replica
func (op *obcBatch) unicast(msgPayload []byte, receiverID uint64) (err error) {
	receiverHandle, err := getValidatorHandle(receiverID)
	if err != nil {
		return
	}
	return op.stack.Unicast(op.wrapMessage(msgPayload), receiverHandle)
}

func (op *obcBatch) sign(msg []byte) ([]byte, error) {
	return op.stack.Sign(msg)
}

// verify message signature
func (op *obcBatch) verify(senderID uint64, signature []byte, message []byte) error {
	senderHandle, err := getValidatorHandle(senderID)
	if err != nil {
		return err
	}
	return op.stack.Verify(senderHandle, signature, message)
}

// validate checks whether the request is valid syntactically
// not used in obc-batch at the moment
func (op *obcBatch) validate(txRaw []byte) error {
	return nil
}

// execute an opaque request which corresponds to an OBC Transaction
func (op *obcBatch) execute(seqNo uint64, raw []byte) {
	op.execChan <- &execInfo{
		seqNo: seqNo,
		raw:   raw,
	}
}

func (op *obcBatch) executeImpl(seqNo uint64, raw []byte) {
	reqs := &RequestBlock{}
	if err := proto.Unmarshal(raw, reqs); err != nil {
		logger.Warning("Batch replica %d could not unmarshal request block: %s", op.pbft.id, err)
		return
	}

	logger.Debug("Batch replica %d received exec for seqNo %d", op.pbft.id, seqNo)

	var txs []*pb.Transaction

	for _, req := range reqs.Requests {
		op.complainer.Success(req)

		if !op.deduplicator.Execute(req) {
			logger.Debug("Batch replica %d received exec of stale request from %d via %d",
				op.pbft.id, req.ReplicaId, req.ReplicaId)
			continue
		}

		tx := &pb.Transaction{}
		if err := proto.Unmarshal(req.Payload, tx); err != nil {
			logger.Warning("Batch replica %d could not unmarshal transaction: %s", op.pbft.id, err)
			continue
		}
		txs = append(txs, tx)
	}

	meta, _ := proto.Marshal(&Metadata{seqNo})

	id := []byte("foo")
	op.stack.BeginTxBatch(id)
	result, err := op.stack.ExecTxs(id, txs)
	_ = err    // XXX what to do on error?
	_ = result // XXX what to do with the result?
	_, err = op.stack.CommitTxBatch(id, meta)

	op.pbft.execDone()
}

// signal when a view-change happened, this is the PBFT thread, don't modify internal state and give it back!
func (op *obcBatch) viewChange(curView uint64) {

	// Outstanding reqs doesn't make sense for batch, as all the requests in a batch may be processed
	// in a different batch, but PBFT core can't see through the opaque structure to see this
	// so, on view change, we rely on the fact that the complaint service will resubmit requests
	// and instead zero the outstandingReqs map ourselves
	op.pbft.outstandingReqs = make(map[string]*Request)

	logger.Debug("Replica %d PBFT view change thread attempting to signal batch thread", op.pbft.id)

	go func() { op.viewChanged <- struct{}{} }()
}

// =============================================================================
// functions specific to batch mode
// =============================================================================

func (op *obcBatch) leaderProcReq(req *Request) error {
	// XXX check req sig

	if !op.deduplicator.Request(req) {
		logger.Debug("Batch replica %d received stale request from %d",
			op.pbft.id, req.ReplicaId)
		return nil
	}

	hash := hashReq(req)

	logger.Debug("Batch primary %d queueing new request %s", op.pbft.id, hash)
	op.batchStore = append(op.batchStore, req)

	if !op.batchTimerActive {
		op.startBatchTimer()
	}

	if len(op.batchStore) >= op.batchSize {
		op.sendBatch()
	}

	return nil
}

func (op *obcBatch) sendBatch() error {
	op.stopBatchTimer()

	reqBlock := &RequestBlock{op.batchStore}
	op.batchStore = nil

	reqsPacked, err := proto.Marshal(reqBlock)
	if err != nil {
		err = fmt.Errorf("Unable to pack block for new batch request")
		logger.Error(err.Error())
		return err
	}

	// process internally
	logger.Info("Creating batch with %d requests", len(reqBlock.Requests))
	op.pbft.request(reqsPacked, op.pbft.id)

	return nil
}

func (op *obcBatch) txToReq(tx []byte) *Request {
	now := time.Now()
	req := &Request{
		Timestamp: &google_protobuf.Timestamp{
			Seconds: now.Unix(),
			Nanos:   int32(now.UnixNano() % 1000000000),
		},
		Payload:   tx,
		ReplicaId: op.pbft.id,
	}
	// XXX sign req
	return req
}

func (op *obcBatch) processMessage(ocMsg *pb.Message, senderHandle *pb.PeerID) error {
	if ocMsg.Type == pb.Message_CHAIN_TRANSACTION {
		req := op.txToReq(ocMsg.Payload)
		hash := op.complainer.Custody(req)

		logger.Info("Batch replica %d received new consensus request: %s", op.pbft.id, hash)

		op.submitToLeader(req)
		return nil
	}

	if ocMsg.Type != pb.Message_CONSENSUS {
		return fmt.Errorf("Unexpected message type: %s", ocMsg.Type)
	}

	batchMsg := &BatchMessage{}
	err := proto.Unmarshal(ocMsg.Payload, batchMsg)
	if err != nil {
		return err
	}

	if req := batchMsg.GetRequest(); req != nil {
		if (op.pbft.primary(op.pbft.view) == op.pbft.id) && op.pbft.activeView {
			err := op.leaderProcReq(req)
			if err != nil {
				return err
			}
		}
	} else if pbftMsg := batchMsg.GetPbftMessage(); pbftMsg != nil {
		senderID, err := getValidatorID(senderHandle) // who sent this?
		if err != nil {
			panic("Cannot map sender's PeerID to a valid replica ID")
		}
		op.pbft.receive(pbftMsg, senderID)
	} else if complaint := batchMsg.GetComplaint(); complaint != nil {
		if op.pbft.primary(op.pbft.view) == op.pbft.id && op.pbft.activeView {
			return op.leaderProcReq(complaint)
		}

		// XXX check req sig
		if !op.deduplicator.IsNew(complaint) {
			logger.Debug("Batch replica %d received stale complaint from %d",
				op.pbft.id, complaint.ReplicaId)
			return nil
		}

		hash := op.complainer.Complaint(complaint)
		logger.Debug("Batch replica %d received complaint %s", op.pbft.id, hash)

		op.submitToLeader(complaint)
	} else {
		err = fmt.Errorf("Unknown request: %+v", batchMsg)
		logger.Error(err.Error())
	}

	return nil
}

// resubmitStaleRequest deals with requests that became stale.  If the
// request has indeed been executed, we don't have to do anything.  If
// this request raced with a later one and lost, then we need to
// repackage this request's payload into a new request and resubmit
// it.
func (op *obcBatch) resubmitStaleRequest(c custodyInfo) {
	oldReq := c.req.(*Request)

	if !op.complainer.InCustody(oldReq) {
		logger.Debug("Batch replica %d custody expired for stale request: %s",
			op.pbft.id, c.hash)
		return
	}

	newReq := op.txToReq(oldReq.Payload)

	logger.Info("Batch replica %d custody expired for skipped request %s, resubmitting as %s",
		op.pbft.id, hashReq(oldReq), hashReq(newReq))
	op.complainer.Success(oldReq)
	op.complainer.Custody(newReq)
	op.submitToLeader(newReq)
}

// allow the primary to send a batch when the timer expires
func (op *obcBatch) main() {
	for {
		logger.Debug("Replica %d batch main thread looping", op.pbft.id)
		select {
		case <-op.pbft.closed:
			close(op.idleChan)
			return
		case ocMsg := <-op.incomingChan:
			if err := op.processMessage(ocMsg.msg, ocMsg.sender); nil != err {
				logger.Error("Error processing message: %v", err)
			}
		case <-op.batchTimer.C:
			logger.Info("Replica %d batch timer expired", op.pbft.id)
			if op.pbft.activeView && (len(op.batchStore) > 0) {
				op.sendBatch()
			}
		case <-op.viewChanged:
			logger.Debug("Replica %d batch thread recognizing new view", op.pbft.id)
			op.inViewChange = false
			if op.batchTimerActive {
				op.stopBatchTimer()
			}

			op.complainer.Restart()
			for _, pair := range op.complainer.CustodyElements() {
				logger.Info("Replica %d resubmitting request under custody: %s", op.pbft.id, pair.Hash)
				op.submitToLeader(pair.Request)
			}
		case c := <-op.custodyTimerChan:
			if !op.deduplicator.IsNew(c.req.(*Request)) {
				op.resubmitStaleRequest(c)
				continue
			}

			if !c.complaint {
				logger.Warning("Batch replica %d custody expired, complaining: %s", op.pbft.id, c.hash)
				op.broadcastMsg(&BatchMessage{&BatchMessage_Complaint{c.req.(*Request)}})
			} else {
				if !op.inViewChange && op.pbft.activeView {
					logger.Debug("Batch replica %d complaint timeout expired for %s", op.pbft.id, c.hash)
					op.inViewChange = true
					op.pbft.injectChan <- func() { op.pbft.sendViewChange() }
				} else {
					logger.Debug("Batch replica %d complaint timeout expired for %s while in view change", op.pbft.id, c.hash)
				}
			}
		case execInfo := <-op.execChan:
			op.executeImpl(execInfo.seqNo, execInfo.raw)
		case op.idleChan <- struct{}{}:
			// Only used to detect thread idleness during unit tests
		}
	}
}

func (op *obcBatch) startBatchTimer() {
	op.batchTimer.Reset(op.batchTimeout)
	logger.Debug("Replica %d started the batch timer", op.pbft.id)
	op.batchTimerActive = true
}

func (op *obcBatch) stopBatchTimer() {
	op.batchTimer.Stop()
	logger.Debug("Replica %d stopped the batch timer", op.pbft.id)
	op.batchTimerActive = false
	select {
	case <-op.pbft.closed:
		return
	default:
	}
loopBatch:
	for {
		select {
		case <-op.batchTimer.C:
		default:
			break loopBatch
		}
	}
}

// Wraps a payload into a batch message, packs it and wraps it into
// a Fabric message. Called by broadcast before transmission.
func (op *obcBatch) wrapMessage(msgPayload []byte) *pb.Message {
	batchMsg := &BatchMessage{&BatchMessage_PbftMessage{msgPayload}}
	packedBatchMsg, _ := proto.Marshal(batchMsg)
	ocMsg := &pb.Message{
		Type:    pb.Message_CONSENSUS,
		Payload: packedBatchMsg,
	}
	return ocMsg
}

// Retrieve the idle channel, only used for testing
func (op *obcBatch) idleChannel() <-chan struct{} {
	return op.idleChan
}


text:
<?php

namespace PDepend\Source\AST;

/**
 * This node class represents a trait adaptation alias.
 *
 * @copyright 2008-2017 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 * @since 1.0.0
 */
class ASTTraitAdaptationAlias extends ASTStatement
{
    /**
     * The new aliased method name.
     *
     * @var string
     */
    protected $newName;

    /**
     * The new method modifier for the imported method.
     *
     * @var integer
     */
    protected $newModifier = -1;

    /**
     * Sets the new method modifier.
     *
     * @param integer $newModifier The new method modifier.
     *
     * @return void
     */
    public function setNewModifier($newModifier)
    {
        $this->newModifier = $newModifier;
    }

    /**
     * Returns the new method modifier or -1 when this alias does not
     * specify a new method modifier.
     *
     * @return integer
     */
    public function getNewModifier()
    {
        return $this->newModifier;
    }

    /**
     * Sets the new aliased method name.
     *
     * @param string $newName The new aliased method name.
     *
     * @return void
     */
    public function setNewName($newName)
    {
        $this->newName = $newName;
    }

    /**
     * Returns the new aliased method name or NULL when this alias does
     * not specify a new method name.
     *
     * @return string
     */
    public function getNewName()
    {
        return $this->newName;
    }

    /**
     * The magic sleep method will be called by PHP's runtime environment right
     * before an instance of this class gets serialized. It should return an
     * array with those property names that should be serialized for this class.
     *
     * @return array
     */
    public function __sleep()
    {
        return array_merge(array('newName', 'newModifier'), parent::__sleep());
    }

    /**
     * Accept method of the visitor design pattern. This method will be called
     * by a visitor during tree traversal.
     *
     * @param \PDepend\Source\ASTVisitor\ASTVisitor $visitor The calling visitor instance.
     * @param mixed                                 $data
     *
     * @return mixed
     */
    public function accept(\PDepend\Source\ASTVisitor\ASTVisitor $visitor, $data = null)
    {
        return $visitor->visitTraitAdaptationAlias($this, $data);
    }
}


text:
import unittest

from chattymarkov import database

class TestDatabase(unittest.TestCase):
    def test_build_database_connection(self):
        """Test `build_database_connection` of `chattymarkov.database`."""
        redis_socket_connection = database.build_database_connection(
            "redis:///path/to/redis/unix_socket.sock;db=1")
        self.assertEquals(redis_socket_connection.db, 1)
        self.assertEquals(redis_socket_connection.unix_socket_path,
                          "/path/to/redis/unix_socket.sock")

        redis_socket_connection = database.build_database_connection(
            "redis://localhost:12345;db=3")
        self.assertEquals(redis_socket_connection.db, 3)
        self.assertEquals(redis_socket_connection.host, "localhost")
        self.assertEquals(redis_socket_connection.port, 12345)


text:
from __future__ import unicode_literals

from django.forms.models import inlineformset_factory

from ..galleries.models import Gallery
from .models import Portfolio

PortfolioFormSet = inlineformset_factory(
    Gallery, Portfolio, fields=['name', 'image'],
    can_delete=False, extra=2, min_num=1, validate_min=True)


text:
package kariminf.langpi.basic.italian;

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

import org.tartarus.snowball.ext.ItalianStemmer;

import kariminf.langpi.basic.Stemmer;

public class ItStemmer implements Stemmer {

	private ItalianStemmer stemmer = new ItalianStemmer();

	@Override
	public List<String> stemListWords(List<String> listWords) {

		List<String> stemmedLW = new ArrayList<String>();

		for (String word: listWords)
			stemmedLW.add(stemWord(word));

		return stemmedLW;
	}

	public String stemWord (String word){

		stemmer.setCurrent(word);
		stemmer.stem();
		return stemmer.getCurrent();
	}

	public static void main(String[] args) {
		ItStemmer Stemmer=new ItStemmer();
		List<String> tstList = new ArrayList<String>();
		tstList.add("il");
		tstList.add("risultato");
		tstList.add("della");
		tstList.add("prima");
		tstList.add("campagna");
		tstList.add("fu");
		tstList.add("l");
		tstList.add("assedio");
		tstList.add("della");
		tstList.add("capitale");
		tstList.add("dacica");
		tstList.add("sarmizegetusa");
		tstList.add("regia");
		tstList.add("e");
		tstList.add("l");
		tstList.add("occupazione");
		tstList.add("di");
		tstList.add("parte");
		tstList.add("del");
		tstList.add("suo");
		tstList.add("territorio");

		tstList = Stemmer.stemListWords(tstList);
		System.out.println(tstList.toString());

	}

}


text:
namespace Urho3D
{

/// A common root class for objects that implement both Serializer and Deserializer.
/// @fakeref
class URHO3D_API AbstractFile : public Deserializer, public Serializer
{
public:
    /// Construct.
    AbstractFile() : Deserializer() { }
    /// Construct.
    explicit AbstractFile(unsigned int size) : Deserializer(size) { }
    /// Destruct.
    ~AbstractFile() override = default;
    /// Change the file name. Used by the resource system.
    /// @property
    virtual void SetName(const String& name) { name_ = name; }
    /// Return the file name.
    const String& GetName() const override { return name_; }

protected:
    /// File name.
    String name_;
};

}


text:
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Services;

namespace Solution.Web.Managers.WebServices
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://192.168.0.10/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(true)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
    // [System.Web.Script.Services.ScriptService]
    public class Weather : WebService
    {
        /// <summary>
        /// 獲取天氣信息
        /// </summary>
        /// <param name="cityid">城市代碼</param>
        /// <returns>json字符串</returns>
        [WebMethod(Description = "獲取天氣信息",CacheDuration=1800)]
        public string GetWeather(string cityid)
        {
            const string url = "http://apis.baidu.com/apistore/weatherservice/recentweathers";
            string param = "cityid=" + cityid;
            string strUrl = url + '?' + param;
            var request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Method = "GET";
            // 添加header
            request.Headers.Add("apikey", "4e3dc30c80cae59cbd7105bc151dc4fd");
            var response = (HttpWebResponse)request.GetResponse();
            var s = response.GetResponseStream();
            string strDate;
            string strValue = "";
            StreamReader reader = new StreamReader(s, Encoding.UTF8);
            while ((strDate = reader.ReadLine()) != null)
            {
                strValue += strDate + "\r\n";
            }
            return strValue;
            //return HttpUtility.UrlDecode(str);
        }
    }
}


text:
/*++

Module Name:

  ResetNotificationBBTestMain.h

Abstract:

  Test Driver of Reset Notification Protocol header file

--*/

#ifndef _RESET_NOTIFICATION_BB_TEST_MAIN_
#define _RESET_NOTIFICATION_BB_TEST_MAIN_

#include <Efi.h>
#include <Library/EfiTestLib.h>
#include <SctLib.h>
#include <UEFI/Protocol/ResetNotification.h>
#include "Guid.h"

#include EFI_TEST_PROTOCOL_DEFINITION(TestRecoveryLibrary)
#include EFI_TEST_PROTOCOL_DEFINITION(TestLoggingLibrary)

#define EFI_RESET_NOTIFICATION_PROTOCOL_TEST_REVISION    0x00010000

#define TEST_VENDOR_GUID                         \
  { 0xF6FAB04F, 0xACAF, 0x4af3, { 0xB9, 0xFA, 0xDC, 0xF9, 0x7F, 0xB4, 0x42, 0x6F } }

#define MAX_BUFFER_SIZE    1024

//
// Entry GUIDs for Func Test
//
#define EFI_RESET_NOTIFICATION_PROTOCOL_TEST_ENTRY_GUID0101 \
{ 0x5b16218b, 0xfd90, 0x40f0, { 0x88, 0xfe, 0x4e, 0x9e, 0x44, 0xe1, 0x24, 0x74 } }

#define EFI_RESET_NOTIFICATION_PROTOCOL_TEST_ENTRY_GUID0102 \
{ 0xee5b57b0, 0xaad3, 0x49c7, { 0x96, 0xbf, 0x25, 0xdf, 0x42, 0x2f, 0x27, 0xa4 } }
//
// Entry GUIDs for Conf Test
//
#define EFI_RESET_NOTIFICATION_PROTOCOL_TEST_ENTRY_GUID0201 \
{ 0x91d30199, 0x63c9, 0x4d1e, { 0x93, 0x97, 0xd2, 0x29, 0x3, 0xce, 0x0, 0x69 } }

#define EFI_RESET_NOTIFICATION_PROTOCOL_TEST_ENTRY_GUID0202 \
{ 0x3b8f4c78, 0xab7a, 0x4d93, { 0x9c, 0x2, 0xa, 0x3f, 0x6e, 0x16, 0xd1, 0xd6 } }

extern EFI_GUID    gTestVendorGuid;
extern CHAR16      *VariableName;
extern UINT32      Attributes;

//
//
//
EFI_STATUS
InitializeResetNotificationBBTest (
  IN EFI_HANDLE                   ImageHandle,
  IN EFI_SYSTEM_TABLE             *SystemTable
  );

EFI_STATUS
UnloadResetNotificationBBTest (
  IN EFI_HANDLE                   ImageHandle
  );

//
//Test Cases
//
EFI_STATUS
BBTestRegisterResetNotifyConformanceTest (
  IN EFI_BB_TEST_PROTOCOL       *This,
  IN VOID                       *ClientInterface,
  IN EFI_TEST_LEVEL             TestLevel,
  IN EFI_HANDLE                 SupportHandle
  );

EFI_STATUS
BBTestUnregisterResetNotifyConformanceTest (
  IN EFI_BB_TEST_PROTOCOL       *This,
  IN VOID                       *ClientInterface,
  IN EFI_TEST_LEVEL             TestLevel,
  IN EFI_HANDLE                 SupportHandle
  );

EFI_STATUS
BBTestRegisterResetNotifyFunctionTest (
  IN EFI_BB_TEST_PROTOCOL       *This,
  IN VOID                       *ClientInterface,
  IN EFI_TEST_LEVEL             TestLevel,
  IN EFI_HANDLE                 SupportHandle
  );

EFI_STATUS
BBTestUnregisterResetNotifyFunctionTest (
  IN EFI_BB_TEST_PROTOCOL       *This,
  IN VOID                       *ClientInterface,
  IN EFI_TEST_LEVEL             TestLevel,
  IN EFI_HANDLE                 SupportHandle
  );

/**
 *  Support function - Get test support protocol library.
 *  @param SupportHandle  A handle containing support protocols.
 *  @param StandardLib    A pointer to Standard Test Support Protocol.
 *  @param RecoveryLib    A pointer to Test Recovery Support Protocol.
 *  @param LoggingLib     A pointer to Test Logging Support Protocol.
 *  @return EFI_SUCCESS   Successfully.
 *  @return Other value   Something failed.
 */
EFI_STATUS
GetTestSupportLibrary (
  IN EFI_HANDLE                           SupportHandle,
  OUT EFI_STANDARD_TEST_LIBRARY_PROTOCOL  **StandardLib,
  OUT EFI_TEST_RECOVERY_LIBRARY_PROTOCOL  **RecoveryLib,
  OUT EFI_TEST_LOGGING_LIBRARY_PROTOCOL   **LoggingLib
  );

VOID
EFIAPI
TestOnReset (
  IN EFI_RESET_TYPE           ResetType,
  IN EFI_STATUS               ResetStatus,
  IN UINTN                    DataSize,
  IN VOID                     *ResetData OPTIONAL
  );

#endif


text:
[
{"id":"layer_new","title":"Nova Camada"},
{"id":"layer_delete","title":"Deletar Camada"},
{"id":"layer_rename","title":"Renomear Camada"},
{"id":"layer_up","title":"Camada para Cima"},
{"id":"layer_down","title":"Camada para baixo"},
{"id":"tool_clear","title":"Nova Imagem"},
{"id":"tool_open","title":"Abrir Imagem"},
{"id":"tool_save","title":"Salvar Imagem"},
{"id":"tool_docprops","title":"Propriedades"},
{"id":"tool_source","title":"Código"},
{"id":"tool_undo","title":"Desfazer"},
{"id":"tool_redo","title":"Refazer"},
{"id":"tool_clone","title":"Duplicar Elemento"},
{"id":"tool_delete","title":"Excluir Elemento"},
{"id":"tool_move_top","title":"Mover para Cima"},
{"id":"tool_move_bottom","title":"Mover para Baixo"},
{"id":"group_opacity","title":"Mudar a opacidade"},
{"id":"angle","title":"Ângulo de rotação"},
{"id":"tool_clone_multi","title":"Duplicar Elementos"},
{"id":"tool_delete_multi","title":"Eliminar Elementos"},
{"id":"tool_alignleft","title":"Alinhar à Esquerda"},
{"id":"tool_aligncenter","title":"Alinhar ao centro"},
{"id":"tool_alignright","title":"Alinhar à Direita"},
{"id":"tool_aligntop","title":"Alinhar Acima"},
{"id":"tool_alignmiddle","title":"Alinhar no Méio"},
{"id":"tool_alignbottom","title":"Alinhar Abaixo"},
{"id":"align_relative_to","title":"Alinhar em relação a ..."},
{"id":"tool_group","title":"Agrupar"},
{"id":"tool_ungroup","title":"Desagrupar"},
{"id":"rect_width","title":"Alterar a largura retângulo"},
{"id":"rect_height","title":"Alterar altura do retângulo"},
{"id":"rect_rx","title":"Radio do chanfro"},
{"id":"image_width","title":"Alterar a largura da imagem"},
{"id":"image_height","title":"Alterar altura da imagem"},
{"id":"image_url","title":"Alterar caminho URL"},
{"id":"circle_cx","title":"Ponto horizontal do centro cx"},
{"id":"circle_cy","title":"Ponto Vertical do centro cy"},
{"id":"circle_r","title":"Alterar raio"},
{"id":"ellipse_cx","title":"Ponto horizontal do centro cx"},
{"id":"ellipse_cy","title":"Ponto Vertical do centro cy"},
{"id":"ellipse_rx","title":"Alterar raio horizontal"},
{"id":"ellipse_ry","title":"Alterar raio vertical"},
{"id":"line_x1","title":"Ponto horizontal do início da linha x1"},
{"id":"line_y1","title":"Ponto vertical do início da linha y1"},
{"id":"line_x2","title":"Ponto horizontal do fim da linha x2"},
{"id":"line_y2","title":"Ponto vertical do fim da linha y2"},
{"id":"tool_bold","title":"Negrito"},
{"id":"tool_italic","title":"Itálico"},
{"id":"font_family","title":"Fonte"},
{"id":"font_size","title":"Alterar tamanho da fonte"},
{"id":"text","title":"Alterar o conteúdo do texto"},
{"id":"tool_select","title":"Seleção"},
{"id":"tool_fhpath","title":"Lápis"},
{"id":"tool_line","title":"Linha"},
{"id":"tools_rect_show","title":"Quadrado / Retângulo"},
{"id":"tools_ellipse_show","title":"Elipse / Círculo"},
{"id":"tool_text","title":"Texto"},
{"id":"tool_path","title":"Área"},
{"id":"tool_image","title":"Imagem"},
{"id":"tool_zoom","title":"Zoom"},
{"id":"zoom","title":"Alterar o zoom"},
{"id":"fill_color","title":"Cor do preenchimento"},
{"id":"stroke_color","title":"Cor do contorno"},
{"id":"stroke_width","title":"Alterar a largura do contorno"},
{"id":"stroke_style","title":"Alterar o estilo do contorno"},
{"id":"palette","title":"Clique para mudar a cor do preenchimento, Shift + Clique para mudar a cor do contorno"},
{"id":"tool_square","title":"Quadrado"},
{"id":"tool_rect","title":"Retângulo"},
{"id":"tool_fhrect","title":"Retangulo à mão-livre"},
{"id":"tool_circle","title":"Circle"},
{"id":"tool_ellipse","title":"Elipse"},
{"id":"tool_fhellipse","title":"Elipse à mão-livre"},
{"id":"bkgnd_color","title":"Mudar a cor de fundo / opacidade"},
{"id":"rwidthLabel","textContent":"largura:"},
{"id":"rheightLabel","textContent":"altura:"},
{"id":"cornerRadiusLabel","textContent":"Raio:"},
{"id":"iwidthLabel","textContent":"largura:"},
{"id":"iheightLabel","textContent":"altura:"},
{"id":"svginfo_width","textContent":"Largura:"},
{"id":"svginfo_height","textContent":"Altura:"},
{"id":"angleLabel","textContent":"ângulo:"},
{"id":"relativeToLabel","textContent":"em relação ao:"},
{"id":"zoomLabel","textContent":"zoom:"},
{"id":"layersLabel","textContent":"Camadas:"},
{"id":"selectedPredefined","textContent":"Selecionar predefinidos:"},
{"id":"fitToContent","textContent":"Ajustar ao conteúdo"},
{"id":"tool_source_save","textContent":"Salvar"},
{"id":"tool_docprops_save","textContent":"Salvar"},
{"id":"tool_docprops_cancel","textContent":"Cancelar"},
{"id":"tool_source_cancel","textContent":"Cancelar"},
{"id":"fit_to_all","textContent":"Ajustar a todo o conteúdo"},
{"id":"fit_to_layer_content","textContent":"Ajustar ao conteúdo da camada"},
{"id":"fit_to_sel","textContent":"Ajustar à seleção"},
{"id":"fit_to_canvas","textContent":"Ajustar à tela"},
{"id":"selected_objects","textContent":"objetos selecionados"},
{"id":"largest_object","textContent":"maior objeto"},
{"id":"smallest_object","textContent":"menor objeto"},
{"id":"page","textContent":"Página"},
{"id":"fill_tool_bottom","textContent":"Preenchimento:"},
{"id":"stroke_tool_bottom","textContent":"Contorno:"},
{"id":"path_node_x","title":"Coordenada do ponto x"},
{"id":"path_node_y","title":"Coordenada do ponto y"},
{"id":"seg_type","title":"Mudar Tipo de segmento"},
{"id":"straight_segments","textContent":"Reta"},
{"id":"curve_segments","textContent":"Curva"},
{"id":"tool_node_clone","title":"Duplicar ponto"},
{"id":"tool_node_delete","title":"Deletar ponto"},
{"id":"selLayerLabel","textContent":"Mover elementos para:"},
{"id":"selLayerNames","title":"Mover elementos selecionados para outra camada"},
{"id":"sidepanel_handle","title":"Arraste para os lados para alterar a largura","textContent":"C a m a d a s"},
{"id":"tool_wireframe","title":"Modo Somente Contornos"},
{"id":"svginfo_image_props","textContent":"Propriedades da Imagem"},
{"id":"svginfo_title","textContent":"Título"},
{"id":"svginfo_dim","textContent":"Dimensões"},
{"id":"includedImages","textContent":"Imagens incluídas"},
{"id":"image_opt_embed","textContent":"Embutir dados (arquivos locais)"},
{"id":"image_opt_ref","textContent":"Usar referência a arquivo"},
{"id":"svginfo_editor_prefs","textContent":"Preferências"},
{"id":"svginfo_lang","textContent":"Idioma"},
{"id":"svginfo_change_background","textContent":"Mudar fundo"},
{"id":"svginfo_bg_note","textContent":"Aviso: Fundo não será salvo com a imagem."},
{"id":"svginfo_icons","textContent":"Tamanho do ícone"},
{"id":"icon_small","textContent":"Pequeno"},
{"id":"icon_medium","textContent":"Medio"},
{"id":"icon_large","textContent":"Grande"},
{"id":"icon_xlarge","textContent":"Extra"},
{"id":"selected_x","title":"Mudar coodenada x"},
{"id":"selected_y","title":"Mudar coodenada y"},
{"id":"tool_topath","title":"Mudar para Área"},
{"id":"tool_reorient","title":"Reorientar Área"},
{"id":"tool_node_link","title":"Alinhar ponto de controle da curva"},
{"js_strings": {
	"invalidAttrValGiven":"Valor inválido",
	"noContentToFitTo":"Sem conteúdo",
	'layer':"Camada",
	"dupeLayerName":"Já existe uma camada com esse nome",
	"enterUniqueLayerName":"Por favor, insira um nome único",
	"enterNewLayerName":"Por favor, insira o nome da nova camada",
	"layerHasThatName":"A camada já possui este nome",
	"QmoveElemsToLayer":"Mover os elementos selecionados para a camada: '%s'?",
	"QwantToClear":"Deseja apagar o desenho?\nIsso também vai limpar o histórico!",
	"QerrorsRevertToSource":"Foram encontrados erros no seu código SVG.\nVoltar para o código SVG original?",
	"QignoreSourceChanges":"Ignorar mudanças no código SVG?",
	"featNotSupported":"Recurso não suportado",
	"enterNewImgURL":"Insirao caminho URL da imagem",
	"ok":"Ok",
	"cancel":"Cancelar",
	"pathNodeTooltip":"Arraste o ponto para move-lo. \nDuplo-click para mudar o tipo de segmento (Reta / Curva)",
	"pathCtrlPtTooltip":"Arraste ponto de controle da curva para alterar suas propriedades",
	"key_up":"seta pra cima",
	"key_down":"seta pra baixo",
	"key_backspace":"backspace",
	"key_del":"delete"
	}
}
]


text:
HtmAdministration.config(function($stateProvider) {
  $stateProvider
    .state('administration', {
      abstract: true,
      url: '/administration',
      views: {
        '': {
            template: '<ui-view/>'
        },
        'navigation': {
          templateUrl: 'client/administration/navigation.ng.html',
          controller: 'CountsCtrl',
          controllerAs: 'counts'
        }
      }
    })

    .state('administration.participants', {
      url: '/participants',
      views: {
        '': {
          templateUrl: 'client/administration/participants.ng.html',
          controller: 'ParticipantsCtrl',
          controllerAs: 'participants'
        }
      },
      dsr: true,
      resolve: {
        tournamentId: function() { return false; }
      }
    })

    .state('administration.participants.import', {
      url: '/import',
      templateUrl: 'client/administration/participants-import.ng.html',
      controller: 'ParticipantsImportCtrl',
      controllerAs: 'importer',
    })

    .state('administration.participants.add', {
      url: '/add',
      templateUrl: 'client/administration/participants-edit.ng.html',
      controller: 'ParticipantEditCtrl',
      controllerAs: 'editor',
    })
    .state('administration.participants.edit', {
      url: '/edit/:participantId',
      views: {
       'edit': {
          templateUrl: 'client/administration/participants-edit.ng.html',
          controller: 'ParticipantEditCtrl',
          controllerAs: 'editor',
        }
      }
    })
    .state('administration.event', {
      url: '/event',
      views: {
        '': {
          templateUrl: 'client/administration/event.ng.html'
        }
      }
    })

    .state('administration.schedule', {
      url: '/schedule',
      views: {
        '': {
          templateUrl: 'client/administration/schedule.ng.html'
        },
        'navigation': {
          templateUrl: 'client/administration/navigation.ng.html'
        }
      }
    })

    .state('administration.tournaments', {
      url: '/tournaments',
      abstract: true,
      template: '<ui-view></ui-view>',
      controller: 'TournamentsCtrl',
      controllerAs: 'tournaments',
      resolve: {
        subscribe: function(waitForSubscription) {
          return waitForSubscription('tournaments');
        }
      }
    })
    .state('administration.tournaments.dashboard', {
      url: '',
      templateUrl: 'client/administration/tournaments-dashboard.ng.html'
    })
    .state('administration.tournaments.view', {
      url: '/:tournamentIdentifier',
      templateUrl: 'client/administration/tournaments-view.ng.html',
      controller: 'TournamentViewCtrl',
      controllerAs: 'tournament',
      resolve: {
        tournamentIdentifier: function($stateParams) {
          return $stateParams.tournamentIdentifier;
        }
      }
    })
    .state('administration.tournaments.view.phase', {
      url: '/:phaseIndex/:phaseType',
      templateUrl: function($stateParams) {
        return 'client/administration/phase-' + $stateParams.phaseType + '.ng.html';
      },
      controllerProvider: function($stateParams) {
        return $stateParams.phaseType.charAt(0).toUpperCase() + $stateParams.phaseType.substring(1) + 'PhaseCtrl';
      },
      controllerAs: 'phase',
      resolve: {
        phaseIndex: function($stateParams) {
          return +$stateParams.phaseIndex;
        }
      }
    });
});


text:
//======================================================================
//        Copyright (C) 2015-2020 Winddy He. All rights reserved
//        Email: hgplan@126.com
//======================================================================
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Knight.Hotfix.Core
{
    public static class HotfixReflectAssists
    {
        public static readonly BindingFlags flags_common            =   BindingFlags.Instance    |
                                                                        BindingFlags.SetField    | BindingFlags.GetField |
                                                                        BindingFlags.GetProperty | BindingFlags.SetProperty;

        public static readonly BindingFlags flags_public            =   flags_common | BindingFlags.Public;
        public static readonly BindingFlags flags_nonpublic         =   flags_common | BindingFlags.NonPublic;
        public static readonly BindingFlags flags_all               =   flags_common | BindingFlags.Public | BindingFlags.NonPublic;
        public static readonly BindingFlags flags_method            =   BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod;
        public static readonly BindingFlags flags_method_private    =   BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod;

        public static readonly Type[]       empty_types             =   new Type[0];

        public static object Construct(string rTypeName, params object[] param)
        {
            var rType = Type.GetType(rTypeName);
            var rParamType = new Type[param.Length];
            for (int nIndex = 0; nIndex < param.Length; ++nIndex)
                rParamType[nIndex] = param[nIndex].GetType();
            var rConstructor = rType.GetConstructor(rParamType);
            return rConstructor.Invoke(param);
        }

        public static object Construct(Type rType, params object[] param)
        {
            var rParamType = new Type[param.Length];
            for (int nIndex = 0; nIndex < param.Length; ++nIndex)
                rParamType[nIndex] = param[nIndex].GetType();
            var rConstructor = rType.GetConstructor(rParamType);
            return rConstructor.Invoke(param);
        }

        public static T Construct<T>(params object[] param)
        {
            return (T)Construct(typeof(T), param);
        }

        public static T TConstruct<T>(Type rType, params object[] param)
        {
            return (T)Construct(rType, param);
        }

        public static object GetAttrMember(object rObject, string rMemberName, BindingFlags rBindFlags)
        {
            if (rObject == null) return null;
            Type rType = rObject.GetType();
            return rType.InvokeMember(rMemberName, rBindFlags, null, rObject, new object[] { });
        }

        public static void SetAttrMember(object rObject, string rMemberName, BindingFlags rBindFlags, params object[] rParams)
        {
            if (rObject == null) return;
            Type rType = rObject.GetType();
            rType.InvokeMember(rMemberName, rBindFlags, null, rObject, rParams);
        }

        public static object MethodMember(object rObject, string rMemberName, BindingFlags rBindFlags, params object[] rParams)
        {
            if (rObject == null) return null;
            Type rType = rObject.GetType();
            var rMethodInfo = rType.GetMethod(rMemberName);
            return rMethodInfo.Invoke(rObject, rParams);
        }

        public static object TypeConvert(Type rType, string rValueStr)
        {
            return Convert.ChangeType(rValueStr, rType);
        }

        public static Type GetType(string rClassName)
        {
            return Type.GetType(rClassName);
        }
    }
}


text:
<?php
namespace Calina\Bundle\MainBundle\Observer;

use Calina\Bundle\MainBundle\Observer\AbstractObserver;

class LogObserver extends AbstractObserver
{
    private $webDir;

    public function update($patient) {
        $fullPath = $this->webDir . "/log.txt";
        file_put_contents ($fullPath, "Patient ssn was changed to " . $patient->getSsn() . "\n");
    }

    public function __construct() {
        global $kernel;

        if ('AppCache' == get_class($kernel)) {
            $kernel = $kernel->getKernel();
        };

        $this->webDir = $kernel->getRootDir() . '/../web';
    }
}


text:
.woocommerce table.form-table,
.woocommerce h1,
.woocommerce h2,
.woocommerce h3,
.woocommerce h4,
.woocommerce h5,
.woocommerce h6,
.woocommerce p {
    display: block;
    width: 75%;
    float: left;
}

.woorac_settings_tab_sidebar {
    display: block;
    width: 23%;
    margin-left: 2%;
    float: right;
}

#message p {
    display: block;
    width: 100%;
    float: none;
}

.woorac_settings_tab_sidebar_item {
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
}

.woorac_settings_tab_sidebar_item p {
    display: block;
    width: 100%;
    float: none;
}


text:
<!DOCTYPE html>

<meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="theme-color" content="#3F51B5">

    <meta name="keywords" content>

    <title>判断javascript加载完成的方法 | codante</title>
    <link type="text/css" rel="stylesheet" source="/blog/css/style.min.css?_v=77623b489ee77b522ff8437b98d73b89" media="all">

判断javascript加载完成的方法

function include_js(file) {
var _doc = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', file);
_doc.appendChild(js);
if (!/*@cc_on!@*/0) { //if not IE
    //Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload
    js.onload = function () {
        alert('Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload');
    }
} else {
    //IE6、IE7 support js.onreadystatechange
    js.onreadystatechange = function () {
        if (js.readyState == 'loaded' || js.readyState == 'complete') {
            alert('IE6、IE7 support js.onreadystatechange');
        }
    }
}
return false;
}
//execution function
include_js('http://www.planabc.net/wp-includes/js/jquery/jquery.js');

    最后更新于
    <time datetime="2020-04-27T06:18:05.676Z">2020.04.27 14:18:05</time>
 by Shinate

            前一篇

MPEG-2,MPEG-4,H.264 编码标准的区别

            后一篇

判断 iframe 是否加载完成的完美方法

cosh-1.0.0$

<input type="text" class="inputing">


text:
namespace Kachuwa.IdentityServerAdmin.ViewModel
{
    public class ListApiResourceScopeViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public string Description { get; set; }

        public bool Required { get; set; }

        public bool Emphasize { get; set; }

        public bool ShowInDiscoveryDocument { get; set; } = true;

        public string UserClaims { get; set; }
    }

}


text:
<?php
namespace Codeception\Command;

use Codeception\Codecept;
use Codeception\Configuration;
use Codeception\Exception\Configuration as ConfigurationException;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

class GenerateScenarios extends Base
{
    protected function configure()
    {
        $this->setDefinition(array(
            new InputArgument('suite', InputArgument::REQUIRED, 'suite from which texts should be generated'),
            new InputOption('config', 'c', InputOption::VALUE_REQUIRED, 'Use specified config instead of default'),
            new InputOption('path', 'p', InputOption::VALUE_REQUIRED, 'Use specified path as destination instead of default'),
            new InputOption('single-file', '', InputOption::VALUE_NONE, 'Render all scenarios to only one file'),
            new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Specify output format: html or text (default)','text'),
            new InputOption('config', 'c', InputOption::VALUE_REQUIRED, 'Use specified config instead of default'),
        ));
        parent::configure();
    }

    public function getDescription()
    {
        return 'Generates text representation for all scenarios';
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $suite = $input->getArgument('suite');

        $suiteconf = $this->getSuiteConfig($suite, $input->getOption('config'));

        $path = $input->getOption('path')
            ? $input->getOption('path')
            : Configuration::dataDir() . 'scenarios';

        $format = $input->getOption('format');

        @mkdir($path);

        if (!is_writable($path)) {
            throw new ConfigurationException("Path $path is not writable. Please, set valid permissions for folder to store scenarios.");
        }

        $path = $path . DIRECTORY_SEPARATOR . $suite;
        if (!$input->getOption('single-file')) @mkdir($path);

        $suiteManager = new \Codeception\SuiteManager(new EventDispatcher(), $suite, $suiteconf);

        if ($suiteconf['bootstrap']) {
            if (file_exists($suiteconf['path'] . $suiteconf['bootstrap'])) {
                require_once $suiteconf['path'] . $suiteconf['bootstrap'];
            }
        }

        $tests = $this->getTests($suiteManager);
        $scenarios = "";

        foreach ($tests as $test) {
            if (!($test instanceof \Codeception\TestCase\Cept)) continue;
            $feature = $test->getScenarioText($format);

            $name = $test instanceof \Codeception\TestCase\Cest
                ? $this->underscore($test->getFileName())
                : $this->underscore(substr($test->getFileName(), 0, -8));

            if ($input->getOption('single-file')) {
                $scenarios .= $feature;
                $output->writeln("* $name rendered");
            } else {
                $feature = $this->decorate($feature, $format);
                $this->save($path . DIRECTORY_SEPARATOR . $name . $this->formatExtension($format), $feature);
                $output->writeln("* $name generated");
            }
        }

        if ($input->getOption('single-file')) {
            $this->save($path . $this->formatExtension($format), $this->decorate($scenarios, $format) . PHP_EOL);
        }
    }

    protected function decorate($text, $format)
    {
        switch ($format) {
            case 'text': return $text;
            case 'html': return "$text";
        }
    }

    protected function getTests($suiteManager)
    {
        $suiteManager->loadTests();
        return $suiteManager->getSuite()->tests();
    }

    protected function formatExtension($format)
    {
        switch ($format) {
            case 'text': return '.txt';
            case 'html': return '.html';
        }
    }

    private function underscore($name)
    {
        $name = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\\1_\\2', $name);
        $name = preg_replace('/([a-z\d])([A-Z])/', '\\1_\\2', $name);
        $name = str_replace(array('/','\\'),array('.','.'), $name);
        return $name;
    }

}


text:
var sys = require('sys')
var content = "Fastest Node I can do";
var headers = {'Content-Type' : 'text/plain'};

http = require('http');

http.createServer(function(req, res){
  res.sendHeader(200, headers);
  res.sendBody(content);
  res.finish();
}).listen(8000);

sys.puts("Server running at http://127.0.0.1:8000")


text:
/**
 * Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.tests.constraints.validatorresolution;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.io.Serializable;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

/**
 * A test constraint which can lead to a error when trying to resolve the validator.
 *
 * @author Hardy Ferentschik
 */
@Constraint(validatedBy = {
		Ambiguous.AmbiguousValidatorForDummy.class, Ambiguous.AmbiguousValidatorForSerializable.class
})
@Documented
@Target({ METHOD, FIELD, TYPE })
@Retention(RUNTIME)
public @interface Ambiguous {
	public abstract String message() default "foobar";

	public abstract Class<?>[] groups() default { };

	public abstract Class<? extends Payload>[] payload() default { };

	public class AmbiguousValidatorForDummy implements ConstraintValidator<Ambiguous, Dummy> {

		@Override
		public boolean isValid(Dummy d, ConstraintValidatorContext constraintValidatorContext) {
			return true;
		}
	}

	public class AmbiguousValidatorForSerializable implements ConstraintValidator<Ambiguous, Serializable> {

		@Override
		public boolean isValid(Serializable o, ConstraintValidatorContext constraintValidatorContext) {
			return true;
		}
	}
}


text:
@interface OCTools : NSObject

@end


text:
<lint>
    <issue id="AllowBackup" severity="ignore" />
    <issue id="IconLauncherShape" severity="ignore" />
    <issue id="IconMissingDensityFolder" severity="ignore" />
    <issue id="GoogleAppIndexingWarning" severity="ignore" />
    <issue id="TrulyRandom" severity="ignore" />
    <issue id="InvalidPackage" severity="ignore" />
</lint>


text:
#ifndef INCLUDED_AERON_CONCURRENT_LOGBUFFER_LOG_BUFFER__
#define INCLUDED_AERON_CONCURRENT_LOGBUFFER_LOG_BUFFER__

#include <util/Index.h>
#include <concurrent/AtomicBuffer.h>
#include "LogBufferDescriptor.h"

namespace aeron { namespace common { namespace concurrent { namespace logbuffer {

class LogBuffer
{
public:

    inline AtomicBuffer& logBuffer() const
    {
        return m_logBuffer;
    }

    inline AtomicBuffer& stateBuffer() const
    {
        return m_stateBuffer;
    }

    inline util::index_t capacity() const
    {
        return m_capacity;
    }

    inline void clean()
    {
        m_logBuffer.setMemory(0, m_logBuffer.getCapacity(), 0);
        m_stateBuffer.setMemory(0, m_stateBuffer.getCapacity(), 0);
        statusOrdered(LogBufferDescriptor::CLEAN);
    }

    inline int status() const
    {
        return m_stateBuffer.getInt32Ordered(LogBufferDescriptor::STATUS_OFFSET);
    }

    inline bool compareAndSetStatus(std::int32_t expectedStatus, std::int32_t updateStatus)
    {
        return m_stateBuffer.compareAndSetInt32(LogBufferDescriptor::STATUS_OFFSET, expectedStatus, updateStatus);
    }

    inline void statusOrdered(std::int32_t status)
    {
        m_stateBuffer.putInt32Ordered(LogBufferDescriptor::STATUS_OFFSET, status);
    }

    inline std::int32_t tailVolatile()
    {
        return std::min(m_stateBuffer.getInt32Ordered(LogBufferDescriptor::TAIL_COUNTER_OFFSET), m_capacity);
    }

    inline std::int32_t highWaterMarkVolatile()
    {
        return m_stateBuffer.getInt32Ordered(LogBufferDescriptor::HIGH_WATER_MARK_OFFSET);
    }

    inline std::int32_t tail()
    {
        return m_stateBuffer.getInt32(LogBufferDescriptor::TAIL_COUNTER_OFFSET);
    }

    inline std::int32_t highWaterMark()
    {
        return m_stateBuffer.getInt32(LogBufferDescriptor::HIGH_WATER_MARK_OFFSET);
    }

protected:
    inline LogBuffer(AtomicBuffer& logBuffer, AtomicBuffer& stateBuffer)
    : m_logBuffer(logBuffer), m_stateBuffer(stateBuffer)
    {
        LogBufferDescriptor::checkLogBuffer(logBuffer);
        LogBufferDescriptor::checkStateBuffer(stateBuffer);

        m_capacity = logBuffer.getCapacity();
    }

private:
    AtomicBuffer& m_logBuffer;
    AtomicBuffer& m_stateBuffer;
    util::index_t m_capacity;
};

}}}}

#endif


text:
package plugin

import (
	"encoding/json"

	"github.com/mcilloni/go-openbaton/util"
	log "github.com/sirupsen/logrus"
	"github.com/streadway/amqp"
)

func (p *plug) spawnWorkers() {
	tag := util.FuncName()

	p.l.WithFields(log.Fields{
		"tag":            tag,
		"num-of-workers": p.params.Workers,
	}).Debug("spawning workers")

	p.wg.Add(p.params.Workers)
	for i := 0; i < p.params.Workers; i++ {
		go p.worker(i)
	}
}

func (p *plug) temporaryQueue() (string, error) {
	queue, err := p.cnl.QueueDeclare(
		"",    // name
		false, // durable
		false, // delete when usused
		true,  // exclusive
		false, // noWait
		nil,   // arguments
	)
	if err != nil {
		return "", err
	}

	return queue.Name, nil
}

func (p *plug) worker(id int) {
	tag := util.FuncName()

	p.l.WithFields(log.Fields{
		"tag":       tag,
		"worker-id": id,
	}).Debug("worker is starting")

	for req := range p.reqChan {
		result, err := p.rh.Handle(req.MethodName, req.Parameters)

		var resp response
		if err != nil {
			// The NFVO expects a Java Exception;
			// This type switch checks if the error is not one of the special
			// Java-compatible types already and wraps it.
			switch err.(type) {
			case plugError:
				resp.Exception = err

			case DriverError:
				resp.Exception = err

			// if the error is not a special plugin error, than wrap it:
			// the nfvo expects a Java exception.
			default:
				resp.Exception = plugError{err.Error()}
			}
		} else {
			resp.Answer = result
		}

		bResp, err := json.MarshalIndent(resp, "", "  ")
		if err != nil {
			p.l.WithError(err).WithFields(log.Fields{
				"tag":       tag,
				"worker-id": id,
			}).Error("failure while serialising response")
			continue
		}

		err = p.cnl.Publish(
			pluginExchange,
			req.ReplyTo,
			false,
			false,
			amqp.Publishing{
				ContentType:   "text/plain",
				CorrelationId: req.CorrID,
				Body:          bResp,
			},
		)

		if err != nil {
			p.l.WithError(err).WithFields(log.Fields{
				"tag":          tag,
				"worker-id":    id,
				"reply-queue":  req.ReplyTo,
				"reply-corrid": req.CorrID,
			}).Error("failure while replying")
			continue
		}

		p.l.WithError(resp.Exception).WithFields(log.Fields{
			"tag":          tag,
			"worker-id":    id,
			"reply-queue":  req.ReplyTo,
			"reply-corrid": req.CorrID,
		}).Info("response sent")

		// IMPORTANT: Acknowledge the received delivery!
		// The VimDriverCaller executor thread of the NFVO
		// will perpetually sleep when trying to publish the
		// next request if this step is omitted.
		if err := p.cnl.Ack(req.DeliveryTag, false); err != nil {
			p.l.WithError(err).WithFields(log.Fields{
				"tag":                tag,
				"worker-id":          id,
				"reply-queue":        req.ReplyTo,
				"reply-corrid":       req.CorrID,
				"reply-delivery_tag": req.DeliveryTag,
			}).Error("failure while acknowledging the last delivery")
			continue
		}
	}

	p.l.WithFields(log.Fields{
		"tag":       tag,
		"worker-id": id,
	}).Debug("worker is stopping")

	p.wg.Done()
}


text:
package docker

import (
	"fmt"
	"github.com/dotcloud/docker/runconfig"
	"io"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"testing"
	"time"
)

func TestKillDifferentUser(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)

	container, _, err := daemon.Create(&runconfig.Config{
		Image:     GetTestImage(daemon).ID,
		Cmd:       []string{"cat"},
		OpenStdin: true,
		User:      "daemon",
	},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)
	// FIXME @shykes: this seems redundant, but is very old, I'm leaving it in case
	// there is a side effect I'm not seeing.
	// defer container.stdin.Close()

	if container.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}
	if err := container.Start(); err != nil {
		t.Fatal(err)
	}

	setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
		for !container.State.IsRunning() {
			time.Sleep(10 * time.Millisecond)
		}
	})

	setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
		out, _ := container.StdoutPipe()
		in, _ := container.StdinPipe()
		if err := assertPipe("hello\n", "hello", out, in, 150); err != nil {
			t.Fatal(err)
		}
	})

	if err := container.Kill(); err != nil {
		t.Fatal(err)
	}

	if container.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}
	container.Wait()
	if container.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}
	// Try stopping twice
	if err := container.Kill(); err != nil {
		t.Fatal(err)
	}
}

func TestRestart(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)
	container, _, err := daemon.Create(&runconfig.Config{
		Image: GetTestImage(daemon).ID,
		Cmd:   []string{"echo", "-n", "foobar"},
	},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)
	output, err := container.Output()
	if err != nil {
		t.Fatal(err)
	}
	if string(output) != "foobar" {
		t.Error(string(output))
	}

	// Run the container again and check the output
	output, err = container.Output()
	if err != nil {
		t.Fatal(err)
	}
	if string(output) != "foobar" {
		t.Error(string(output))
	}
}

func TestRestartStdin(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)
	container, _, err := daemon.Create(&runconfig.Config{
		Image: GetTestImage(daemon).ID,
		Cmd:   []string{"cat"},

		OpenStdin: true,
	},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)

	stdin, err := container.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	stdout, err := container.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := container.Start(); err != nil {
		t.Fatal(err)
	}
	if _, err := io.WriteString(stdin, "hello world"); err != nil {
		t.Fatal(err)
	}
	if err := stdin.Close(); err != nil {
		t.Fatal(err)
	}
	container.Wait()
	output, err := ioutil.ReadAll(stdout)
	if err != nil {
		t.Fatal(err)
	}
	if err := stdout.Close(); err != nil {
		t.Fatal(err)
	}
	if string(output) != "hello world" {
		t.Fatalf("Unexpected output. Expected %s, received: %s", "hello world", string(output))
	}

	// Restart and try again
	stdin, err = container.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	stdout, err = container.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := container.Start(); err != nil {
		t.Fatal(err)
	}
	if _, err := io.WriteString(stdin, "hello world #2"); err != nil {
		t.Fatal(err)
	}
	if err := stdin.Close(); err != nil {
		t.Fatal(err)
	}
	container.Wait()
	output, err = ioutil.ReadAll(stdout)
	if err != nil {
		t.Fatal(err)
	}
	if err := stdout.Close(); err != nil {
		t.Fatal(err)
	}
	if string(output) != "hello world #2" {
		t.Fatalf("Unexpected output. Expected %s, received: %s", "hello world #2", string(output))
	}
}

func TestStdin(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)
	container, _, err := daemon.Create(&runconfig.Config{
		Image: GetTestImage(daemon).ID,
		Cmd:   []string{"cat"},

		OpenStdin: true,
	},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)

	stdin, err := container.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	stdout, err := container.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := container.Start(); err != nil {
		t.Fatal(err)
	}
	defer stdin.Close()
	defer stdout.Close()
	if _, err := io.WriteString(stdin, "hello world"); err != nil {
		t.Fatal(err)
	}
	if err := stdin.Close(); err != nil {
		t.Fatal(err)
	}
	container.Wait()
	output, err := ioutil.ReadAll(stdout)
	if err != nil {
		t.Fatal(err)
	}
	if string(output) != "hello world" {
		t.Fatalf("Unexpected output. Expected %s, received: %s", "hello world", string(output))
	}
}

func TestTty(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)
	container, _, err := daemon.Create(&runconfig.Config{
		Image: GetTestImage(daemon).ID,
		Cmd:   []string{"cat"},

		OpenStdin: true,
	},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)

	stdin, err := container.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	stdout, err := container.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := container.Start(); err != nil {
		t.Fatal(err)
	}
	defer stdin.Close()
	defer stdout.Close()
	if _, err := io.WriteString(stdin, "hello world"); err != nil {
		t.Fatal(err)
	}
	if err := stdin.Close(); err != nil {
		t.Fatal(err)
	}
	container.Wait()
	output, err := ioutil.ReadAll(stdout)
	if err != nil {
		t.Fatal(err)
	}
	if string(output) != "hello world" {
		t.Fatalf("Unexpected output. Expected %s, received: %s", "hello world", string(output))
	}
}

func TestEntrypoint(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)
	container, _, err := daemon.Create(
		&runconfig.Config{
			Image:      GetTestImage(daemon).ID,
			Entrypoint: []string{"/bin/echo"},
			Cmd:        []string{"-n", "foobar"},
		},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)
	output, err := container.Output()
	if err != nil {
		t.Fatal(err)
	}
	if string(output) != "foobar" {
		t.Error(string(output))
	}
}

func TestEntrypointNoCmd(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)
	container, _, err := daemon.Create(
		&runconfig.Config{
			Image:      GetTestImage(daemon).ID,
			Entrypoint: []string{"/bin/echo", "foobar"},
		},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)
	output, err := container.Output()
	if err != nil {
		t.Fatal(err)
	}
	if strings.Trim(string(output), "\r\n") != "foobar" {
		t.Error(string(output))
	}
}

func BenchmarkRunSequential(b *testing.B) {
	daemon := mkDaemon(b)
	defer nuke(daemon)
	for i := 0; i < b.N; i++ {
		container, _, err := daemon.Create(&runconfig.Config{
			Image: GetTestImage(daemon).ID,
			Cmd:   []string{"echo", "-n", "foo"},
		},
			"",
		)
		if err != nil {
			b.Fatal(err)
		}
		defer daemon.Destroy(container)
		output, err := container.Output()
		if err != nil {
			b.Fatal(err)
		}
		if string(output) != "foo" {
			b.Fatalf("Unexpected output: %s", output)
		}
		if err := daemon.Destroy(container); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkRunParallel(b *testing.B) {
	daemon := mkDaemon(b)
	defer nuke(daemon)

	var tasks []chan error

	for i := 0; i < b.N; i++ {
		complete := make(chan error)
		tasks = append(tasks, complete)
		go func(i int, complete chan error) {
			container, _, err := daemon.Create(&runconfig.Config{
				Image: GetTestImage(daemon).ID,
				Cmd:   []string{"echo", "-n", "foo"},
			},
				"",
			)
			if err != nil {
				complete <- err
				return
			}
			defer daemon.Destroy(container)
			if err := container.Start(); err != nil {
				complete <- err
				return
			}
			if err := container.WaitTimeout(15 * time.Second); err != nil {
				complete <- err
				return
			}
			// if string(output) != "foo" {
			// 	complete <- fmt.Errorf("Unexecpted output: %v", string(output))
			// }
			if err := daemon.Destroy(container); err != nil {
				complete <- err
				return
			}
			complete <- nil
		}(i, complete)
	}
	var errors []error
	for _, task := range tasks {
		err := <-task
		if err != nil {
			errors = append(errors, err)
		}
	}
	if len(errors) > 0 {
		b.Fatal(errors)
	}
}

func tempDir(t *testing.T) string {
	tmpDir, err := ioutil.TempDir("", "docker-test-container")
	if err != nil {
		t.Fatal(err)
	}
	return tmpDir
}

// Test for #1737
func TestCopyVolumeUidGid(t *testing.T) {
	eng := NewTestEngine(t)
	r := mkDaemonFromEngine(eng, t)
	defer r.Nuke()

	// Add directory not owned by root
	container1, _, _ := mkContainer(r, []string{"_", "/bin/sh", "-c", "mkdir -p /hello && touch /hello/test.txt && chown daemon.daemon /hello"}, t)
	defer r.Destroy(container1)

	if container1.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}
	if err := container1.Run(); err != nil {
		t.Fatal(err)
	}
	if container1.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}

	img, err := r.Commit(container1, "", "", "unit test commited image", "", nil)
	if err != nil {
		t.Error(err)
	}

	// Test that the uid and gid is copied from the image to the volume
	tmpDir1 := tempDir(t)
	defer os.RemoveAll(tmpDir1)
	stdout1, _ := runContainer(eng, r, []string{"-v", "/hello", img.ID, "stat", "-c", "%U %G", "/hello"}, t)
	if !strings.Contains(stdout1, "daemon daemon") {
		t.Fatal("Container failed to transfer uid and gid to volume")
	}
}

// Test for #1582
func TestCopyVolumeContent(t *testing.T) {
	eng := NewTestEngine(t)
	r := mkDaemonFromEngine(eng, t)
	defer r.Nuke()

	// Put some content in a directory of a container and commit it
	container1, _, _ := mkContainer(r, []string{"_", "/bin/sh", "-c", "mkdir -p /hello/local && echo hello > /hello/local/world"}, t)
	defer r.Destroy(container1)

	if container1.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}
	if err := container1.Run(); err != nil {
		t.Fatal(err)
	}
	if container1.State.IsRunning() {
		t.Errorf("Container shouldn't be running")
	}

	img, err := r.Commit(container1, "", "", "unit test commited image", "", nil)
	if err != nil {
		t.Error(err)
	}

	// Test that the content is copied from the image to the volume
	tmpDir1 := tempDir(t)
	defer os.RemoveAll(tmpDir1)
	stdout1, _ := runContainer(eng, r, []string{"-v", "/hello", img.ID, "find", "/hello"}, t)
	if !(strings.Contains(stdout1, "/hello/local/world") && strings.Contains(stdout1, "/hello/local")) {
		t.Fatal("Container failed to transfer content to volume")
	}
}

func TestBindMounts(t *testing.T) {
	eng := NewTestEngine(t)
	r := mkDaemonFromEngine(eng, t)
	defer r.Nuke()

	tmpDir := tempDir(t)
	defer os.RemoveAll(tmpDir)
	writeFile(path.Join(tmpDir, "touch-me"), "", t)

	// Test reading from a read-only bind mount
	stdout, _ := runContainer(eng, r, []string{"-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "_", "ls", "/tmp"}, t)
	if !strings.Contains(stdout, "touch-me") {
		t.Fatal("Container failed to read from bind mount")
	}

	// test writing to bind mount
	runContainer(eng, r, []string{"-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "_", "touch", "/tmp/holla"}, t)
	readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist

	// test mounting to an illegal destination directory
	if _, err := runContainer(eng, r, []string{"-v", fmt.Sprintf("%s:.", tmpDir), "_", "ls", "."}, nil); err == nil {
		t.Fatal("Container bind mounted illegal directory")
	}

	// test mount a file
	runContainer(eng, r, []string{"-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "_", "sh", "-c", "echo -n 'yotta' > /tmp/holla"}, t)
	content := readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
	if content != "yotta" {
		t.Fatal("Container failed to write to bind mount file")
	}
}

// Test that restarting a container with a volume does not create a new volume on restart. Regression test for #819.
func TestRestartWithVolumes(t *testing.T) {
	daemon := mkDaemon(t)
	defer nuke(daemon)

	container, _, err := daemon.Create(&runconfig.Config{
		Image:   GetTestImage(daemon).ID,
		Cmd:     []string{"echo", "-n", "foobar"},
		Volumes: map[string]struct{}{"/test": {}},
	},
		"",
	)
	if err != nil {
		t.Fatal(err)
	}
	defer daemon.Destroy(container)

	for key := range container.Config.Volumes {
		if key != "/test" {
			t.Fail()
		}
	}

	_, err = container.Output()
	if err != nil {
		t.Fatal(err)
	}

	expected := container.Volumes["/test"]
	if expected == "" {
		t.Fail()
	}
	// Run the container again to verify the volume path persists
	_, err = container.Output()
	if err != nil {
		t.Fatal(err)
	}

	actual := container.Volumes["/test"]
	if expected != actual {
		t.Fatalf("Expected volume path: %s Actual path: %s", expected, actual)
	}
}


text:
package org.zstack.header.image;

import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.rest.RestRequest;

import java.util.Collections;
import java.util.List;

/**
 * Created by frank on 11/15/2015.
 */
@Action(category = ImageConstant.ACTION_CATEGORY)
@RestRequest(
        path = "/images/{uuid}/actions",
        method = HttpMethod.PUT,
        responseClass = APIRecoverImageEvent.class,
        parameterName = "params",
        isAction = true
)
public class APIRecoverImageMsg extends APIMessage implements ImageMessage {
    @APIParam(resourceType = ImageVO.class, checkAccount = true, operationTarget = true)
    private String imageUuid;
    private List<String> backupStorageUuids;

    @Override
    public String getImageUuid() {
        return imageUuid;
    }

    public void setImageUuid(String imageUuid) {
        this.imageUuid = imageUuid;
    }

    public List<String> getBackupStorageUuids() {
        return backupStorageUuids;
    }

    public void setBackupStorageUuids(List<String> backupStorageUuids) {
        this.backupStorageUuids = backupStorageUuids;
    }

    public static APIRecoverImageMsg __example__() {
        APIRecoverImageMsg msg = new APIRecoverImageMsg();

        msg.setBackupStorageUuids(Collections.singletonList(uuid()));
        msg.setImageUuid(uuid());

        return msg;
    }

}


text:
<?php

class BlogAdminSidebar extends FieldGroup {
	/**
	 * @return bool
	 */
	public function isOpen() {
		$sidebar = Cookie::get('blog-admin-sidebar');

		if($sidebar == 1 || is_null($sidebar)) {
			return true;
		}

		return false;
	}
}


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

using ZXing.Common;
using ZXing.Multi;
using ZXing.Multi.QrCode;

namespace ZXing
{
   /// <summary>
   /// A smart class to decode the barcode inside a bitmap object
   /// </summary>
   public class BarcodeReaderGeneric<T> : IBarcodeReaderGeneric<T>, IMultipleBarcodeReaderGeneric<T>
   {
      private static readonly Func<LuminanceSource, Binarizer> defaultCreateBinarizer =
         (luminanceSource) => new HybridBinarizer(luminanceSource);

      protected static readonly Func<byte[], int, int, RGBLuminanceSource.BitmapFormat, LuminanceSource> defaultCreateRGBLuminanceSource =
         (rawBytes, width, height, format) => new RGBLuminanceSource(rawBytes, width, height, format);

      private Reader reader;
      private readonly Func<byte[], int, int, RGBLuminanceSource.BitmapFormat, LuminanceSource> createRGBLuminanceSource;
#if !UNITY
      private readonly Func<T, LuminanceSource> createLuminanceSource;
#else
      private readonly Func<T, int, int, LuminanceSource> createLuminanceSource;
#endif
      private readonly Func<LuminanceSource, Binarizer> createBinarizer;
      private bool usePreviousState;
      private DecodingOptions options;

      /// <summary>
      /// Gets or sets the options.
      /// </summary>
      /// <value>
      /// The options.
      /// </value>
      public DecodingOptions Options
      {
         get { return options ?? (options = new DecodingOptions()); }
         set { options = value; }
      }

      /// <summary>
      /// Gets the reader which should be used to find and decode the barcode.
      /// </summary>
      /// <value>
      /// The reader.
      /// </value>
      protected Reader Reader
      {
         get
         {
            return reader ?? (reader = new MultiFormatReader());
         }
      }

      /// <summary>
      /// Gets or sets a method which is called if an important point is found
      /// </summary>
      /// <value>
      /// The result point callback.
      /// </value>
      public event Action<ResultPoint> ResultPointFound
      {
         add
         {
            if (!Options.Hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
            {
               var callback = new ResultPointCallback(OnResultPointFound);
               Options.Hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK] = callback;
            }
            explicitResultPointFound += value;
            usePreviousState = false;
         }
         remove
         {
            explicitResultPointFound -= value;
            if (explicitResultPointFound == null)
               Options.Hints.Remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
            usePreviousState = false;
         }
      }

      private event Action<ResultPoint> explicitResultPointFound;

      /// <summary>
      /// event is executed if a result was found via decode
      /// </summary>
      public event Action<Result> ResultFound;

      /// <summary>
      /// Gets or sets a flag which cause a deeper look into the bitmap
      /// </summary>
      /// <value>
      ///   <c>true</c> if [try harder]; otherwise, <c>false</c>.
      /// </value>
      [Obsolete("Please use the Options.TryHarder property instead.")]
      public bool TryHarder
      {
         get { return Options.TryHarder; }
         set { Options.TryHarder = value; }
      }

      /// <summary>
      /// Image is a pure monochrome image of a barcode.
      /// </summary>
      /// <value>
      ///   <c>true</c> if monochrome image of a barcode; otherwise, <c>false</c>.
      /// </value>
      [Obsolete("Please use the Options.PureBarcode property instead.")]
      public bool PureBarcode
      {
         get { return Options.PureBarcode; }
         set { Options.PureBarcode = value; }
      }

      /// <summary>
      /// Specifies what character encoding to use when decoding, where applicable (type String)
      /// </summary>
      /// <value>
      /// The character set.
      /// </value>
      [Obsolete("Please use the Options.CharacterSet property instead.")]
      public string CharacterSet
      {
         get { return Options.CharacterSet; }
         set { Options.CharacterSet = value; }
      }

      /// <summary>
      /// Image is known to be of one of a few possible formats.
      /// Maps to a {@link java.util.List} of {@link BarcodeFormat}s.
      /// </summary>
      /// <value>
      /// The possible formats.
      /// </value>
      [Obsolete("Please use the Options.PossibleFormats property instead.")]
      public IList<BarcodeFormat> PossibleFormats
      {
         get { return Options.PossibleFormats; }
         set { Options.PossibleFormats = value; }
      }

      /// <summary>
      /// Gets or sets a value indicating whether the image should be automatically rotated.
      /// Rotation is supported for 90, 180 and 270 degrees
      /// </summary>
      /// <value>
      ///   <c>true</c> if image should be rotated; otherwise, <c>false</c>.
      /// </value>
      public bool AutoRotate { get; set; }

      /// <summary>
      /// Gets or sets a value indicating whether the image should be automatically inverted
      /// if no result is found in the original image.
      /// ATTENTION: Please be carefully because it slows down the decoding process if it is used
      /// </summary>
      /// <value>
      ///   <c>true</c> if image should be inverted; otherwise, <c>false</c>.
      /// </value>
      public bool TryInverted { get; set; }

#if !UNITY
      /// <summary>
      /// Optional: Gets or sets the function to create a luminance source object for a bitmap.
      /// If null a platform specific default LuminanceSource is used
      /// </summary>
      /// <value>
      /// The function to create a luminance source object.
      /// </value>
      protected Func<T, LuminanceSource> CreateLuminanceSource
#else
      /// <summary>
      /// Optional: Gets or sets the function to create a luminance source object for a bitmap.
      /// If null a platform specific default LuminanceSource is used
      /// </summary>
      /// <value>
      /// The function to create a luminance source object.
      /// </value>
      protected Func<T, int, int, LuminanceSource> CreateLuminanceSource
#endif
      {
         get
         {
            return createLuminanceSource;
         }
      }

      /// <summary>
      /// Optional: Gets or sets the function to create a binarizer object for a luminance source.
      /// If null then HybridBinarizer is used
      /// </summary>
      /// <value>
      /// The function to create a binarizer object.
      /// </value>
      protected Func<LuminanceSource, Binarizer> CreateBinarizer
      {
         get
         {
            return createBinarizer ?? defaultCreateBinarizer;
         }
      }

      /// <summary>
      /// Initializes a new instance of the <see cref="BarcodeReaderGeneric{T}"/> class.
      /// </summary>
      public BarcodeReaderGeneric()
         : this(new MultiFormatReader(), null, defaultCreateBinarizer)
      {
      }

      /// <summary>
      /// Initializes a new instance of the <see cref="BarcodeReaderGeneric{T}"/> class.
      /// </summary>
      /// <param name="reader">Sets the reader which should be used to find and decode the barcode.
      /// If null then MultiFormatReader is used</param>
      /// <param name="createLuminanceSource">Sets the function to create a luminance source object for a bitmap.
      /// If null, an exception is thrown when Decode is called</param>
      /// <param name="createBinarizer">Sets the function to create a binarizer object for a luminance source.
      /// If null then HybridBinarizer is used</param>
      public BarcodeReaderGeneric(Reader reader,
#if !UNITY
         Func<T, LuminanceSource> createLuminanceSource,
#else
         Func<T, int, int, LuminanceSource> createLuminanceSource,
#endif
         Func<LuminanceSource, Binarizer> createBinarizer
         )
         : this(reader, createLuminanceSource, createBinarizer, null)
      {
      }

      /// <summary>
      /// Initializes a new instance of the <see cref="BarcodeReaderGeneric{T}"/> class.
      /// </summary>
      /// <param name="reader">Sets the reader which should be used to find and decode the barcode.
      /// If null then MultiFormatReader is used</param>
      /// <param name="createLuminanceSource">Sets the function to create a luminance source object for a bitmap.
      /// If null, an exception is thrown when Decode is called</param>
      /// <param name="createBinarizer">Sets the function to create a binarizer object for a luminance source.
      /// If null then HybridBinarizer is used</param>
      /// <param name="createRGBLuminanceSource">Sets the function to create a luminance source object for a rgb array.
      /// If null the RGBLuminanceSource is used. The handler is only called when Decode with a byte[] array is called.</param>
      public BarcodeReaderGeneric(Reader reader,
#if !UNITY
         Func<T, LuminanceSource> createLuminanceSource,
#else
         Func<T, int, int, LuminanceSource> createLuminanceSource,
#endif
         Func<LuminanceSource, Binarizer> createBinarizer,
         Func<byte[], int, int, RGBLuminanceSource.BitmapFormat, LuminanceSource> createRGBLuminanceSource
         )
      {
         this.reader = reader ?? new MultiFormatReader();
         this.createLuminanceSource = createLuminanceSource;
         this.createBinarizer = createBinarizer ?? defaultCreateBinarizer;
         this.createRGBLuminanceSource = createRGBLuminanceSource ?? defaultCreateRGBLuminanceSource;
         Options.ValueChanged += (o, args) => usePreviousState = false;
         usePreviousState = false;
      }

#if !PORTABLE
#if !UNITY
      /// <summary>
      /// Decodes the specified barcode bitmap.
      /// </summary>
      /// <param name="barcodeBitmap">The barcode bitmap.</param>
      /// <returns>the result data or null</returns>
      public Result Decode(T barcodeBitmap)
#else
      /// <summary>
      /// Decodes the specified barcode bitmap.
      /// </summary>
      /// <param name="rawRGB">raw bytes of the image in RGB order</param>
      /// <param name="width"></param>
      /// <param name="height"></param>
      /// <returns>
      /// the result data or null
      /// </returns>
      public Result Decode(T rawRGB, int width, int height)
#endif
      {
         if (CreateLuminanceSource == null)
         {
            throw new InvalidOperationException("You have to declare a luminance source delegate.");
         }

#if !UNITY
         if (barcodeBitmap == null)
            throw new ArgumentNullException("barcodeBitmap");
#else
         if (rawRGB == null)
            throw new ArgumentNullException("rawRGB");
#endif

#if !UNITY
         var luminanceSource = CreateLuminanceSource(barcodeBitmap);
#else
         var luminanceSource = CreateLuminanceSource(rawRGB, width, height);
#endif

         return Decode(luminanceSource);
      }
#endif

      /// <summary>
      /// Tries to decode a barcode within an image which is given by a luminance source.
      /// That method gives a chance to prepare a luminance source completely before calling
      /// the time consuming decoding method. On the other hand there is a chance to create
      /// a luminance source which is independent from external resources (like Bitmap objects)
      /// and the decoding call can be made in a background thread.
      /// </summary>
      /// <param name="luminanceSource">The luminance source.</param>
      /// <returns></returns>
      virtual public Result Decode(LuminanceSource luminanceSource)
      {
         var result = default(Result);
         var binarizer = CreateBinarizer(luminanceSource);
         var binaryBitmap = new BinaryBitmap(binarizer);
         var multiformatReader = Reader as MultiFormatReader;
         var rotationCount = 0;
         var rotationMaxCount = 1;

         if (AutoRotate)
         {
            Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
            rotationMaxCount = 4;
         }
         else
         {
            if (Options.Hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION))
               Options.Hints.Remove(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION);
         }

         for (; rotationCount < rotationMaxCount; rotationCount++)
         {
            if (usePreviousState && multiformatReader != null)
            {
               result = multiformatReader.decodeWithState(binaryBitmap);
            }
            else
            {
               result = Reader.decode(binaryBitmap, Options.Hints);
               usePreviousState = true;
            }

            if (result == null)
            {
               if (TryInverted && luminanceSource.InversionSupported)
               {
                  binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                  if (usePreviousState && multiformatReader != null)
                  {
                     result = multiformatReader.decodeWithState(binaryBitmap);
                  }
                  else
                  {
                     result = Reader.decode(binaryBitmap, Options.Hints);
                     usePreviousState = true;
                  }
               }
            }

            if (result != null ||
                !luminanceSource.RotateSupported ||
                !AutoRotate)
               break;

            binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.rotateCounterClockwise()));
         }

         if (result != null)
         {
            if (result.ResultMetadata == null)
            {
               result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
            }
            else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
            {
               result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
            }
            else
            {
               // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
               result.ResultMetadata[ResultMetadataType.ORIENTATION] = ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
            }

            OnResultFound(result);
         }

         return result;
      }

#if !PORTABLE
#if !UNITY
      /// <summary>
      /// Decodes the specified barcode bitmap.
      /// </summary>
      /// <param name="barcodeBitmap">The barcode bitmap.</param>
      /// <returns>the result data or null</returns>
      public Result[] DecodeMultiple(T barcodeBitmap)
#else
      /// <summary>
      /// Decodes the specified barcode bitmap.
      /// </summary>
      /// <param name="rawRGB">raw bytes of the image in RGB order</param>
      /// <param name="width"></param>
      /// <param name="height"></param>
      /// <returns>
      /// the result data or null
      /// </returns>
      public Result[] DecodeMultiple(T rawRGB, int width, int height)
#endif
      {
         if (CreateLuminanceSource == null)
         {
            throw new InvalidOperationException("You have to declare a luminance source delegate.");
         }
#if !UNITY
         if (barcodeBitmap == null)
            throw new ArgumentNullException("barcodeBitmap");
#else
         if (rawRGB == null)
            throw new ArgumentNullException("rawRGB");
#endif

#if !UNITY
         var luminanceSource = CreateLuminanceSource(barcodeBitmap);
#else
         var luminanceSource = CreateLuminanceSource(rawRGB, width, height);
#endif

         return DecodeMultiple(luminanceSource);
      }
#endif

      /// <summary>
      /// Tries to decode barcodes within an image which is given by a luminance source.
      /// That method gives a chance to prepare a luminance source completely before calling
      /// the time consuming decoding method. On the other hand there is a chance to create
      /// a luminance source which is independent from external resources (like Bitmap objects)
      /// and the decoding call can be made in a background thread.
      /// </summary>
      /// <param name="luminanceSource">The luminance source.</param>
      /// <returns></returns>
      virtual public Result[] DecodeMultiple(LuminanceSource luminanceSource)
      {
         var results = default(Result[]);
         var binarizer = CreateBinarizer(luminanceSource);
         var binaryBitmap = new BinaryBitmap(binarizer);
         var rotationCount = 0;
         var rotationMaxCount = 1;
         MultipleBarcodeReader multiReader = null;

         if (AutoRotate)
         {
            Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
            rotationMaxCount = 4;
         }

         var formats = Options.PossibleFormats;
         if (formats != null &&
             formats.Count == 1 &&
             formats.Contains(BarcodeFormat.QR_CODE))
         {
            multiReader = new QRCodeMultiReader();
         }
         else
         {
            multiReader = new GenericMultipleBarcodeReader(Reader);
         }

         for (; rotationCount < rotationMaxCount; rotationCount++)
         {
            results = multiReader.decodeMultiple(binaryBitmap, Options.Hints);

            if (results == null)
            {
               if (TryInverted && luminanceSource.InversionSupported)
               {
                  binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                  results = multiReader.decodeMultiple(binaryBitmap, Options.Hints);
               }
            }

            if (results != null ||
                !luminanceSource.RotateSupported ||
                !AutoRotate)
               break;

            binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.rotateCounterClockwise()));
         }

         if (results != null)
         {
            foreach (var result in results)
            {
               if (result.ResultMetadata == null)
               {
                  result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
               }
               else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
               {
                  result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
               }
               else
               {
                  // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
                  result.ResultMetadata[ResultMetadataType.ORIENTATION] =
                     ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
               }
            }

            OnResultsFound(results);
         }

         return results;
      }

      protected void OnResultsFound(IEnumerable<Result> results)
      {
         if (ResultFound != null)
         {
            foreach (var result in results)
            {
               ResultFound(result);
            }
         }
      }

      protected void OnResultFound(Result result)
      {
         if (ResultFound != null)
         {
            ResultFound(result);
         }
      }

      protected void OnResultPointFound(ResultPoint resultPoint)
      {
         if (explicitResultPointFound != null)
         {
            explicitResultPointFound(resultPoint);
         }
      }

      /// <summary>
      /// Decodes the specified barcode bitmap.
      /// </summary>
      /// <param name="rawRGB">The image as byte[] array.</param>
      /// <param name="width">The width.</param>
      /// <param name="height">The height.</param>
      /// <param name="format">The format.</param>
      /// <returns>
      /// the result data or null
      /// </returns>
      public Result Decode(byte[] rawRGB, int width, int height, RGBLuminanceSource.BitmapFormat format)
      {
         if (rawRGB == null)
            throw new ArgumentNullException("rawRGB");

         var luminanceSource = createRGBLuminanceSource(rawRGB, width, height, format);

         return Decode(luminanceSource);
      }

      /// <summary>
      /// Decodes the specified barcode bitmap.
      /// </summary>
      /// <param name="rawRGB">The image as byte[] array.</param>
      /// <param name="width">The width.</param>
      /// <param name="height">The height.</param>
      /// <param name="format">The format.</param>
      /// <returns>
      /// the result data or null
      /// </returns>
      public Result[] DecodeMultiple(byte[] rawRGB, int width, int height, RGBLuminanceSource.BitmapFormat format)
      {
         if (rawRGB == null)
            throw new ArgumentNullException("rawRGB");

         var luminanceSource = createRGBLuminanceSource(rawRGB, width, height, format);

         return DecodeMultiple(luminanceSource);
      }
   }
}


text:
This is an experimental [Prometheus](http://prometheus.io/) setup for monitoring
Kubernetes services that expose prometheus-friendly metrics through address
http://service_address:service_port/metrics.

# Purpose
The purpose of the setup is to gather performance-related metrics during load
tests and analyze them to find and fix bottlenecks.

# Quick start

## Promdash/Prometheus

1. Pick a local directory for promdash.  It can be any directory, preferably one which is stable and which you don't mind keeping around.  Then (in our case, we use */mnt/promdash*, just run this docker command `docker run -v /mnt/promdash:/mnt/promdash -e DATABASE_URL=sqlite3:/mnt/promdash/file.sqlite3 prom/promdash ./bin/rake db:migrate`.  In the future, we might use mysql as the promdash database, however, in any case, this 1 time db setup step is required.

Now quickly confirm that /mnt/promdash/file.sqlite3 exists, and has a non-zero size, and make sure its permissions are open so that containers can read from it.  For example:
```
    [jay@rhbd kubernetes]$ ls -altrh /mnt/promdash/
    total 20K
    drwxr-xr-x. 6 root root 4.0K May  6 23:12 ..
    -rwxrwxrwx  1 root root  12K May  6 23:33 file.sqlite3
```
Looks open enough :).

1. Now, you can start this pod, like so `kubectl create -f cluster/add-ons/prometheus/prometheusB3.yaml`.  This pod will start both prometheus, the server, as well as promdash, the visualization tool.  You can then configure promdash, and next time you restart the pod - you're configuration will be remain (since the promdash directory was mounted as a local docker volume).

1. Finally, you can simply access localhost:3000, which will have promdash running.  Then, add the prometheus server (locahost:9090)to as a promdash server, and create a dashboard according to the promdash directions.

## Prometheus

You can launch prometheus easily, by simply running.

`kubectl create -f cluster/addons/prometheus/prometheus.yaml`

This will bind to port 9090 locally.  You can see the prometheus database at that URL.

# How it works

This is a v1beta1 based, containerized prometheus pod, which scrapes endpoints which are readable on the KUBERNETES_RO service (the internal kubernetes service running in the default namespace, which is visible to all pods).

1. The KUBERNETES_RO service is already running : providing read access to the API metrics.

1. The list of services to be monitored is passed as a command line aguments in
the yaml file.

1. The startup scripts assumes that each service T will have
2 environment variables set ```T_SERVICE_HOST``` and ```T_SERVICE_PORT```

1. Each can be configured manually in yaml file if you want to monitor something
that is not a regular Kubernetes service.  For example, you can add comma delimted
endpoints which can be scraped like so...
```
- -t
- KUBERNETES_RO,MY_OTHER_METRIC_SERVICE
```

# Other notes

For regular Kubernetes services the env variables are set up automatically and injected at runtime.

By default the metrics are written to a temporary location (that can be changed
in the the volumes section of the yaml file). Prometheus' UI is available
at port 9090.

# TODO

- We should publish this image into the kube/ namespace.
- Possibly use postgre or mysql as a promdash database.
- push gateway (https://github.com/prometheus/pushgateway) setup.
- Setup high availability via NFS

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/contrib/prometheus/README.md?pixel)]()


text:
class TutorialPipeline(object):
    def process_item(self, item, spider):
        return item