text:
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/iotsitewise/model/ForwardingConfig.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTSiteWise
{
namespace Model
{

  /**
   *
The processing configuration for the given measurement property. You can
   * configure measurements to be kept at the edge or forwarded to the Amazon Web
   * Services Cloud. By default, measurements are forwarded to the
   * cloud.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTSITEWISE_API MeasurementProcessingConfig
  {
  public:
    MeasurementProcessingConfig();
    MeasurementProcessingConfig(Aws::Utils::Json::JsonView jsonValue);
    MeasurementProcessingConfig& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The forwarding configuration for the given measurement property.

     */
    inline const ForwardingConfig& GetForwardingConfig() const{ return m_forwardingConfig; }

    /**
     *
The forwarding configuration for the given measurement property.

     */
    inline bool ForwardingConfigHasBeenSet() const { return m_forwardingConfigHasBeenSet; }

    /**
     *
The forwarding configuration for the given measurement property.

     */
    inline void SetForwardingConfig(const ForwardingConfig& value) { m_forwardingConfigHasBeenSet = true; m_forwardingConfig = value; }

    /**
     *
The forwarding configuration for the given measurement property.

     */
    inline void SetForwardingConfig(ForwardingConfig&& value) { m_forwardingConfigHasBeenSet = true; m_forwardingConfig = std::move(value); }

    /**
     *
The forwarding configuration for the given measurement property.

     */
    inline MeasurementProcessingConfig& WithForwardingConfig(const ForwardingConfig& value) { SetForwardingConfig(value); return *this;}

    /**
     *
The forwarding configuration for the given measurement property.

     */
    inline MeasurementProcessingConfig& WithForwardingConfig(ForwardingConfig&& value) { SetForwardingConfig(std::move(value)); return *this;}

  private:

    ForwardingConfig m_forwardingConfig;
    bool m_forwardingConfigHasBeenSet = false;
  };

} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws


text:
package whisperv2

import (
	"crypto/ecdsa"
	"fmt"
	"sync"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/crypto/ecies"
	"github.com/ethereum/go-ethereum/event/filter"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/p2p"
	"github.com/ethereum/go-ethereum/rpc"

	"gopkg.in/fatih/set.v0"
)

const (
	statusCode   = 0x00
	messagesCode = 0x01

	protocolVersion uint64 = 0x02
	protocolName           = "shh"

	signatureFlag   = byte(1 << 7)
	signatureLength = 65

	expirationCycle   = 800 * time.Millisecond
	transmissionCycle = 300 * time.Millisecond
)

const (
	DefaultTTL = 50 * time.Second
	DefaultPoW = 50 * time.Millisecond
)

type MessageEvent struct {
	To      *ecdsa.PrivateKey
	From    *ecdsa.PublicKey
	Message *Message
}

// Whisper represents a dark communication interface through the Ethereum
// network, using its very own P2P communication layer.
type Whisper struct {
	protocol p2p.Protocol
	filters  *filter.Filters

	keys map[string]*ecdsa.PrivateKey

	messages    map[common.Hash]*Envelope // Pool of messages currently tracked by this node
	expirations map[uint32]*set.SetNonTS  // Message expiration pool (TODO: something lighter)
	poolMu      sync.RWMutex              // Mutex to sync the message and expiration pools

	peers  map[*peer]struct{} // Set of currently active peers
	peerMu sync.RWMutex       // Mutex to sync the active peer set

	quit chan struct{}
}

// New creates a Whisper client ready to communicate through the Ethereum P2P
// network.
func New() *Whisper {
	whisper := &Whisper{
		filters:     filter.New(),
		keys:        make(map[string]*ecdsa.PrivateKey),
		messages:    make(map[common.Hash]*Envelope),
		expirations: make(map[uint32]*set.SetNonTS),
		peers:       make(map[*peer]struct{}),
		quit:        make(chan struct{}),
	}
	whisper.filters.Start()

	// p2p whisper sub protocol handler
	whisper.protocol = p2p.Protocol{
		Name:    protocolName,
		Version: uint(protocolVersion),
		Length:  2,
		Run:     whisper.handlePeer,
	}

	return whisper
}

// APIs returns the RPC descriptors the Whisper implementation offers
func (s *Whisper) APIs() []rpc.API {
	return []rpc.API{
		{
			Namespace: "shh",
			Version:   "1.0",
			Service:   NewPublicWhisperAPI(s),
			Public:    true,
		},
	}
}

// Protocols returns the whisper sub-protocols ran by this particular client.
func (self *Whisper) Protocols() []p2p.Protocol {
	return []p2p.Protocol{self.protocol}
}

// Version returns the whisper sub-protocols version number.
func (self *Whisper) Version() uint {
	return self.protocol.Version
}

// NewIdentity generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption.
func (self *Whisper) NewIdentity() *ecdsa.PrivateKey {
	key, err := crypto.GenerateKey()
	if err != nil {
		panic(err)
	}
	self.keys[string(crypto.FromECDSAPub(&key.PublicKey))] = key

	return key
}

// HasIdentity checks if the the whisper node is configured with the private key
// of the specified public pair.
func (self *Whisper) HasIdentity(key *ecdsa.PublicKey) bool {
	return self.keys[string(crypto.FromECDSAPub(key))] != nil
}

// GetIdentity retrieves the private key of the specified public identity.
func (self *Whisper) GetIdentity(key *ecdsa.PublicKey) *ecdsa.PrivateKey {
	return self.keys[string(crypto.FromECDSAPub(key))]
}

// Watch installs a new message handler to run in case a matching packet arrives
// from the whisper network.
func (self *Whisper) Watch(options Filter) int {
	filter := filterer{
		to:      string(crypto.FromECDSAPub(options.To)),
		from:    string(crypto.FromECDSAPub(options.From)),
		matcher: newTopicMatcher(options.Topics...),
		fn: func(data interface{}) {
			options.Fn(data.(*Message))
		},
	}
	return self.filters.Install(filter)
}

// Unwatch removes an installed message handler.
func (self *Whisper) Unwatch(id int) {
	self.filters.Uninstall(id)
}

// Send injects a message into the whisper send queue, to be distributed in the
// network in the coming cycles.
func (self *Whisper) Send(envelope *Envelope) error {
	return self.add(envelope)
}

// Start implements node.Service, starting the background data propagation thread
// of the Whisper protocol.
func (self *Whisper) Start(*p2p.Server) error {
	log.Info("Whisper started")
	go self.update()
	return nil
}

// Stop implements node.Service, stopping the background data propagation thread
// of the Whisper protocol.
func (self *Whisper) Stop() error {
	close(self.quit)
	log.Info("Whisper stopped")
	return nil
}

// Messages retrieves all the currently pooled messages matching a filter id.
func (self *Whisper) Messages(id int) []*Message {
	messages := make([]*Message, 0)
	if filter := self.filters.Get(id); filter != nil {
		for _, envelope := range self.messages {
			if message := self.open(envelope); message != nil {
				if self.filters.Match(filter, createFilter(message, envelope.Topics)) {
					messages = append(messages, message)
				}
			}
		}
	}
	return messages
}

// handlePeer is called by the underlying P2P layer when the whisper sub-protocol
// connection is negotiated.
func (self *Whisper) handlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
	// Create the new peer and start tracking it
	whisperPeer := newPeer(self, peer, rw)

	self.peerMu.Lock()
	self.peers[whisperPeer] = struct{}{}
	self.peerMu.Unlock()

	defer func() {
		self.peerMu.Lock()
		delete(self.peers, whisperPeer)
		self.peerMu.Unlock()
	}()

	// Run the peer handshake and state updates
	if err := whisperPeer.handshake(); err != nil {
		return err
	}
	whisperPeer.start()
	defer whisperPeer.stop()

	// Read and process inbound messages directly to merge into client-global state
	for {
		// Fetch the next packet and decode the contained envelopes
		packet, err := rw.ReadMsg()
		if err != nil {
			return err
		}
		var envelopes []*Envelope
		if err := packet.Decode(&envelopes); err != nil {
			log.Info(fmt.Sprintf("%v: failed to decode envelope: %v", peer, err))
			continue
		}
		// Inject all envelopes into the internal pool
		for _, envelope := range envelopes {
			if err := self.add(envelope); err != nil {
				// TODO Punish peer here. Invalid envelope.
				log.Debug(fmt.Sprintf("%v: failed to pool envelope: %v", peer, err))
			}
			whisperPeer.mark(envelope)
		}
	}
}

// add inserts a new envelope into the message pool to be distributed within the
// whisper network. It also inserts the envelope into the expiration pool at the
// appropriate time-stamp.
func (self *Whisper) add(envelope *Envelope) error {
	self.poolMu.Lock()
	defer self.poolMu.Unlock()

	// short circuit when a received envelope has already expired
	if envelope.Expiry < uint32(time.Now().Unix()) {
		return nil
	}

	// Insert the message into the tracked pool
	hash := envelope.Hash()
	if _, ok := self.messages[hash]; ok {
		log.Trace(fmt.Sprintf("whisper envelope already cached: %x\n", envelope))
		return nil
	}
	self.messages[hash] = envelope

	// Insert the message into the expiration pool for later removal
	if self.expirations[envelope.Expiry] == nil {
		self.expirations[envelope.Expiry] = set.NewNonTS()
	}
	if !self.expirations[envelope.Expiry].Has(hash) {
		self.expirations[envelope.Expiry].Add(hash)

		// Notify the local node of a message arrival
		go self.postEvent(envelope)
	}
	log.Trace(fmt.Sprintf("cached whisper envelope %x\n", envelope))
	return nil
}

// postEvent opens an envelope with the configured identities and delivers the
// message upstream from application processing.
func (self *Whisper) postEvent(envelope *Envelope) {
	if message := self.open(envelope); message != nil {
		self.filters.Notify(createFilter(message, envelope.Topics), message)
	}
}

// open tries to decrypt a whisper envelope with all the configured identities,
// returning the decrypted message and the key used to achieve it. If not keys
// are configured, open will return the payload as if non encrypted.
func (self *Whisper) open(envelope *Envelope) *Message {
	// Short circuit if no identity is set, and assume clear-text
	if len(self.keys) == 0 {
		if message, err := envelope.Open(nil); err == nil {
			return message
		}
	}
	// Iterate over the keys and try to decrypt the message
	for _, key := range self.keys {
		message, err := envelope.Open(key)
		if err == nil {
			message.To = &key.PublicKey
			return message
		} else if err == ecies.ErrInvalidPublicKey {
			return message
		}
	}
	// Failed to decrypt, don't return anything
	return nil
}

// createFilter creates a message filter to check against installed handlers.
func createFilter(message *Message, topics []Topic) filter.Filter {
	matcher := make([][]Topic, len(topics))
	for i, topic := range topics {
		matcher[i] = []Topic{topic}
	}
	return filterer{
		to:      string(crypto.FromECDSAPub(message.To)),
		from:    string(crypto.FromECDSAPub(message.Recover())),
		matcher: newTopicMatcher(matcher...),
	}
}

// update loops until the lifetime of the whisper node, updating its internal
// state by expiring stale messages from the pool.
func (self *Whisper) update() {
	// Start a ticker to check for expirations
	expire := time.NewTicker(expirationCycle)

	// Repeat updates until termination is requested
	for {
		select {
		case <-expire.C:
			self.expire()

		case <-self.quit:
			return
		}
	}
}

// expire iterates over all the expiration timestamps, removing all stale
// messages from the pools.
func (self *Whisper) expire() {
	self.poolMu.Lock()
	defer self.poolMu.Unlock()

	now := uint32(time.Now().Unix())
	for then, hashSet := range self.expirations {
		// Short circuit if a future time
		if then > now {
			continue
		}
		// Dump all expired messages and remove timestamp
		hashSet.Each(func(v interface{}) bool {
			delete(self.messages, v.(common.Hash))
			return true
		})
		self.expirations[then].Clear()
	}
}

// envelopes retrieves all the messages currently pooled by the node.
func (self *Whisper) envelopes() []*Envelope {
	self.poolMu.RLock()
	defer self.poolMu.RUnlock()

	envelopes := make([]*Envelope, 0, len(self.messages))
	for _, envelope := range self.messages {
		envelopes = append(envelopes, envelope)
	}
	return envelopes
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * 02/21/2004
 *
 * Token.java - A token used in syntax highlighting.
 *
 * This library is distributed under a modified BSD license.  See the included
 * RSyntaxTextArea.License.txt file for details.
 */
package org.fife.ui.rsyntaxtextarea;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import javax.swing.text.TabExpander;

/**
 * A generic token that functions as a node in a linked list of syntax
 * highlighted tokens for some language.

 *
 * A Token is a piece of text representing some logical token in
 * source code for a programming language.  For example, the line of C code:

 *

 * int i = 0;
 *

 * would be broken into 8 Tokens: the first representing
 * int, the second whitespace, the third i, the fourth
 * whitespace, the fifth =, etc.

 *
 * @author Robert Futrell
 * @version 0.3
 */
public abstract class Token implements TokenTypes {

	/**
	 * The text this token represents.  This is implemented as a segment so we
	 * can point directly to the text in the document without having to make a
	 * copy of it.
	 */
	public char[] text;
	public int textOffset;
	public int textCount;

	/**
	 * The offset into the document at which this token resides.
	 */
	public int offset;

	/**
	 * The type of token this is; for example, {@link #FUNCTION}.
	 */
	public int type;

	/**
	 * Whether this token is a hyperlink.
	 */
	private boolean hyperlink;

	/**
	 * The next token in this linked list.
	 */
	private Token nextToken;

	/**
	 * The language this token is in, >= 0.
	 */
	private int languageIndex;

	/**
	 * Rectangle used for filling token backgrounds.
	 */
	private Rectangle2D.Float bgRect;

	/**
	 * Micro-optimization; buffer used to compute tab width.  If the width is
	 * correct it's not re-allocated, to prevent lots of very small garbage.
	 * Only used when painting tab lines.
	 */
	private static char[] tabBuf;

	/**
	 * Creates a "null token."  The token itself is not null; rather, it
	 * signifies that it is the last token in a linked list of tokens and
	 * that it is not part of a "multi-line token."
	 */
	public Token() {
		this.text = null;
		this.textOffset = -1;
		this.textCount = -1;
		this.type = NULL;
		offset = -1;
		hyperlink = false;
		nextToken = null;
		bgRect = new Rectangle2D.Float();
	}

	/**
	 * Constructor.
	 *
	 * @param line The segment from which to get the token.
	 * @param beg The first character's position in line.
	 * @param end The last character's position in line.
	 * @param startOffset The offset into the document at which this
	 *        token begins.
	 * @param type A token type listed as "generic" above.
	 */
	public Token(final char[] line, final int beg, final int end,
							final int startOffset, final int type) {
		this();
		set(line, beg,end, startOffset, type);
	}

	/**
	 * Creates this token as a deep copy of the passed-in token.
	 *
	 * @param t2 The token from which to make a copy.
	 */
	public Token(Token t2) {
		this();
		copyFrom(t2);
	}

	/**
	 * Appends HTML code for painting this token, using the given text area's
	 * color scheme.
	 *
	 * @param sb The buffer to append to.
	 * @param textArea The text area whose color scheme to use.
	 * @param fontFamily Whether to include the font family in the HTML for
	 *        this token.  You can pass false for this parameter
	 *        if, for example, you are making all your HTML be monospaced,
	 *        and don't want any crazy fonts being used in the editor to be
	 *        reflected in your HTML.
	 * @return The buffer appended to.
	 * @see #getHTMLRepresentation(RSyntaxTextArea)
	 */
	public StringBuffer appendHTMLRepresentation(StringBuffer sb,
											RSyntaxTextArea textArea,
											boolean fontFamily) {
		return appendHTMLRepresentation(sb, textArea, fontFamily, false);
	}

	/**
	 * Appends HTML code for painting this token, using the given text area's
	 * color scheme.
	 *
	 * @param sb The buffer to append to.
	 * @param textArea The text area whose color scheme to use.
	 * @param fontFamily Whether to include the font family in the HTML for
	 *        this token.  You can pass false for this parameter
	 *        if, for example, you are making all your HTML be monospaced,
	 *        and don't want any crazy fonts being used in the editor to be
	 *        reflected in your HTML.
	 * @param tabsToSpaces Whether to convert tabs into spaces.
	 * @return The buffer appended to.
	 * @see #getHTMLRepresentation(RSyntaxTextArea)
	 */
	public StringBuffer appendHTMLRepresentation(StringBuffer sb,
								RSyntaxTextArea textArea, boolean fontFamily,
								boolean tabsToSpaces) {

		SyntaxScheme colorScheme = textArea.getSyntaxScheme();
		Style scheme = colorScheme.getStyle(type);
		Font font = textArea.getFontForTokenType(type);//scheme.font;

		if (font.isBold()) sb.append("");
		if (font.isItalic()) sb.append("");
		if (scheme.underline || isHyperlink()) sb.append("");

		sb.append("");

		// NOTE: Don't use getLexeme().trim() because whitespace tokens will
		// be turned into NOTHING.
		appendHtmlLexeme(textArea, sb, tabsToSpaces);

		sb.append("");
		if (scheme.underline || isHyperlink()) sb.append("");
		if (font.isItalic()) sb.append("");
		if (font.isBold()) sb.append("");

		return sb;

	}

	/**
	 * Appends an HTML version of the lexeme of this token (i.e. no style
	 * HTML, but replacing chars such as \t, <
	 * and > with their escapes).
	 *
	 * @param textArea The text area.
	 * @param sb The buffer to append to.
	 * @param tabsToSpaces Whether to convert tabs into spaces.
	 * @return The same buffer.
	 */
	private final StringBuffer appendHtmlLexeme(RSyntaxTextArea textArea,
								StringBuffer sb, boolean tabsToSpaces) {

		boolean lastWasSpace = false;
		int i = textOffset;
		int lastI = i;
		String tabStr = null;

		while (i<textOffset+textCount) {
			char ch = text[i];
			switch (ch) {
				case ' ':
					sb.append(text, lastI, i-lastI);
					lastI = i+1;
					sb.append(lastWasSpace ? " " : " ");
					lastWasSpace = true;
					break;
				case '\t':
					sb.append(text, lastI, i-lastI);
					lastI = i+1;
					if (tabsToSpaces && tabStr==null) {
						tabStr = "";
						for (int j=0; j<textArea.getTabSize(); j++) {
							tabStr += " ";
						}
					}
					sb.append(tabsToSpaces ? tabStr : "	");
					lastWasSpace = false;
					break;
				case '<':
					sb.append(text, lastI, i-lastI);
					lastI = i+1;
					sb.append("<");
					lastWasSpace = false;
					break;
				case '>':
					sb.append(text, lastI, i-lastI);
					lastI = i+1;
					sb.append(">");
					lastWasSpace = false;
					break;
				default:
					lastWasSpace = false;
					break;
			}
			i++;
		}
		if (lastI<textOffset+textCount) {
			sb.append(text, lastI, textOffset+textCount-lastI);
		}
		return sb;
	}

	/**
	 * Returns whether the token straddles the specified position in the
	 * document.
	 *
	 * @param pos The position in the document to check.
	 * @return Whether the specified position is straddled by this token.
	 */
	public boolean containsPosition(int pos) {
		return pos>=offset && pos<offset+textCount;
	}

	/**
	 * Makes one token point to the same text segment, and have the same value
	 * as another token.
	 *
	 * @param t2 The token from which to copy.
	 */
	public void copyFrom(Token t2) {
		text = t2.text;
		textOffset = t2.textOffset;
		textCount = t2.textCount;
		offset = t2.offset;
		type = t2.type;
		languageIndex = t2.languageIndex;
		nextToken = t2.nextToken;
	}

	/**
	 * Returns the position in the token's internal char array corresponding
	 * to the specified document position.

	 * Note that this method does NOT do any bounds checking; you can pass in
	 * a document position that does not correspond to a position in this
	 * token, and you will not receive an Exception or any other notification;
	 * it is up to the caller to ensure valid input.
	 *
	 * @param pos A position in the document that is represented by this token.
	 * @return The corresponding token position >= textOffset and
	 *         < textOffset+textCount.
	 * @see #tokenToDocument
	 */
	public int documentToToken(int pos) {
		return pos + (textOffset-offset);
	}

	/**
	 * Returns whether this token's lexeme ends with the specified characters.
	 *
	 * @param ch The characters.
	 * @return Whether this token's lexeme ends with the specified characters.
	 * @see #startsWith(char[])
	 */
	public boolean endsWith(char[] ch) {
		if (ch==null || ch.length>textCount) {
			return false;
		}
		final int start = textOffset + textCount - ch.length;
		for (int i=0; i<ch.length; i++) {
			if (text[start+i]!=ch[i]) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Returns a String of the form "#xxxxxx" good for use
	 * in HTML, representing the given color.
	 *
	 * @param color The color to get a string for.
	 * @return The HTML form of the color.  If color is
	 *         null, #000000 is returned.
	 */
	private static final String getHTMLFormatForColor(Color color) {
		if (color==null) {
			return "black";
		}
		String hexRed = Integer.toHexString(color.getRed());
		if (hexRed.length()==1)
			hexRed = "0" + hexRed;
		String hexGreen = Integer.toHexString(color.getGreen());
		if (hexGreen.length()==1)
			hexGreen = "0" + hexGreen;
		String hexBlue = Integer.toHexString(color.getBlue());
		if (hexBlue.length()==1)
			hexBlue = "0" + hexBlue;
		return "#" + hexRed + hexGreen + hexBlue;
	}

	/**
	 * Returns a String containing HTML code for painting this
	 * token, using the given text area's color scheme.
	 *
	 * @param textArea The text area whose color scheme to use.
	 * @return The HTML representation of the token.
	 * @see #appendHTMLRepresentation(StringBuffer, RSyntaxTextArea, boolean)
	 */
	public String getHTMLRepresentation(RSyntaxTextArea textArea) {
		StringBuffer buf = new StringBuffer();
		appendHTMLRepresentation(buf, textArea, true);
		return buf.toString();
	}

	/**
	 * Returns the language index of this token.
	 *
	 * @return The language index.  A value of 0 denotes the
	 *        "main" language, any positive value denotes a specific secondary
	 *        language.
	 * @see #setLanguageIndex(int)
	 */
	public int getLanguageIndex() {
		return languageIndex;
	}

	/**
	 * Returns the last token in this list that is not whitespace or a
	 * comment.
	 *
	 * @return The last non-comment, non-whitespace token, or null
	 *         if there isn't one.
	 */
	public Token getLastNonCommentNonWhitespaceToken() {

		Token last = null;

		for (Token t=this; t!=null && t.isPaintable(); t=t.nextToken) {
			switch (t.type) {
				case COMMENT_DOCUMENTATION:
				case COMMENT_EOL:
				case COMMENT_MULTILINE:
				case WHITESPACE:
					break;
				default:
					last = t;
					break;
			}
		}

		return last;

	}

	/**
	 * Returns the last paintable token in this token list, or null
	 * if there is no paintable token.
	 *
	 * @return The last paintable token in this token list.
	 */
	public Token getLastPaintableToken() {
		Token t = this;
		while (t.isPaintable()) {
			if (t.nextToken==null || !t.nextToken.isPaintable()) {
				return t;
			}
			t = t.nextToken;
		}
		return null;
	}

	/**
	 * Returns the text of this token, as a string.

	 *
	 * Note that this method isn't used much by the
	 * rsyntaxtextarea package internally, as it tries to limit
	 * memory allocation.
	 *
	 * @return The text of this token.
	 */
	public String getLexeme() {
		return new String(text, textOffset, textCount);
	}

	/**
	 * Determines the offset into this token list (i.e., into the
	 * document) that covers pixel location x if the token list
	 * starts at pixel location x0
.
	 * This method will return the document position "closest" to the
	 * x-coordinate (i.e., if they click on the "right-half" of the
	 * w in awe, the caret will be placed in
	 * between the w and e; similarly, clicking on
	 * the left-half places the caret between the a and
	 * w).  This makes it useful for methods such as
	 * viewToModel found in javax.swing.text.View
	 * subclasses.

	 *
	 * This method is abstract so subclasses who paint themselves differently
	 * (i.e., {@link VisibleWhitespaceToken} is painted a tad differently than
	 * {@link DefaultToken} when rendering hints are enabled) can still return
	 * accurate results.
	 *
	 * @param textArea The text area from which the token list was derived.
	 * @param e How to expand tabs.
	 * @param x0 The pixel x-location that is the beginning of
	 *        tokenList.
	 * @param x The pixel-position for which you want to get the corresponding
	 *        offset.
	 * @return The position (in the document, NOT into the token list!) that
	 *         covers the pixel location.  If tokenList is
	 *         null or has type Token.NULL, then
	 *         -1</code is returned; the caller should recognize this and
	 *         return the actual end position of the (empty) line.
	 */
	public abstract int getListOffset(RSyntaxTextArea textArea, TabExpander e,
								float x0, float x);

	/**
	 * Returns the token after this one in the linked list.
	 *
	 * @return The next token.
	 * @see #setNextToken
	 */
	public Token getNextToken() {
		return nextToken;
	}

	/**
	 * Returns the position in the document that represents the last character
	 * in the token that will fit into endBeforeX-startX pixels.
	 * For example, if you're using a monospaced 8-pixel-per-character font,
	 * have the token "while" and startX is 0 and
	 * endBeforeX is 30, this method will return the
	 * document position of the "i" in "while", because the "i" ends at pixel
	 * 24, while the "l" ends at 32.  If not even the
	 * first character fits in endBeforeX-startX, the first
	 * character's position is still returned so calling methods don't go into
	 * infinite loops.
	 *
	 * @param textArea The text area in which this token is being painted.
	 * @param e How to expand tabs.
	 * @param startX The x-coordinate at which the token will be painted.  This
	 *        is needed because of tabs.
	 * @param endBeforeX The x-coordinate for which you want to find the last
	 *        character of t which comes before it.
	 * @return The last document position that will fit in the specified amount
	 *         of pixels.
	 */
	/*
	 * @see #getTokenListOffsetBeforeX
	 * FIXME:  This method does not compute correctly!  It needs to be abstract
	 * and implemented by subclasses.
	 */
	public int getOffsetBeforeX(RSyntaxTextArea textArea, TabExpander e,
							float startX, float endBeforeX) {

		FontMetrics fm = textArea.getFontMetricsForTokenType(type);
		int i = textOffset;
		int stop = i + textCount;
		float x = startX;

		while (i<stop) {
			if (text[i]=='\t')
				x = e.nextTabStop(x, 0);
			else
				x += fm.charWidth(text[i]);
			if (x>endBeforeX) {
				// If not even the first character fits into the space, go
				// ahead and say the first char does fit so we don't go into
				// an infinite loop.
				int intoToken = Math.max(i-textOffset, 1);
				return offset + intoToken;
			}
			i++;
		}

		// If we got here, the whole token fit in (endBeforeX-startX) pixels.
		return offset + textCount - 1;

	}

	/**
	 * Returns the width of this token given the specified parameters.
	 *
	 * @param textArea The text area in which the token is being painted.
	 * @param e Describes how to expand tabs.  This parameter cannot be
	 *        null.
	 * @param x0 The pixel-location at which the token begins.  This is needed
	 *        because of tabs.
	 * @return The width of the token, in pixels.
	 * @see #getWidthUpTo
	 */
	public float getWidth(RSyntaxTextArea textArea, TabExpander e, float x0) {
		return getWidthUpTo(textCount, textArea, e, x0);
	}

	/**
	 * Returns the width of a specified number of characters in this token.
	 * For example, for the token "while", specifying a value of 3
	 * here returns the width of the "whi" portion of the token.

	 *
	 * This method is abstract so subclasses who paint themselves differently
	 * (i.e., {@link VisibleWhitespaceToken} is painted a tad differently than
	 * {@link DefaultToken} when rendering hints are enabled) can still return
	 * accurate results.
	 *
	 * @param numChars The number of characters for which to get the width.
	 * @param textArea The text area in which the token is being painted.
	 * @param e How to expand tabs.  This value cannot be null.
	 * @param x0 The pixel-location at which this token begins.  This is needed
	 *        because of tabs.
	 * @return The width of the specified number of characters in this token.
	 * @see #getWidth
	 */
	public abstract float getWidthUpTo(int numChars, RSyntaxTextArea textArea,
										TabExpander e, float x0);

	/**
	 * Returns whether this token is of the specified type, with the specified
	 * lexeme.

	 * This method is preferred over the other overload in performance-critical
	 * code where this operation may be called frequently, since it does not
	 * involve any String allocations.
	 *
	 * @param type The type to check for.
	 * @param lexeme The lexeme to check for.
	 * @return Whether this token has that type and lexeme.
	 * @see #is(int, String)
	 * @see #startsWith(char[])
	 */
	public boolean is(int type, char[] lexeme) {
		if (this.type==type && textCount==lexeme.length) {
			for (int i=0; i<textCount; i++) {
				if (text[textOffset+i]!=lexeme[i]) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * Returns whether this token is of the specified type, with the specified
	 * lexeme.

	 * The other overload of this method is preferred over this one in
	 * performance-critical code, as this one involves a String allocation
	 * while the other does not.
	 *
	 * @param type The type to check for.
	 * @param lexeme The lexeme to check for.
	 * @return Whether this token has that type and lexeme.
	 * @see #is(int, char[])
	 */
	public boolean is(int type, String lexeme) {
		return this.type==type && textCount==lexeme.length() &&
				lexeme.equals(getLexeme());
	}

    public int getTokenType()
    {
        return type;
    }

	/**
	 * Returns whether this token is a comment.
	 *
	 * @return Whether this token is a comment.
	 * @see #isWhitespace()
	 */
	public boolean isComment() {
		return type>=Token.COMMENT_EOL && type<=Token.COMMENT_MARKUP;
	}

	/**
	 * Returns whether this token is a hyperlink.
	 *
	 * @return Whether this token is a hyperlink.
	 * @see #setHyperlink(boolean)
	 */
	public boolean isHyperlink() {
		return hyperlink;
	}

	/**
	 * Returns whether this token is an identifier.
	 *
	 * @return Whether this token is an identifier.
	 */
	public boolean isIdentifier() {
		return type==IDENTIFIER;
	}

	/**
	 * Returns whether this token is a {@link #SEPARATOR} representing a single
	 * left curly brace.
	 *
	 * @return Whether this token is a left curly brace.
	 * @see #isRightCurly()
	 */
	public boolean isLeftCurly() {
		return type==SEPARATOR && isSingleChar('{');
	}

	/**
	 * Returns whether this token is a {@link #SEPARATOR} representing a single
	 * right curly brace.
	 *
	 * @return Whether this token is a right curly brace.
	 * @see #isLeftCurly()
	 */
	public boolean isRightCurly() {
		return type==SEPARATOR && isSingleChar('}');
	}

	/**
	 * Returns whether or not this token is "paintable;" i.e., whether or not
	 * the type of this token is one such that it has an associated syntax
	 * style.  What this boils down to is whether the token type is greater
	 * than Token.NULL.
	 *
	 * @return Whether or not this token is paintable.
	 */
	public boolean isPaintable() {
		return type>Token.NULL;
	}

	/**
	 * Returns whether this token is the specified single character.
	 *
	 * @param ch The character to check for.
	 * @return Whether this token's lexeme is the single character specified.
	 */
	public boolean isSingleChar(char ch) {
		return textCount==1 && text[textOffset]==ch;
	}

	/**
	 * Returns whether or not this token is whitespace.
	 *
	 * @return true iff this token is whitespace.
	 * @see #isComment()
	 */
	public boolean isWhitespace() {
		return type==WHITESPACE;
	}

	/**
	 * Returns the bounding box for the specified document location.  The
	 * location must be in the specified token list; if it isn't,
	 * null is returned.
	 *
	 * @param textArea The text area from which the token list was derived.
	 * @param e How to expand tabs.
	 * @param pos The position in the document for which to get the bounding
	 *        box in the view.
	 * @param x0 The pixel x-location that is the beginning of
	 *        tokenList.
	 * @param rect The rectangle in which we'll be returning the results.  This
	 *        object is reused to keep from frequent memory allocations.
	 * @return The bounding box for the specified position in the model.
	 */
	public abstract Rectangle listOffsetToView(RSyntaxTextArea textArea,
								TabExpander e, int pos, int x0,
								Rectangle rect);

	/**
	 * Makes this token start at the specified offset into the document.
	 *
	 * @param pos The offset into the document this token should start at.
	 *        Note that this token must already contain this position; if
	 *        it doesn't, an exception is thrown.
	 * @throws IllegalArgumentException If pos is not already contained by
	 *         this token.
	 * @see #moveOffset(int)
	 */
	public void makeStartAt(int pos) {
		if (pos<offset || pos>=(offset+textCount)) {
			throw new IllegalArgumentException("pos " + pos +
				" is not in range " + offset + "-" + (offset+textCount-1));
		}
		int shift = pos - offset;
		offset = pos;
		textOffset += shift;
		textCount -= shift;
	}

	/**
	 * Moves the starting offset of this token.
	 *
	 * @param amt The amount to move the starting offset.  This should be
	 *        between 0 and textCount, inclusive.
	 * @throws IllegalArgumentException If amt is an invalid value.
	 * @see #makeStartAt(int)
	 */
	public void moveOffset(int amt) {
		if (amt<0 || amt>textCount) {
			throw new IllegalArgumentException("amt " + amt +
					" is not in range 0-" + textCount);
		}
		offset += amt;
		textOffset += amt;
		textCount -= amt;
	}

	/**
	 * Paints this token.
	 *
	 * @param g The graphics context in which to paint.
	 * @param x The x-coordinate at which to paint.
	 * @param y The y-coordinate at which to paint.
	 * @param host The text area this token is in.
	 * @param e How to expand tabs.
	 * @return The x-coordinate representing the end of the painted text.
	 */
	public final float paint(Graphics2D g, float x, float y,
						RSyntaxTextArea host, TabExpander e) {
		return paint(g, x,y, host, e, 0);
	}

	/**
	 * Paints this token.
	 *
	 * @param g The graphics context in which to paint.
	 * @param x The x-coordinate at which to paint.
	 * @param y The y-coordinate at which to paint.
	 * @param host The text area this token is in.
	 * @param e How to expand tabs.
	 * @param clipStart The left boundary of the clip rectangle in which we're
	 *        painting.  This optimizes painting by allowing us to not paint
	 *        paint when this token is "to the left" of the clip rectangle.
	 * @return The x-coordinate representing the end of the painted text.
	 */
	public abstract float paint(Graphics2D g, float x, float y,
							RSyntaxTextArea host,
							TabExpander e, float clipStart);

	/**
	 * Paints the background of a token.
	 *
	 * @param x The x-coordinate of the token.
	 * @param y The y-coordinate of the token.
	 * @param width The width of the token (actually, the width of the part of
	 *        the token to paint).
	 * @param height The height of the token.
	 * @param g The graphics context with which to paint.
	 * @param fontAscent The ascent of the token's font.
	 * @param host The text area.
	 * @param color The color with which to paint.
	 */
	protected void paintBackground(float x, float y, float width, float height,
							Graphics2D g, int fontAscent,
							RSyntaxTextArea host, Color color) {
		// RSyntaxTextArea's bg can be null, so we must check for this.
		Color temp = host.getBackground();
		g.setXORMode(temp!=null ? temp : Color.WHITE);
		g.setColor(color);
		bgRect.setRect(x,y-fontAscent, width,height);
		//g.fill(bgRect);
		g.fillRect((int)x, (int)(y-fontAscent), (int)width, (int)height);
		g.setPaintMode();
	}

	/**
	 * Paints dotted "tab" lines; that is, lines that show where your caret
	 * would go to on the line if you hit "tab".  This visual effect is usually
	 * done in the leading whitespace token(s) of lines.
	 *
	 * @param x The starting x-offset of this token.  It is assumed that this
	 *        is the left margin of the text area (may be non-zero due to
	 *        insets), since tab lines are only painted for leading whitespace.
	 * @param y The baseline where this token was painted.
	 * @param endX The ending x-offset of this token.
	 * @param g The graphics context.
	 * @param e Used to expand tabs.
	 * @param host The text area.
	 */
	protected void paintTabLines(int x, int y, int endX, Graphics2D g,
								TabExpander e, RSyntaxTextArea host) {

		// We allow tab lines to be painted in more than just Token.WHITESPACE,
		// i.e. for MLC's and Token.IDENTIFIERS (for TokenMakers that return
		// whitespace as identifiers for performance).  But we only paint tab
		// lines for the leading whitespace in the token.  So, if this isn't a
		// WHITESPACE token, figure out the leading whitespace's length.
		if (type!=Token.WHITESPACE) {
			int offs = textOffset;
			for (; offs<textOffset+textCount; offs++) {
				if (!RSyntaxUtilities.isWhitespace(text[offs])) {
					break; // MLC text, etc.
				}
			}
			int len = offs - textOffset;
			if (len<2) { // Must be at least two whitespaces to see tab line
				return;
			}
			//endX = x + (int)getWidthUpTo(len, host, e, x);
			endX = (int)getWidthUpTo(len, host, e, 0);
		}

		// Get the length of a tab.
		FontMetrics fm = host.getFontMetricsForTokenType(type);
		int tabSize = host.getTabSize();
		if (tabBuf==null || tabBuf.length<tabSize) {
			tabBuf = new char[tabSize];
			for (int i=0; i<tabSize; i++) {
				tabBuf[i] = ' ';
			}
		}
		// Note different token types (MLC's, whitespace) could possibly be
		// using different fonts, which means we can't cache the actual width
		// of a tab as it may be different per-token-type.  We could keep a
		// per-token-type cache, but we'd have to clear it whenever they
		// modified token styles.
		int tabW = fm.charsWidth(tabBuf, 0, tabSize);

		// Draw any tab lines.  Here we're assuming that "x" is the left
		// margin of the editor.
		g.setColor(host.getTabLineColor());
		int x0 = x + tabW;
		int y0 = y - fm.getAscent();
		if ((y0&1)>0) {
			// Only paint on even y-pixels to prevent doubling up between lines
			y0++;
		}
		while (x0<endX) {
			int y1 = y0;
			int y2 = y0 + host.getLineHeight();
			while (y1<y2) {
				g.drawLine(x0, y1, x0, y1);
				y1 += 2;
			}
			//g.drawLine(x0,y0, x0,y0+host.getLineHeight());
			x0 += tabW;
		}

	}

	/**
	 * Sets the value of this token to a particular segment of a document.
	 * The "next token" value is cleared.
	 *
	 * @param line The segment from which to get the token.
	 * @param beg The first character's position in line.
	 * @param end The last character's position in line.
	 * @param offset The offset into the document at which this token begins.
	 * @param type A token type listed as "generic" above.
	 */
	public void set(final char[] line, final int beg, final int end,
							final int offset, final int type) {
		this.text = line;
		this.textOffset = beg;
		this.textCount = end - beg + 1;
		this.type = type;
		this.offset = offset;
		nextToken = null;
	}

	/**
	 * Sets whether this token is a hyperlink.
	 *
	 * @param hyperlink Whether this token is a hyperlink.
	 * @see #isHyperlink()
	 */
	public void setHyperlink(boolean hyperlink) {
		this.hyperlink = hyperlink;
	}

	/**
	 * Sets the language index for this token.  If this value is positive, it
	 * denotes a specific "secondary" language this token represents (such as
	 * JavaScript code or CSS embedded in an HTML file).  If this value is
	 * 0, this token is in the "main" language being edited.
	 * Negative values are invalid and treated as 0.
	 *
	 * @param languageIndex The new language index.  A value of
	 *        0 denotes the "main" language, any positive value
	 *        denotes a specific secondary language.  Negative values will
	 *        be treated as 0.
	 * @see #getLanguageIndex()
	 */
	public void setLanguageIndex(int languageIndex) {
		this.languageIndex = languageIndex;
	}

	/**
	 * Sets the "next token" pointer of this token to point to the specified
	 * token.
	 *
	 * @param nextToken The new next token.
	 * @see #getNextToken()
	 */
	public void setNextToken(Token nextToken) {
		this.nextToken = nextToken;
	}

	/**
	 * Returns whether this token starts with the specified characters.
	 *
	 * @param chars The characters.
	 * @return Whether this token starts with those characters.
	 * @see #endsWith(char[])
	 * @see #is(int, char[])
	 */
	public boolean startsWith(char[] chars) {
		if (chars.length<=textCount){
			for (int i=0; i<chars.length; i++) {
				if (text[textOffset+i]!=chars[i]) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * Returns the position in the document corresponding to the specified
	 * position in this token's internal char array (textOffset -
	 * textOffset+textCount-1).

	 * Note that this method does NOT do any bounds checking; you can pass in
	 * an invalid token position, and you will not receive an Exception or any
	 * other indication that the returned document position is invalid.  It is
	 * up to the user to ensure valid input.
	 *
	 * @param pos A position in the token's internal char array
	 *        (textOffset - textOffset+textCount).
	 * @return The corresponding position in the document.
	 * @see #documentToToken(int)
	 */
	public int tokenToDocument(int pos) {
		return pos + (offset-textOffset);
	}

	/**
	 * Returns this token as a String, which is useful for
	 * debugging.
	 *
	 * @return A string describing this token.
	 */
	public String toString() {
		return "[Token: " +
			(type==Token.NULL ? "<null token>" :
				"text: '" +
					(text==null ? "<null>" : getLexeme() + "'; " +
	       		"offset: " + offset + "; type: " + type + "; " +
		   		"isPaintable: " + isPaintable() +
		   		"; nextToken==null: " + (nextToken==null))) +
		   "]";
	}

}


text:
'use strict';

module.exports = {
  bindings: {
    env: '<environment',
    application: '<application',
    envChangedCallback: '&onEnvironmentChanged'
  },
  controller: function () {
    var ctrl = this;
    ctrl.error = null;

    ctrl.$onChanges = function () {
      if (ctrl.env) {
        ctrl.allProperties = ctrl.env.reduce(function (left, right) {
          return left.concat(right.value);
        }, []);

        var managerSource = ctrl.env.find(function (source) {
          return source.name === 'manager';
        });
        ctrl.newProperties = (managerSource ? managerSource.value.slice(0) : []);

        ctrl.newProperties.push({
          name: null,
          value: null
        });

        ctrl.allPropertyNames = ctrl.allProperties.map(function (property) {
          return property.name;
        }).sort().filter(function (name, index, names) {
          return !name || name !== names[index - 1];
        });
      }
    };

    ctrl.onChangePropertyName = function (edited) {
      var property = ctrl.allProperties.find(function (p) {
        return p.name === edited.name;
      });
      if (property) {
        edited.value = property.value;
      }
      if (ctrl.newProperties[ctrl.newProperties.length - 1].name) {
        ctrl.newProperties.push({
          name: null,
          value: null
        });
      }
    };

    ctrl.updateEnvironment = function () {
      ctrl.error = null;
      var newPropertyMap = ctrl.newProperties.reduce(function (map, property) {
        if (property.name) {
          map[property.name] = property.value;
        }
        return map;
      }, {});
      ctrl.application.setEnv(newPropertyMap).then(function () {
        ctrl.envChangedCallback()();
      }).catch(function (error) {
        ctrl.error = error;
        ctrl.envChangedCallback()();
      });
    };

    ctrl.resetEnvironment = function () {
      ctrl.error = null;
      ctrl.application.resetEnv().then(function () {
        ctrl.envChangedCallback()();
      }).catch(function (error) {
        ctrl.error = error;
        ctrl.envChangedCallback()();
      });
    };

    ctrl.refreshContext = function () {
      ctrl.application.refresh().then(function () {
        ctrl.envChangedCallback()();
      }).catch(function (error) {
        ctrl.error = error;
        ctrl.envChangedCallback()();
      });
    };
  },
  template: require('./environmentManager.tpl.html')
};


text:
module ActiveScaffold::Config
  class FieldSearch < Base
    self.crud_type = :read

    def initialize(core_config)
      super
      @text_search = self.class.text_search
      @human_conditions = self.class.human_conditions
    end

    # global level configuration
    # --------------------------
    # the ActionLink for this action
    cattr_reader :link
    @@link = ActiveScaffold::DataStructures::ActionLink.new('show_search', :label => :search, :type => :collection, :security_method => :search_authorized?, :ignore_method => :field_search_ignore?)

    # A flag for how the search should do full-text searching in the database:
    # * :full: LIKE %?%
    # * :start: LIKE ?%
    # * :end: LIKE %?
    # * false: LIKE ?
    # Default is :full
    cattr_accessor :text_search
    @@text_search = :full

    # human conditions
    # instead of just filtered you may show the user a humanized search condition statment
    cattr_accessor :human_conditions
    @@human_conditions = false

    # instance-level configuration
    # ----------------------------

    # provides access to the list of columns specifically meant for the Search to use
    def columns
      # we want to delay initializing to the @core.columns set for as long as possible. Too soon and .search_sql will not be available to .searchable?
      unless @columns
        self.columns = @core.columns._inheritable
        columns.exclude @core.columns.active_record_class.locking_column.to_sym
      end
      @columns
    end

    public :columns=

    # A flag for how the search should do full-text searching in the database:
    # * :full: LIKE %?%
    # * :start: LIKE ?%
    # * :end: LIKE %?
    # * false: LIKE ?
    # Default is :full
    attr_accessor :text_search

    # the ActionLink for this action
    attr_accessor :link

    # rarely searched columns may be placed in a hidden subgroup
    def optional_columns=(optionals)
      @optional_columns = Array(optionals)
    end

    def optional_columns
      @optional_columns ||= []
    end

    # default search params
    # default_params = {:title => {"from"=>"test", "to"=>"", "opt"=>"%?%"}}
    attr_accessor :default_params

    # human conditions
    # instead of just filtered you may show the user a humanized search condition statment
    attr_accessor :human_conditions
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.klose.concurrency.shutdown;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class BrokenLogWriter {

    private final BlockingQueue<String> queue;
    private final LoggerThread logger;
    private final int CAPACITY = 100;

    public BrokenLogWriter(PrintWriter writer) {
        this.queue = new LinkedBlockingQueue<>(CAPACITY);
        this.logger = new LoggerThread(writer);
    }

    public void start() {
        logger.start();
    }

    /**
     * 需要打印数据的线程调用该方法, 将待打印数据加入阻塞队列
     *
     * @param msg
     * @throws java.lang.InterruptedException
     */
    public void log(String msg) throws InterruptedException {
        queue.put(msg);
    }

    /**
     * 负责从阻塞队列中取出数据输出的线程
     */
    private class LoggerThread extends Thread {

        private final PrintWriter writer;

        private LoggerThread(PrintWriter writer) {
            this.writer = writer;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    writer.println(queue.take());
                }
            } catch (InterruptedException ignored) {
            } finally {
                writer.close();
            }
        }
    }

    /**
     * 该方法用于停止LoggerThread线程
     */
    public void shutDown() {
        logger.interrupt();
    }
}


text:
#include "DeviceListView.h"

CDeviceListView::CDeviceListView(AppListInterface * pList,QWidget *parent)
    :QWidget(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);
    if (parent){
        setGeometry(0,0,parent->width(),parent->height());
        m_AppWidth = parent->width() / 4;
        m_AppHeight = parent->height() / 2;
    }

    setAutoFillBackground(true);
    QPixmap pixmap(":/images/applinkmain.png");
    pixmap = pixmap.scaled(width(),height(),
                           Qt::IgnoreAspectRatio,
                           Qt::SmoothTransformation);
    QPalette palette;
    palette.setBrush(QPalette::Background, QBrush(pixmap));
    setPalette(palette);

    m_pList = pList;

    //QString childText[2]={"Find New App","App Setting"};
    QString appsheet_on[2] = {":/images/phonechild_on.png",
                              ":/images/listchild_on.png"};
    QString appsheet_off[2] = {":/images/phonechild_off.png",
                               ":/images/listchild_off.png"};

    QString childText[2] = {"返回","连接移动应用程序"};
    InsertDevice(0,"return",childText[0],
                   appsheet_on[0],appsheet_off[0]);
    /*
    for (int i = 0; i < 2; ++i) {
        InsertChildApp(i,funcId[i],childText[i],
                       appsheet_on[i],appsheet_off[i]);
    }*/
}

CDeviceListView::~CDeviceListView()
{
    for (int i = 0; i != m_pDevices.size(); ++i) {
        delete m_pDevices[i];
    }
    m_pDevices.clear();
}

void CDeviceListView::onDeviceSelected(std::string strId)
{
    if(strId != "return")
    {
        m_pList->OnDeviceSelect(strId);
    }
    m_pList->ShowPreviousUI();
}

void CDeviceListView::InsertDevice(int index,std::string DeviceId,QString text,
                                  QString on,QString off,bool bPaint)
{
    for (int i = index; i < m_pDevices.size(); ++i) {
        CAppButton *button = m_pDevices.at(i);
        int r = (i+1)/4;
        int c = (i+1)%4;
        button->setGeometry(5+m_AppWidth*c,5+m_AppHeight*r,
                            m_AppWidth-10,m_AppHeight-10);
    }
    CAppButton *newbutton = new CAppButton(this);
    int r = index/4;
    int c = index%4;
    newbutton->setGeometry(5 + m_AppWidth*c, 5 + m_AppHeight*r,
                           m_AppWidth - 10, m_AppHeight - 10);
    newbutton->setStringId(DeviceId);
    newbutton->setIcon(on, off,bPaint);
    newbutton->setText(text);
    newbutton->show();
    connect(newbutton, SIGNAL(OnClicked(std::string)),
            SLOT(onDeviceSelected(std::string)));
    m_pDevices.insert(index, newbutton);
}

void CDeviceListView::DeleteDevice(int index)
{
    CAppButton *button = m_pDevices.at(index);
    m_pDevices.removeAt(index);
    disconnect(button,SIGNAL(OnClicked(std::string)),
               this,SLOT(onDeviceSelected(std::string)));
    delete button;
    for (int i = index;i<m_pDevices.size();++i) {
        CAppButton *button = m_pDevices.at(i);
        int r = i/4;
        int c = i%4;
        button->setGeometry(5+m_AppWidth*c,5+m_AppHeight*r,
                            m_AppWidth-10,m_AppHeight-10);
    }
}

void CDeviceListView::ClearDeviceList()
{
    for(int i = 0;i < m_pDevices.size();++i)
    {
        delete m_pDevices[i];
    }
    m_pDevices.clear();
}

void CDeviceListView::showEvent(QShowEvent * e)
{
    ClearDeviceList();

    QString appsheet_on[2] = {":/images/phonechild_on.png",
                              ":/images/listchild_on.png"};
    QString appsheet_off[2] = {":/images/phonechild_off.png",
                               ":/images/listchild_off.png"};

    QString childText[2] = {"返回","连接移动应用程序"};
    InsertDevice(0,"return",childText[0],
                   appsheet_on[0],appsheet_off[0]);

    std::vector<DeviceData> DeviceList;
    m_pList->getDeviceList(DeviceList);

    if (DeviceList.size() > 0) {
        for (int i = 0; i < DeviceList.size(); ++i) {
            InsertDevice(1+i,DeviceList[i].id,
                           DeviceList[i].name.c_str(),
                           appsheet_on[0],
                           appsheet_off[0],
                           true);
        }
    }
}


text:
package gov.adlnet.xapi.model;

/**
 * Created by lou on 12/15/14.
 */
public class Person {
    private static final String OBJECTTYPE = "Person";
    private String[] name;
    private String[] mbox;
    private String[] mbox_sha1sum;
    private String[] openid;
    private Account[] account;

    public String getObjectType() {
        return OBJECTTYPE;
    }

    public String[] getName(){
        return this.name;
    }
    public String[] getMbox(){
        return this.mbox;
    }
    public String[] getMbox_sha1sum(){
        return this.mbox_sha1sum;
    }
    public String[] getOpenid(){
        return this.openid;
    }
    public Account[] getAccount(){
        return this.account;
    }

    public String toString() {
        String ret = getObjectType() + " ; ";
        if (name != null && name.length != 0){
            ret += "name: " + name.toString() + " ; ";
        }
        if (mbox != null && mbox.length != 0){
            ret += "mbox: " + mbox.toString() + " ; ";
        }
        if (mbox_sha1sum != null && mbox_sha1sum.length != 0){
            ret += "mbox_sha1sum: " + mbox_sha1sum.toString() + " ; ";
        }
        if (openid != null && openid.length != 0){
            ret += "openid: " + openid.toString() + " ; ";
        }
        if (account != null && account.length != 0){
            ret += "account: ";
            String accts = "";
            for(Account acc: account){
                if (accts.length() != 0){
                    accts += " , ";
                }
                accts += acc.toString() + " ";
            }
            ret += accts + " ; ";
        }
        return ret;
    }
}


text:
class ResultFit2D {
    public :
        ResultFit2D() { clear(); }

        ResultFit2D(
            const std::string& name, int ndimx, int ndimy, int ntmp,
            const std::vector<std::vector<std::array<double, 2>>>& tmps,
            double num_smp, const std::vector<std::array<double, 2>>& smp,
            double num_ref = 0.0, const std::vector<std::array<double, 2>>& ref = std::vector<std::array<double, 2>>());

        void clear();

        void set_fitting_result(int ndof, double nchi, const std::vector<double>& wgt_tmps, const std::vector<double>& wgt_errs);
        void set_histogram_result(bool hist_build = false, TAxis* hist_xaxis = nullptr, TAxis* hist_yaxis = nullptr, const std::string& hist_xtitle = "", const std::string& hist_ytitle = "", const std::string& hist_ztitle = "");

        inline int    ndof() { return ndof_; }
        inline double nchi() { return nchi_; }

        inline int data_ndimx() { return data_ndimx_; }
        inline int data_ndimy() { return data_ndimy_; }
        inline int data_ntmp() { return data_ntmp_; }

        inline const std::vector<std::vector<std::array<double, 2>>>& data_tmps() const { return data_tmps_; }
        inline const std::vector<std::array<double, 2>>& data_smp() const { return data_smp_; }
        inline const std::vector<std::array<double, 2>>& data_ref() const { return data_ref_; }

        inline const std::vector<double>& wgt_tmps() const { return wgt_tmps_; }
        inline const std::vector<double>& wgt_errs() const { return wgt_errs_; }

        inline const std::vector<double>& num_tmps() const { return num_tmps_; }
        inline const std::vector<double>& num_errs() const { return num_errs_; }
        inline const double& num_sum() const { return num_sum_; }
        inline const double& num_smp() const { return num_smp_; }
        inline const double& num_ref() const { return num_ref_; }

        inline std::vector<std::shared_ptr<TH2D>>& htmps() { return hist_tmps_; }
        inline std::shared_ptr<TH2D>& hsum() { return hist_sum_; }
        inline std::shared_ptr<TH2D>& hsmp() { return hist_smp_; }
        inline std::shared_ptr<TH2D>& href() { return hist_ref_; }

        inline std::vector<std::shared_ptr<TH1D>>& htmps_x() { return hist_tmps_x_; }
        inline std::shared_ptr<TH1D>& hsum_x() { return hist_sum_x_; }
        inline std::shared_ptr<TH1D>& hsmp_x() { return hist_smp_x_; }
        inline std::shared_ptr<TH1D>& href_x() { return hist_ref_x_; }

        inline std::vector<std::shared_ptr<TH1D>>& htmps_y() { return hist_tmps_y_; }
        inline std::shared_ptr<TH1D>& hsum_y() { return hist_sum_y_; }
        inline std::shared_ptr<TH1D>& hsmp_y() { return hist_smp_y_; }
        inline std::shared_ptr<TH1D>& href_y() { return hist_ref_y_; }

    protected :
        bool  hist_build_;
        TAxis hist_xaxis_;
        TAxis hist_yaxis_;

        std::string data_name_;
        int         data_ndimx_;
        int         data_ndimy_;
        int         data_ntmp_;

        std::vector<std::vector<std::array<double, 2>>> data_tmps_;
        std::vector<std::array<double, 2>> data_smp_;
        std::vector<std::array<double, 2>> data_ref_;

        std::vector<double> wgt_tmps_;
        std::vector<double> wgt_errs_;

        std::vector<double> num_tmps_;
        std::vector<double> num_errs_;
        double num_sum_;
        double num_smp_;
        double num_ref_;

        std::vector<std::vector<std::array<double, 2>>> tmps_;
        std::vector<std::array<double, 2>> sum_;
        std::vector<std::array<double, 2>> smp_;
        std::vector<std::array<double, 2>> ref_;

        std::vector<std::vector<std::array<double, 2>>> tmps_x_;
        std::vector<std::array<double, 2>> sum_x_;
        std::vector<std::array<double, 2>> smp_x_;
        std::vector<std::array<double, 2>> ref_x_;

        std::vector<std::vector<std::array<double, 2>>> tmps_y_;
        std::vector<std::array<double, 2>> sum_y_;
        std::vector<std::array<double, 2>> smp_y_;
        std::vector<std::array<double, 2>> ref_y_;

        std::vector<std::shared_ptr<TH2D>> hist_tmps_;
        std::shared_ptr<TH2D> hist_sum_;
        std::shared_ptr<TH2D> hist_smp_;
        std::shared_ptr<TH2D> hist_ref_;

        std::vector<std::shared_ptr<TH1D>> hist_tmps_x_;
        std::shared_ptr<TH1D> hist_sum_x_;
        std::shared_ptr<TH1D> hist_smp_x_;
        std::shared_ptr<TH1D> hist_ref_x_;

        std::vector<std::shared_ptr<TH1D>> hist_tmps_y_;
        std::shared_ptr<TH1D> hist_sum_y_;
        std::shared_ptr<TH1D> hist_smp_y_;
        std::shared_ptr<TH1D> hist_ref_y_;

        int    ndof_;
        double nchi_;
};

class DataFit2D {
    public :
        DataFit2D(const std::string& name, std::vector<TH2D*> htmps, TH2D* hsmp, TH2D* href = nullptr, bool hist_build = false, const std::string& hist_xtitle = "", const std::string& hist_ytitle = "", const std::string& hist_ztitle = "");

        inline const int& data_ndimx() const { return data_ndimx_; }
        inline const int& data_ndimy() const { return data_ndimy_; }
        inline const int& data_ntmp() const { return data_ntmp_; }

        inline const double& data_num_smp()      const { return data_num_smp_; }
        inline const double& data_num_ref()      const { return data_num_ref_; }
        inline const double& data_num_tmp(int i) const { return data_num_tmps_.at(i); }

        inline const ResultFit2D& result() const { return result_; }

    protected :
        void clear();

        std::tuple<double, std::vector<std::array<double, 2>>> build_data(TH2D* hist);
        bool fit();

    private :
        bool hist_build_;
        TAxis hist_xaxis_;
        TAxis hist_yaxis_;
        std::string hist_xtitle_;
        std::string hist_ytitle_;
        std::string hist_ztitle_;

        std::string data_name_;
        int         data_ndimx_;
        int         data_ndimy_;
        int         data_ntmp_;

        std::vector<TH2D*> htmps_;
        TH2D*              hsmp_;
        TH2D*              href_;

        std::vector<double> data_num_tmps_;
        double              data_num_smp_;
        double              data_num_ref_;

        std::vector<std::vector<std::array<double, 2>>> data_tmps_;
        std::vector<std::array<double, 2>>              data_smp_;
        std::vector<std::array<double, 2>>              data_ref_;

        ResultFit2D result_;
};

class VirtualDataFit2D : public ceres::CostFunction {
    public :
        VirtualDataFit2D(int ndimx, int ndimy, int ntmp, const std::vector<std::vector<std::array<double, 2>>>& tmps, const std::vector<std::array<double, 2>>& smp) {
            ndimx_ = ndimx;
            ndimy_ = ndimy;
            ntmp_ = ntmp;
            tmps_ = tmps;
            smp_  = smp;

            nres_ = ndimy_*ndimx_;
            npar_ = tmps_.size();
            ndof_ = -npar_;

            has_      = std::vector<bool>(ndimy_*ndimx_, false);
            has_tmps_ = std::vector<std::vector<bool>>(ntmp_, std::vector<bool>(ndimy_*ndimx_, false));
            has_smp_  = std::vector<bool>(ndimy_*ndimx_, false);

            for (int iby = 0; iby < ndimy_; ++iby) {
            for (int ibx = 0; ibx < ndimx_; ++ibx) {
                int idx = iby * ndimx_ + ibx;
                bool has = false;
                for (int it = 0; it < ntmp_; ++it) {
                    has_tmps_.at(it).at(idx) = (tmps_.at(it).at(idx)[0] > 0.0);
                    if (has_tmps_.at(it).at(idx)) has = true;
                }
                has_smp_.at(idx) = (smp_.at(idx)[0] > 0.0);
                if (has_smp_.at(idx)) has = true;
                if (!has) continue;
                has_.at(idx) = true;
                ndof_++;
            }}

            set_num_residuals(nres_);
            mutable_parameter_block_sizes()->clear();
            mutable_parameter_block_sizes()->push_back(npar_);
        }

    public :
        virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const;

        inline const int& nres() const { return nres_; }
        inline const int& npar() const { return npar_; }
        inline const int& ndof() const { return ndof_; }

    protected :
        int ndimx_;
        int ndimy_;
        int ntmp_;

        std::vector<bool>              has_;
        std::vector<std::vector<bool>> has_tmps_;
        std::vector<bool>              has_smp_;

        std::vector<std::vector<std::array<double, 2>>> tmps_;
        std::vector<std::array<double, 2>>              smp_;

        int nres_;
        int npar_;
        int ndof_;
};

#endif // __DataFit2D_H__


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.jgrapht.ext Class Hierarchy (JGraphT : a free Java graph library)
</TITLE>

<META NAME="date" CONTENT="2013-12-17">

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

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.jgrapht.ext

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.jgrapht.ext.DOTExporter<V,E>
org.jgrapht.ext.GmlExporter<V,E>
org.jgrapht.ext.GraphMLExporter<V,E>
org.jgrapht.ext.IntegerEdgeNameProvider<E> (implements org.jgrapht.ext.EdgeNameProvider<E>)

org.jgrapht.ext.IntegerNameProvider<V> (implements org.jgrapht.ext.VertexNameProvider<V>)

org.jgrapht.ext.JGraphModelAdapter.DefaultCellFactory<VV,EE> (implements org.jgrapht.ext.JGraphModelAdapter.CellFactory<VV,EE>, java.io.Serializable)

org.jgrapht.ext.MatrixExporter<V,E>
com.mxgraph.util.mxEventSource

com.mxgraph.view.mxGraph

org.jgrapht.ext.JGraphXAdapter<V,E> (implements org.jgrapht.event.GraphListener<V,E>)

org.jgrapht.ext.StringEdgeNameProvider<E> (implements org.jgrapht.ext.EdgeNameProvider<E>)

org.jgrapht.ext.StringNameProvider<V> (implements org.jgrapht.ext.VertexNameProvider<V>)

javax.swing.undo.UndoableEditSupport

org.jgraph.graph.DefaultGraphModel (implements org.jgraph.graph.GraphModel, java.io.Serializable)

org.jgrapht.ext.JGraphModelAdapter<V,E>

org.jgrapht.ext.VisioExporter<V,E>

Interface Hierarchy

org.jgrapht.ext.ComponentAttributeProvider<T>
org.jgrapht.ext.EdgeNameProvider<E>
org.jgrapht.ext.JGraphModelAdapter.CellFactory<VV,EE>
org.jgrapht.ext.VertexNameProvider<V>

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2013. All rights reserved.


text:
layout: post
title: Android字符串格式化开源库phrase介绍
category: Android
tags: Android
keywords: Android,Phrase
description: ndroid字符串格式化开源库phrase介绍
---
### 引言
   [Phrase](https://github.com/square/phrase)是一个字符串格式化的开源项目,整个项目只有一个类Phrase.java,相比于String.format,通过phrase格式化字符串代码更具可读性。

### phrase项目介绍
- 源码:phrase项目的源代码很简单,里面总共只有一个类:Phrase.java,代码如下:

		package com.eebbk.learnspell.util;

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

		import android.app.Fragment;
		import android.content.Context;
		import android.content.res.Resources;
		import android.text.SpannableStringBuilder;
		import android.view.View;

		public final class Phrase {
		  private final CharSequence pattern;

		  private final Set<String> keys = new HashSet<String>();
		  private final Map<String, CharSequence> keysToValues = new HashMap<String, CharSequence>();

		  private CharSequence formatted;

		  private Token head;

		  private char curChar;
		  private int curCharIndex;

		  private static final int EOF = 0;

		  public static Phrase from(Fragment f, int patternResourceId) {
		    return from(f.getResources(), patternResourceId);
		  }

		  public static Phrase from(View v, int patternResourceId) {
		    return from(v.getResources(), patternResourceId);
		  }

		  public static Phrase from(Context c, int patternResourceId) {
		    return from(c.getResources(), patternResourceId);
		  }

		  public static Phrase from(Resources r, int patternResourceId) {
		    return from(r.getText(patternResourceId));
		  }

		  public static Phrase from(CharSequence pattern) {
		    return new Phrase(pattern);
		  }

		  public Phrase put(String key, CharSequence value) {
		    if (!keys.contains(key)) {
		      throw new IllegalArgumentException("Invalid key: " + key);
		    }
		    if (value == null) {
		      throw new IllegalArgumentException("Null value for '" + key + "'");
		    }
		    keysToValues.put(key, value);

		    formatted = null;
		    return this;
		  }

		  public Phrase put(String key, int value) {
		    if (!keys.contains(key)) {
		      throw new IllegalArgumentException("Invalid key: " + key);
		    }
		    keysToValues.put(key, Integer.toString(value));

		    formatted = null;
		    return this;
		  }

		  public Phrase putOptional(String key, CharSequence value) {
		    return keys.contains(key) ? put(key, value) : this;
		  }

		  public Phrase putOptional(String key, int value) {
		    return keys.contains(key) ? put(key, value) : this;
		  }

		  public CharSequence format() {
		    if (formatted == null) {
		      if (!keysToValues.keySet().containsAll(keys)) {
		        Set<String> missingKeys = new HashSet<String>(keys);
		        missingKeys.removeAll(keysToValues.keySet());
		        throw new IllegalArgumentException("Missing keys: " + missingKeys);
		      }

		      SpannableStringBuilder sb = new SpannableStringBuilder(pattern);
		      for (Token t = head; t != null; t = t.next) {
		        t.expand(sb, keysToValues);
		      }

		      formatted = sb;
		    }
		    return formatted;
		  }

		  @Override
		  public String toString() {
		    return pattern.toString();
		  }

		  private Phrase(CharSequence pattern) {
		    curChar = (pattern.length() > 0) ? pattern.charAt(0) : EOF;
		    this.pattern = pattern;

		    Token prev = null;
		    Token next;
		    while ((next = token(prev)) != null) {
		      if (head == null) head = next;
		      prev = next;
		    }
		  }

		  private Token token(Token prev) {
		    if (curChar == EOF) {
		      return null;
		    }
		    if (curChar == '{') {
		      char nextChar = lookahead();
		      if (nextChar == '{') {
		        return leftCurlyBracket(prev);
		      } else if (nextChar >= 'a' && nextChar <= 'z') {
		        return key(prev);
		      } else {
		        throw new IllegalArgumentException(
		            "Unexpected character '" + nextChar + "'; expected key.");
		      }
		    }
		    return text(prev);
		  }

		  private KeyToken key(Token prev) {
		    StringBuilder sb = new StringBuilder();

		    consume();
		    while ((curChar >= 'a' && curChar <= 'z') || curChar == '_') {
		      sb.append(curChar);
		      consume();
		    }

		    if (curChar != '}') {
		      throw new IllegalArgumentException("Missing closing brace: }");
		    }
		    consume();

		    if (sb.length() == 0) {
		      throw new IllegalArgumentException("Empty key: {}");
		    }

		    String key = sb.toString();
		    keys.add(key);
		    return new KeyToken(prev, key);
		  }

		  private TextToken text(Token prev) {
		    int startIndex = curCharIndex;

		    while (curChar != '{' && curChar != EOF) {
		      consume();
		    }
		    return new TextToken(prev, curCharIndex - startIndex);
		  }

		  private LeftCurlyBracketToken leftCurlyBracket(Token prev) {
		    consume();
		    consume();
		    return new LeftCurlyBracketToken(prev);
		  }

		  private char lookahead() {
		    return curCharIndex < pattern.length() - 1 ? pattern.charAt(curCharIndex + 1) : EOF;
		  }

		  private void consume() {
		    curCharIndex++;
		    curChar = (curCharIndex == pattern.length()) ? EOF : pattern.charAt(curCharIndex);
		  }

		  private abstract static class Token {
		    private final Token prev;
		    private Token next;

		    protected Token(Token prev) {
		      this.prev = prev;
		      if (prev != null) prev.next = this;
		    }

		    abstract void expand(SpannableStringBuilder target, Map<String, CharSequence> data);

		    abstract int getFormattedLength();

		    final int getFormattedStart() {
		      if (prev == null) {
		        return 0;
		      } else {
		        return prev.getFormattedStart() + prev.getFormattedLength();
		      }
		    }
		  }

		  private static class TextToken extends Token {
		    private final int textLength;

		    TextToken(Token prev, int textLength) {
		      super(prev);
		      this.textLength = textLength;
		    }

		    @Override void expand(SpannableStringBuilder target, Map<String, CharSequence> data) {

		    }

		    @Override int getFormattedLength() {
		      return textLength;
		    }
		  }

		  private static class LeftCurlyBracketToken extends Token {
		    LeftCurlyBracketToken(Token prev) {
		      super(prev);
		    }

		    @Override void expand(SpannableStringBuilder target, Map<String, CharSequence> data) {
		      int start = getFormattedStart();
		      target.replace(start, start + 2, "{");
		    }

		    @Override int getFormattedLength() {
		      return 1;
		    }
		  }

		  private static class KeyToken extends Token {
		    private final String key;

		    private CharSequence value;

		    KeyToken(Token prev, String key) {
		      super(prev);
		      this.key = key;
		    }

		    @Override void expand(SpannableStringBuilder target, Map<String, CharSequence> data) {
		      value = data.get(key);

		      int replaceFrom = getFormattedStart();
		      int replaceTo = replaceFrom + key.length() + 2;
		      target.replace(replaceFrom, replaceTo, value);
		    }

		    @Override int getFormattedLength() {
		      return value.length();
		    }
		  }
		}

- 字符串格式化原理
通过阅读Phrase.java的代码可知,它用"{"和"}"将需要格式化的内容包起来,然后用键值对给需要改变的内容传值,包起来的内容为键,值为动态设置的内容,比如:

		"Hi {first_name}, you are {age} years old."

我们要最终的显示内容为:"Hi UperOne, you are 26 years old."这里的first_name和age是键,值为UperOne和26。

### 使用方法
使用起来很简单,通过键值对的方式插值:

		CharSequence parseStr = Phrase.from("Hi {first_name}, you are {age} years old.")
						 .put("first_name", "UperOne")
						 .put("age", "26")
						 .format();

		mParseTxt.setText( parseStr );


text:
using System.Windows;

namespace SharpLib.Wpf.Controls
{
    public class PathConversionEventArgs : RoutedEventArgs
    {
        #region Перечисления

        public enum ConversionMode
        {
            DisplayToEdit,

            EditToDisplay,
        }

        #endregion

        #region Свойства

        /// <summary>
        /// Отображаемое значение (пользовательское представление)
        /// </summary>
        public string DisplayPath { get; set; }

        /// <summary>
        /// Редактируемое значение
        /// </summary>
        public string EditPath { get; set; }

        public ConversionMode Mode { get; private set; }

        public object Root { get; private set; }

        #endregion

        #region Конструктор

        public PathConversionEventArgs(ConversionMode mode, string path, object root, RoutedEvent routedEvent)
            : base(routedEvent)
        {
            Mode = mode;
            DisplayPath = EditPath = path;
            Root = root;
        }

        #endregion
    }

    public delegate void PathConversionEventHandler(object sender, PathConversionEventArgs e);
}


text:
<!DOCTYPE html>

<title>How do I enable student peer review for an assignment?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.assignment" name="description">
<meta content="peer review, peer assessment, peer evaluation" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="../css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I limit access to Lessons page items to groups?

Instructors can limit access (i.e. specify conditional release) to items added to a Lessons page or subpage by group.

Note: The site must have existing groups in order to limit items to groups. See How do I create groups? for more information on creating groups.

Go to Lessons.

Click on the Lessons page title in the Tool Menu to display the page.

Note: The default or blank Lessons page contains text and images that explain the basic functionality of the Lessons tool.

Click Edit.

Click the Edit button for the item you want to restrict to a group or groups.

Click Edit the groups for which this item should be shown.

This will display a list of the site's existing groups.

Select the group(s), then click Update Item.

View item on the page.

Items which are restricted based on specified criteria indicate the criteria in red next to the item, e.g. [Group A]

Note: All items that can be added to a Lessons page can be limited to a selected group (or groups) via the Edit button.


text:
package duy.phuong.handnote.DTO;

/**
 * Created by Phuong on 10/05/2016.
 */
public class SideMenuItem {
    public int mIcon;
    public int mIconFocused;
    public String mTitle;
    public boolean mFocused;

    public SideMenuItem(int Icon, int IconFocused, String Title, boolean State) {
        this.mIcon = Icon;
        this.mIconFocused = IconFocused;
        this.mTitle = Title;
        this.mFocused = State;
    }
}


text:
SPEC_BEGIN(BNDInterfaceBuilderParserSpec)

describe(@"BNDInterfaceBuilderParser", ^{
    __block NSArray *_bindings = nil;
    __block NSError *_error = nil;
    __block BNDInterfaceBuilderParser *parser = nil;

    BNDInterfaceBuilderParser* (^parserWithXIBNamed)(NSString *) = ^BNDInterfaceBuilderParser*(NSString *xibName) {
        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
        NSURL *pathURL = [bundle URLForResource:xibName
                                  withExtension:@"xib"];

        NSXMLDocument *xibDocument = [[NSXMLDocument alloc] initWithContentsOfURL:pathURL
                                                                          options:NSXMLNodePreserveAll
                                                                            error:nil];

        return [BNDInterfaceBuilderParser parserWithXIBDocument:xibDocument];
    };

    context(@"when a xib file has a file owner that has no bindings", ^{
        it(@"should return an array with 0 bindings", ^{
            parser = parserWithXIBNamed(@"Empty");
            [parser parse:^(NSArray *bindings, NSError *error) {
                _bindings = bindings;
                _error = error;
            }];

            [[_error should] beNil];
            [[_bindings should] haveCountOf:0];
        });
    });

    context(@"when a xib file has a suitable file owner", ^{
        it(@"should return a correct number of bindings", ^{
            parser = parserWithXIBNamed(@"ViewControllerWithBinding");
            [parser parse:^(NSArray *bindings, NSError *error) {
                _bindings = bindings;
                _error = error;
            }];

            [[_error should] beNil];
            [[_bindings should] haveCountOf:1];
        });
    });

});

SPEC_END