text:
package scalax.collection.constrained
package mutable

import scala.language.{higherKinds, postfixOps}
import scala.collection.{Set, Iterable}
import scala.collection.generic.{CanBuildFrom, Growable, Shrinkable}
import scala.collection.mutable.{Builder, Cloneable, ListBuffer, Set => MutableSet}
import scala.reflect.runtime.universe._

import scalax.collection.{Graph => CommonGraph, GraphTraversalImpl}
import scalax.collection.GraphEdge.{EdgeLike, EdgeCompanionBase}
import scalax.collection.GraphPredef.{EdgeLikeIn, Param, InParam, OutParam,
                                      NodeParam, OuterNode, InnerNodeParam, OuterEdge, InnerEdgeParam}
import scalax.collection.mutable.{ArraySet, BuilderImpl}
import scalax.collection.config.AdjacencyListArrayConfig

import scalax.collection.constrained.{Graph => CGraph, GraphLike => CGraphLike}
import PreCheckFollowUp._
import generic.GraphConstrainedCompanion
import config.GenConstrainedConfig

class GraphBuilder[N,
                   E[X] <: EdgeLikeIn[X],
                   GC[N,E[X] <: EdgeLikeIn[X]] <: CGraph[N,E] with CGraphLike[N,E,GC]]
      (companion: GraphConstrainedCompanion[GC])
      (implicit edgeT: TypeTag[E[N]],
       config: GenConstrainedConfig)
  extends BuilderImpl[N,E,GC]
{
  def result: This =
    companion.from(nodes, edges)(edgeT, config.asInstanceOf[companion.Config])
}
trait GraphLike[N,
                E[X] <: EdgeLikeIn[X],
               +This[X, Y[X]<:EdgeLikeIn[X]] <: GraphLike[X,Y,This] with Graph[X,Y]]
	extends scalax.collection.mutable.GraphLike[N, E, This]
	with	  scalax.collection.constrained.GraphLike[N, E, This]
  with    Growable  [Param[N,E]]
	with	  Shrinkable[Param[N,E]]
	with	  Cloneable [Graph[N,E]]
  with    Mutable
{ selfGraph: This[N,E] =>
  trait NodeSet extends super.NodeSet {
    /** generic constrained subtraction */
    protected def checkedRemove(node: NodeT, ripple: Boolean): Boolean = {
      def remove = withoutChecks { subtract(node, ripple,  minus, minusEdges) }
      var removed, handle = false
      if (checkSuspended) removed = remove
      else {
        val preCheckResult = preSubtract(node.asInstanceOf[self.NodeT], ripple)
        preCheckResult.followUp match {
          case Complete  => removed = remove
          case PostCheck => removed = remove
            if (removed &&
                ! postSubtract(selfGraph, Set(node), Set.empty[E[N]], preCheckResult)) {
              handle = true
              selfGraph  += node.value
              selfGraph ++= node.edges
            }
          case Abort     => handle = true
        }
      }
      if (handle) onSubtractionRefused(Set(node.asInstanceOf[self.NodeT]),
                                       Set.empty[self.EdgeT], selfGraph)
      removed && ! handle
    }
    override def remove      (node: NodeT) = checkedRemove(node, true)
    override def removeGently(node: NodeT) = checkedRemove(node, false)
  }
  /** generic checked addition */
  protected def checkedAdd[G >: This[N,E]]
            ( contained: => Boolean,
              preAdd:    => PreCheckResult,
              copy:      => G,
              nodes:     => Iterable[N],
              edges:     => Iterable[E[N]] ): This[N,E] =
  { if (contained) this
    else if (checkSuspended) copy.asInstanceOf[This[N,E]]
    else {
      var graph = this
      var handle = false
      val preCheckResult = preAdd
      preCheckResult.followUp match {
        case Complete  => graph = copy.asInstanceOf[This[N,E]]
        case PostCheck => graph = copy.asInstanceOf[This[N,E]]
          if (! postAdd(graph, nodes, edges, preCheckResult)) {
            handle = true
            graph = this
          }
        case Abort     => handle = true
      }
      if (handle) onAdditionRefused(nodes, edges, this)
      graph
    }
  }
  override def + (node: N) =
    checkedAdd (contained = nodes contains Node(node),
                preAdd    = preAdd(node),
                copy      = clone += node,
                nodes     = Set(node),
                edges     = Set.empty[E[N]])

  override def ++=(elems: TraversableOnce[Param[N,E]]): this.type =
  { elems match {
      case elems: Iterable[Param[N,E]] =>
        val p = new Param.Partitions[N,E](elems)
        val inFiltered = p.toInParams.toSet.filter(elem => ! (this contains elem)).toSeq
        var handle = false
        val preCheckResult = preAdd(inFiltered: _*)
        if (preCheckResult.abort)
          handle = true
        else {
          withoutChecks { super.++=(elems) }
          if (preCheckResult.postCheck) {
            val (outerNodes, outerEdges) = (p.toOuterNodes, p.toOuterEdges)
            if (! postAdd(this, outerNodes, outerEdges, preCheckResult)) {
              handle = true
              withoutChecks {
                super.--=(allNodes(outerNodes, outerEdges) map (n => OuterNode(n)))
              }
            }
          }
        }
        if (handle) onAdditionRefused(p.toOuterNodes, p.toOuterEdges, this)

      case _ => throw new IllegalArgumentException("Iterable expected")
    }
    this
  }
  override def --=(elems: TraversableOnce[Param[N,E]]): this.type =
  { lazy val p = partition(elems)
    lazy val (outerNodes, outerEdges) = (p.toOuterNodes.toSet, p.toOuterEdges.toSet)
    def innerNodes =
       (outerNodes.view map (this find _) filter (_.isDefined) map (_.get) force).toSet
    def innerEdges =
       (outerEdges.view map (this find _) filter (_.isDefined) map (_.get) force).toSet

    type C_NodeT = self.NodeT
    type C_EdgeT = self.EdgeT
    var handle = false
    val preCheckResult = preSubtract(innerNodes.asInstanceOf[Set[C_NodeT]],
                                     innerEdges.asInstanceOf[Set[C_EdgeT]], true)
    preCheckResult.followUp match {
      case Complete  => withoutChecks { super.--=(elems) }
      case PostCheck =>
        val subtractables = elems filter (this contains _)
        withoutChecks { super.--=(subtractables) }
        if (! postSubtract(this, outerNodes, outerEdges, preCheckResult)) {
          handle = true
          withoutChecks { super.++=(subtractables) }
        }
      case Abort     => handle = true
    }
    if (handle) onSubtractionRefused(innerNodes.asInstanceOf[Set[C_NodeT]],
                                     innerEdges.asInstanceOf[Set[C_EdgeT]], this)
    this
  }
}

import scalax.collection.constrained.generic.{MutableGraphCompanion}

trait Graph[N, E[X] <: EdgeLikeIn[X]]
	extends	scalax.collection.mutable.Graph[N,E]
  with    scalax.collection.constrained.Graph[N,E]
	with	  GraphLike[N, E, Graph]
{
  override def empty: Graph[N,E] = Graph.empty[N,E](edgeT, config)
}
object Graph
  extends MutableGraphCompanion[Graph]
{
  override def empty[N, E[X] <: EdgeLikeIn[X]](implicit edgeT: TypeTag[E[N]],
                                               config: Config): Graph[N,E] =
    DefaultGraphImpl.empty[N,E](edgeT, config)

  override protected[collection]
  def fromUnchecked[N, E[X] <: EdgeLikeIn[X]]
     (nodes: Iterable[N],
      edges: Iterable[E[N]])
     (implicit edgeT: TypeTag[E[N]],
      config: Config): DefaultGraphImpl[N,E] =
    DefaultGraphImpl.fromUnchecked[N,E](nodes, edges)(edgeT, config)

  override def from [N, E[X] <: EdgeLikeIn[X]]
     (nodes: Iterable[N],
      edges: Iterable[E[N]])
     (implicit edgeT: TypeTag[E[N]],
      config: Config): Graph[N,E] =
    DefaultGraphImpl.from[N,E](nodes, edges)(edgeT, config)

  // TODO: canBuildFrom
}
abstract class DefaultGraphImpl[N, E[X] <: EdgeLikeIn[X]]
   (iniNodes: Iterable[N]    = Set[N](),
    iniEdges: Iterable[E[N]] = Set[E[N]]())
   (implicit override val edgeT: TypeTag[E[N]],
    _config: DefaultGraphImpl.Config with GenConstrainedConfig with AdjacencyListArrayConfig)
  extends Graph[N,E]
  with    AdjacencyListGraph[N,E,DefaultGraphImpl]
  with    GraphTraversalImpl[N,E]
{
  @transient override final val graphCompanion = DefaultGraphImpl
  protected type Config = DefaultGraphImpl.Config
  override final def config = _config.asInstanceOf[graphCompanion.Config with Config]

  class NodeSet extends super[AdjacencyListGraph].NodeSet with super[Graph].NodeSet
  @inline final def newNodeSet: NodeSetT = new NodeSet
  override final val nodes = newNodeSet
  override final val edges = new EdgeSet
  initialize(iniNodes, iniEdges)

  @inline final override def empty = DefaultGraphImpl.empty(edgeT, config)
  @inline final override def clone(): this.type = {
    graphCompanion.from[N,E](nodes.toOuter, edges.toOuter)(
                             edgeT, config).asInstanceOf[this.type]
  }
  @SerialVersionUID(8082L)
  protected class NodeBase(value: N, hints: ArraySet.Hints)
    extends InnerNodeImpl(value, hints)
    with    InnerNodeTraversalImpl
  type NodeT = NodeBase
  @inline final protected def newNodeWithHints(n: N, h: ArraySet.Hints) = new NodeT(n, h)
}
object DefaultGraphImpl extends MutableGraphCompanion[DefaultGraphImpl]
{
  override def empty[N, E[X] <: EdgeLikeIn[X]](implicit edgeT: TypeTag[E[N]],
                                               config: Config) =
    from(Set.empty[N], Set.empty[E[N]])(edgeT, config)

  override protected[collection]
  def fromUnchecked[N, E[X] <: EdgeLikeIn[X]](nodes: Iterable[N],
                                              edges: Iterable[E[N]])
                                             (implicit edgeT: TypeTag[E[N]],
                                              config: Config): DefaultGraphImpl[N,E] =
    new UserConstrainedGraphImpl[N,E](nodes, edges)(edgeT, config)

  override def from [N, E[X] <: EdgeLikeIn[X]]
     (nodes: Iterable[N],
      edges: Iterable[E[N]])
     (implicit edgeT: TypeTag[E[N]],
      config: Config) : DefaultGraphImpl[N,E] =
  { val existElems = nodes.nonEmpty || edges.nonEmpty
    var preCheckResult = PreCheckResult(Abort)
    if (existElems) {
      val emptyGraph = empty[N,E](edgeT, config)
      val constraint = config.constraintCompanion(emptyGraph)
      preCheckResult = constraint.preCreate(nodes, edges)
      if (preCheckResult.abort) {
        constraint onAdditionRefused (nodes, edges, emptyGraph)
        return emptyGraph
      }
    }
    val newGraph = fromUnchecked[N,E](nodes, edges)(edgeT, config)
    if (existElems) {
      val emptyGraph = empty[N,E](edgeT, config)
      val constraint = config.constraintCompanion(emptyGraph)
      var handle = false
      preCheckResult.followUp match {
        case Complete  =>
        case PostCheck => handle = ! constraint.postAdd(newGraph, nodes, edges, preCheckResult)
        case Abort     => handle = true
      }
      if (handle) {
        constraint.onAdditionRefused(nodes, edges, newGraph)
        emptyGraph
      } else
        newGraph
    } else
      newGraph
  }
  // TODO canBuildFrom
}
class UserConstrainedGraphImpl[N, E[X] <: EdgeLikeIn[X]]
   (iniNodes: Iterable[N]    = Set.empty[N],
    iniEdges: Iterable[E[N]] = Set.empty[E[N]])
   (implicit override val edgeT: TypeTag[E[N]],
    _config: DefaultGraphImpl.Config)
  extends DefaultGraphImpl    [N,E](iniNodes, iniEdges)(edgeT, _config)
  with    UserConstrainedGraph[N,E]
{
  final override val self = this
  final override val constraintFactory = config.constraintCompanion
  final override val constraint  = constraintFactory(this)
}


text:
"""This module implements the "zfs allow" and "zfs unallow" subcommands.
The only public interface is the zfs.allow.do_allow() function."""

import zfs.util
import zfs.dataset
import optparse
import sys
import pwd
import grp
import errno

_ = zfs.util._

class FSPerms(object):
	"""This class represents all the permissions that are set on a
	particular filesystem (not including those inherited)."""

	__slots__ = "create", "sets", "local", "descend", "ld"
	__repr__ = zfs.util.default_repr

	def __init__(self, raw):
		"""Create a FSPerms based on the dict of raw permissions
		from zfs.ioctl.get_fsacl()."""
		# set of perms
		self.create = set()

		# below are { "Ntype name": set(perms) }
		# where N is a number that we just use for sorting,
		# type is "user", "group", "everyone", or "" (for sets)
		# name is a user, group, or set name, or "" (for everyone)
		self.sets = dict()
		self.local = dict()
		self.descend = dict()
		self.ld = dict()

		# see the comment in dsl_deleg.c for the definition of whokey
		for whokey in raw.keys():
			perms = raw[whokey].keys()
			whotypechr = whokey[0].lower()
			ws = whokey[3:]
			if whotypechr == "c":
				self.create.update(perms)
			elif whotypechr == "s":
				nwho = "1" + ws
				self.sets.setdefault(nwho, set()).update(perms)
			else:
				if whotypechr == "u":
					try:
						name = pwd.getpwuid(int(ws)).pw_name
					except KeyError:
						name = ws
					nwho = "1user " + name
				elif whotypechr == "g":
					try:
						name = grp.getgrgid(int(ws)).gr_name
					except KeyError:
						name = ws
					nwho = "2group " + name
				elif whotypechr == "e":
					nwho = "3everyone"
				else:
					raise ValueError(whotypechr)

				if whokey[1] == "l":
					d = self.local
				elif whokey[1] == "d":
					d = self.descend
				else:
					raise ValueError(whokey[1])

				d.setdefault(nwho, set()).update(perms)

		# Find perms that are in both local and descend, and
		# move them to ld.
		for nwho in self.local:
			if nwho not in self.descend:
				continue
			# note: these are set operations
			self.ld[nwho] = self.local[nwho] & self.descend[nwho]
			self.local[nwho] -= self.ld[nwho]
			self.descend[nwho] -= self.ld[nwho]

	@staticmethod
	def __ldstr(d, header):
		s = ""
		for (nwho, perms) in sorted(d.items()):
			# local and descend may have entries where perms
			# is an empty set, due to consolidating all
			# permissions into ld
			if perms:
				s += "\t%s %s\n" % \
				    (nwho[1:], ",".join(sorted(perms)))
		if s:
			s = header + s
		return s

	def __str__(self):
		s = self.__ldstr(self.sets, _("Permission sets:\n"))

		if self.create:
			s += _("Create time permissions:\n")
			s += "\t%s\n" % ",".join(sorted(self.create))

		s += self.__ldstr(self.local, _("Local permissions:\n"))
		s += self.__ldstr(self.descend, _("Descendent permissions:\n"))
		s += self.__ldstr(self.ld, _("Local+Descendent permissions:\n"))
		return s.rstrip()

def args_to_perms(parser, options, who, perms):
	"""Return a dict of raw perms {"whostr" -> {"perm" -> None}}
	based on the command-line input."""

	# perms is not set if we are doing a "zfs unallow <who> <fs>" to
	# remove all of someone's permissions
	if perms:
		setperms = dict(((p, None) for p in perms if p[0] == "@"))
		baseperms = dict(((canonicalized_perm(p), None)
		    for p in perms if p[0] != "@"))
	else:
		setperms = None
		baseperms = None

	d = dict()

	def storeperm(typechr, inheritchr, arg):
		assert typechr in "ugecs"
		assert inheritchr in "ld-"

		def mkwhokey(t):
			return "%c%c$%s" % (t, inheritchr, arg)

		if baseperms or not perms:
			d[mkwhokey(typechr)] = baseperms
		if setperms or not perms:
			d[mkwhokey(typechr.upper())] = setperms

	def decodeid(w, toidfunc, fmt):
		try:
			return int(w)
		except ValueError:
			try:
				return toidfunc(w)[2]
			except KeyError:
				parser.error(fmt % w)

	if options.set:
		storeperm("s", "-", who)
	elif options.create:
		storeperm("c", "-", "")
	else:
		for w in who:
			if options.user:
				id = decodeid(w, pwd.getpwnam,
				    _("invalid user %s"))
				typechr = "u"
			elif options.group:
				id = decodeid(w, grp.getgrnam,
				    _("invalid group %s"))
				typechr = "g"
			elif w == "everyone":
				id = ""
				typechr = "e"
			else:
				try:
					id = pwd.getpwnam(w)[2]
					typechr = "u"
				except KeyError:
					try:
						id = grp.getgrnam(w)[2]
						typechr = "g"
					except KeyError:
						parser.error(_("invalid user/group %s") % w)
			if options.local:
				storeperm(typechr, "l", id)
			if options.descend:
				storeperm(typechr, "d", id)
	return d

perms_subcmd = dict(
    create=_("Must also have the 'mount' ability"),
    destroy=_("Must also have the 'mount' ability"),
    snapshot="",
    rollback="",
    clone=_("""Must also have the 'create' ability and 'mount'
\t\t\t\tability in the origin file system"""),
    promote=_("""Must also have the 'mount'
\t\t\t\tand 'promote' ability in the origin file system"""),
    rename=_("""Must also have the 'mount' and 'create'
\t\t\t\tability in the new parent"""),
    receive=_("Must also have the 'mount' and 'create' ability"),
    allow=_("Must also have the permission that is being\n\t\t\t\tallowed"),
    mount=_("Allows mount/umount of ZFS datasets"),
    share=_("Allows sharing file systems over NFS or SMB\n\t\t\t\tprotocols"),
    send="",
    hold=_("Allows adding a user hold to a snapshot"),
    release=_("Allows releasing a user hold which\n\t\t\t\tmight destroy the snapshot"),
    diff=_("Allows lookup of paths within a dataset,\n\t\t\t\tgiven an object number. Ordinary users need this\n\t\t\t\tin order to use zfs diff"),
    bookmark="",
)

perms_other = dict(
    userprop=_("Allows changing any user property"),
    userquota=_("Allows accessing any userquota@... property"),
    groupquota=_("Allows accessing any groupquota@... property"),
    userused=_("Allows reading any userused@... property"),
    groupused=_("Allows reading any groupused@... property"),
)

def hasset(ds, setname):
	"""Return True if the given setname (string) is defined for this
	ds (Dataset)."""
	# It would be nice to cache the result of get_fsacl().
	for raw in ds.get_fsacl().values():
		for whokey in raw.keys():
			if whokey[0].lower() == "s" and whokey[3:] == setname:
				return True
	return False

def canonicalized_perm(permname):
	"""Return the canonical name (string) for this permission (string).
	Raises ZFSError if it is not a valid permission."""
	if permname in perms_subcmd.keys() or permname in perms_other.keys():
		return permname
	try:
		return zfs.dataset.getpropobj(permname).name
	except KeyError:
		raise zfs.util.ZFSError(errno.EINVAL, permname,
		    _("invalid permission"))

def print_perms():
	"""Print the set of supported permissions."""
	print(_("\nThe following permissions are supported:\n"))
	fmt = "%-16s %-14s\t%s"
	print(fmt % (_("NAME"), _("TYPE"), _("NOTES")))

	for (name, note) in sorted(perms_subcmd.iteritems()):
		print(fmt % (name, _("subcommand"), note))

	for (name, note) in sorted(perms_other.iteritems()):
		print(fmt % (name, _("other"), note))

	for (name, prop) in sorted(zfs.dataset.proptable.iteritems()):
		if prop.visible and prop.delegatable():
			print(fmt % (name, _("property"), ""))

def do_allow():
	"""Implements the "zfs allow" and "zfs unallow" subcommands."""
	un = (sys.argv[1] == "unallow")

	def usage(msg=None):
		parser.print_help()
		print_perms()
		if msg:
			print
			parser.exit("zfs: error: " + msg)
		else:
			parser.exit()

	if un:
		u = _("""unallow [-rldug] <"everyone"|user|group>[,...]
	    [<perm|@setname>[,...]] <filesystem|volume>
	unallow [-rld] -e [<perm|@setname>[,...]] <filesystem|volume>
	unallow [-r] -c [<perm|@setname>[,...]] <filesystem|volume>
	unallow [-r] -s @setname [<perm|@setname>[,...]] <filesystem|volume>""")
		verb = _("remove")
		sstr = _("undefine permission set")
	else:
		u = _("""allow <filesystem|volume>
	allow [-ldug] <"everyone"|user|group>[,...] <perm|@setname>[,...]
	    <filesystem|volume>
	allow [-ld] -e <perm|@setname>[,...] <filesystem|volume>
	allow -c <perm|@setname>[,...] <filesystem|volume>
	allow -s @setname <perm|@setname>[,...] <filesystem|volume>""")
		verb = _("set")
		sstr = _("define permission set")

	parser = optparse.OptionParser(usage=u, prog="zfs")

	parser.add_option("-l", action="store_true", dest="local",
	    help=_("%s permission locally") % verb)
	parser.add_option("-d", action="store_true", dest="descend",
	    help=_("%s permission for descendents") % verb)
	parser.add_option("-u", action="store_true", dest="user",
	    help=_("%s permission for user") % verb)
	parser.add_option("-g", action="store_true", dest="group",
	    help=_("%s permission for group") % verb)
	parser.add_option("-e", action="store_true", dest="everyone",
	    help=_("%s permission for everyone") % verb)
	parser.add_option("-c", action="store_true", dest="create",
	    help=_("%s create time permissions") % verb)
	parser.add_option("-s", action="store_true", dest="set", help=sstr)
	if un:
		parser.add_option("-r", action="store_true", dest="recursive",
		    help=_("remove permissions recursively"))

	if len(sys.argv) == 3 and not un:
		# just print the permissions on this fs

		if sys.argv[2] == "-h":
			# hack to make "zfs allow -h" work
			usage()
		ds = zfs.dataset.Dataset(sys.argv[2], snaps=False)

		p = dict()
		for (fs, raw) in ds.get_fsacl().items():
			p[fs] = FSPerms(raw)

		for fs in sorted(p.keys(), reverse=True):
			s = _("---- Permissions on %s ") % fs
			print(s + "-" * (70-len(s)))
			print(p[fs])
		return

	(options, args) = parser.parse_args(sys.argv[2:])

	if sum((bool(options.everyone), bool(options.user),
	    bool(options.group))) > 1:
		parser.error(_("-u, -g, and -e are mutually exclusive"))

	def mungeargs(expected_len):
		if un and len(args) == expected_len-1:
			return (None, args[expected_len-2])
		elif len(args) == expected_len:
			return (args[expected_len-2].split(","),
			    args[expected_len-1])
		else:
			usage(_("wrong number of parameters"))

	if options.set:
		if options.local or options.descend or options.user or \
		    options.group or options.everyone or options.create:
			parser.error(_("invalid option combined with -s"))
		if args[0][0] != "@":
			parser.error(_("invalid set name: missing '@' prefix"))

		(perms, fsname) = mungeargs(3)
		who = args[0]
	elif options.create:
		if options.local or options.descend or options.user or \
		    options.group or options.everyone or options.set:
			parser.error(_("invalid option combined with -c"))

		(perms, fsname) = mungeargs(2)
		who = None
	elif options.everyone:
		if options.user or options.group or \
		    options.create or options.set:
			parser.error(_("invalid option combined with -e"))

		(perms, fsname) = mungeargs(2)
		who = ["everyone"]
	else:
		(perms, fsname) = mungeargs(3)
		who = args[0].split(",")

	if not options.local and not options.descend:
		options.local = True
		options.descend = True

	d = args_to_perms(parser, options, who, perms)

	ds = zfs.dataset.Dataset(fsname, snaps=False)

	if not un and perms:
		for p in perms:
			if p[0] == "@" and not hasset(ds, p):
				parser.error(_("set %s is not defined") % p)

	ds.set_fsacl(un, d)
	if un and options.recursive:
		for child in ds.descendents():
			child.set_fsacl(un, d)

redpajama_set_name: RedPajamaGithub


text:
require 'blankslate'

class FileBuilder < BlankSlate
  def self.define(&block)
    new(&block)
  end

  define_method(:_instance_exec, find_hidden_method(:instance_exec))

  def initialize(&block)
    @main = block if block_given?
    @files = {}
    @lines = []
    @indent = ''
    @partials = {}
  end

  def build(data = {})
    _instance_exec(data, &@main)
    @files
  end

  def file(name)
    yield self
    @files[name] = @lines
    @lines = []
  end

  def block(first_line, last_line = nil)
    ln(first_line)
    @indent += '  '
    yield self
    @indent = @indent[0..-3]
    ln(last_line) unless last_line.nil?
  end

  def ln(line = nil)
    @lines << (line.nil? ? '' : "#{@indent}#{line}")
  end

  def partial(name, objects = nil, &block)
    if block_given?
      @partials[name] = block
    else
      partial = @partials[name] or raise "Missing partial: #{name.inspect}"
      Array(objects).each { |object| partial.call(object) }
    end
  end
end

require "file_builder/version"


text:
package alluxio.client.block.stream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;

import alluxio.ClientContext;
import alluxio.ConfigurationRule;
import alluxio.ConfigurationTestUtils;
import alluxio.conf.InstancedConfiguration;
import alluxio.conf.PropertyKey;
import alluxio.client.file.FileSystemContext;
import alluxio.client.file.options.OutStreamOptions;
import alluxio.grpc.Chunk;
import alluxio.grpc.RequestType;
import alluxio.grpc.WriteRequest;
import alluxio.resource.CloseableResource;
import alluxio.util.ThreadFactoryUtils;
import alluxio.util.io.BufferUtils;
import alluxio.wire.WorkerNetAddress;

import com.google.protobuf.ByteString;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.StreamObserver;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@RunWith(PowerMockRunner.class)
@PrepareForTest({FileSystemContext.class, WorkerNetAddress.class})
public final class GrpcDataWriterTest {
  private static final Logger LOG = LoggerFactory.getLogger(GrpcDataWriterTest.class);

  private static final int CHUNK_SIZE = 1024;
  private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(4,
      ThreadFactoryUtils.build("test-executor-%d", true));

  private static final Random RANDOM = new Random();
  private static final long BLOCK_ID = 1L;
  private static final int TIER = 0;

  private FileSystemContext mContext;
  private WorkerNetAddress mAddress;
  private BlockWorkerClient mClient;
  private ClientCallStreamObserver<WriteRequest> mRequestObserver;
  private InstancedConfiguration mConf = ConfigurationTestUtils.defaults();
  private ClientContext mClientContext;

  @Rule
  public ConfigurationRule mConfigurationRule =
      new ConfigurationRule(PropertyKey.USER_STREAMING_WRITER_CHUNK_SIZE_BYTES,
          String.valueOf(CHUNK_SIZE), mConf);

  @Before
  public void before() throws Exception {
    mClientContext = ClientContext.create(mConf);

    mContext = PowerMockito.mock(FileSystemContext.class);
    mAddress = mock(WorkerNetAddress.class);

    mClient = mock(BlockWorkerClient.class);
    mRequestObserver = mock(ClientCallStreamObserver.class);
    when(mContext.acquireBlockWorkerClient(mAddress)).thenReturn(
        new NoopClosableResource<>(mClient));
    when(mContext.getClientContext()).thenReturn(mClientContext);
    when(mContext.getClusterConf()).thenReturn(mConf);
    when(mClient.writeBlock(any(StreamObserver.class))).thenReturn(mRequestObserver);
    when(mRequestObserver.isReady()).thenReturn(true);
  }

  @After
  public void after() throws Exception {
    mClient.close();
  }

  /**
   * Writes an empty file.
   */
  @Test(timeout = 1000 * 60)
  public void writeEmptyFile() throws Exception {
    long checksumActual;
    try (DataWriter writer = create(10)) {
      checksumActual = verifyWriteRequests(mClient, 0, 10);
    }
    assertEquals(0, checksumActual);
  }

  /**
   * Writes a file with file length matches what is given and verifies the checksum of the whole
   * file.
   */
  @Test(timeout = 1000 * 60)
  public void writeFullFile() throws Exception {
    long checksumActual;
    Future<Long> checksumExpected;
    long length = CHUNK_SIZE * 1024 + CHUNK_SIZE / 3;
    try (DataWriter writer = create(length)) {
      checksumExpected = writeFile(writer, length, 0, length - 1);
      checksumExpected.get();
      checksumActual = verifyWriteRequests(mClient, 0, length - 1);
    }
    assertEquals(checksumExpected.get().longValue(), checksumActual);
  }

  /**
   * Writes a file with file length matches what is given and verifies the checksum of the whole
   * file.
   */
  @Test(timeout = 1000 * 60)
  public void writeFileChecksumOfPartialFile() throws Exception {
    long checksumActual;
    Future<Long> checksumExpected;
    long length = CHUNK_SIZE * 1024 + CHUNK_SIZE / 3;
    try (DataWriter writer = create(length)) {
      checksumExpected = writeFile(writer, length, 10, length / 3);
      checksumExpected.get();
      checksumActual = verifyWriteRequests(mClient, 10, length / 3);
    }
    assertEquals(checksumExpected.get().longValue(), checksumActual);
  }

  /**
   * Writes a file with unknown length.
   */
  @Test(timeout = 1000 * 60)
  public void writeFileUnknownLength() throws Exception {
    long checksumActual;
    Future<Long> checksumExpected;
    long length = CHUNK_SIZE * 1024;
    try (DataWriter writer = create(Long.MAX_VALUE)) {
      checksumExpected = writeFile(writer, length, 10, length / 3);
      checksumExpected.get();
      checksumActual = verifyWriteRequests(mClient, 10, length / 3);
    }
    assertEquals(checksumExpected.get().longValue(), checksumActual);
  }

  /**
   * Writes lots of chunks.
   */
  @Test(timeout = 1000 * 60)
  public void writeFileManyChunks() throws Exception {
    long checksumActual;
    Future<Long> checksumExpected;
    long length = CHUNK_SIZE * 30000 + CHUNK_SIZE / 3;
    try (DataWriter writer = create(Long.MAX_VALUE)) {
      checksumExpected = writeFile(writer, length, 10, length / 3);
      checksumExpected.get();
      checksumActual = verifyWriteRequests(mClient, 10, length / 3);
    }
    assertEquals(checksumExpected.get().longValue(), checksumActual);
  }

  @Test
  public void closedBlockWorkerClientTest() throws IOException {
    CloseableResource<BlockWorkerClient> resource = Mockito.mock(CloseableResource.class);
    when(resource.get()).thenReturn(mClient);
    FileSystemContext context = PowerMockito.mock(FileSystemContext.class);
    when(context.acquireBlockWorkerClient(any(WorkerNetAddress.class))).thenReturn(resource);
    when(context.getClusterConf()).thenReturn(mConf);
    mConf.set(PropertyKey.USER_STREAMING_WRITER_CLOSE_TIMEOUT, "1");
    GrpcDataWriter writer = GrpcDataWriter.create(context, mAddress, BLOCK_ID, 0,
        RequestType.ALLUXIO_BLOCK,
        OutStreamOptions.defaults(mClientContext).setWriteTier(0));
    verify(resource, times(0)).close();
    verifyWriteRequests(mClient, 0, 0);
    writer.close();
    verify(resource, times(1)).close();
  }

  /**
   * Creates a {@link DataWriter}.
   *
   * @param length the length
   * @return the data writer instance
   */
  private DataWriter create(long length) throws Exception {
    DataWriter writer =
        GrpcDataWriter.create(mContext, mAddress, BLOCK_ID, length,
            RequestType.ALLUXIO_BLOCK,
            OutStreamOptions.defaults(mClientContext).setWriteTier(TIER));
    return writer;
  }

  /**
   * Writes chunks of data via the given data writer and returns a checksum for a region of the data
   * written.
   *
   * @param length the length
   * @param start the start position to calculate the checksum
   * @param end the end position to calculate the checksum
   * @return the checksum
   */
  private Future<Long> writeFile(final DataWriter writer, final long length,
      final long start, final long end) throws Exception {
    return EXECUTOR.submit(new Callable<Long>() {
      @Override
      public Long call() throws IOException {
        try {
          long checksum = 0;
          long pos = 0;

          long remaining = length;
          while (remaining > 0) {
            int bytesToWrite = (int) Math.min(remaining, CHUNK_SIZE);
            byte[] data = new byte[bytesToWrite];
            RANDOM.nextBytes(data);
            ByteBuf buf = Unpooled.wrappedBuffer(data);
            try {
              writer.writeChunk(buf);
            } catch (Exception e) {
              fail(e.getMessage());
              throw e;
            }
            remaining -= bytesToWrite;

            for (int i = 0; i < data.length; i++) {
              if (pos >= start && pos <= end) {
                checksum += BufferUtils.byteToInt(data[i]);
              }
              pos++;
            }
          }
          return checksum;
        } catch (Throwable throwable) {
          LOG.error("Failed to write file.", throwable);
          fail();
          throw throwable;
        }
      }
    });
  }

  /**
   * Verifies the packets written. After receiving the last packet, it will also send an EOF to
   * the client.
   *
   * @param checksumStart the start position to calculate the checksum
   * @param checksumEnd the end position to calculate the checksum
   * @return the checksum of the data read starting from checksumStart
   */
  private long verifyWriteRequests(final BlockWorkerClient client, final long checksumStart,
      final long checksumEnd) {
    try {
      ArgumentCaptor<WriteRequest> requestCaptor = ArgumentCaptor.forClass(WriteRequest.class);
      verify(mRequestObserver, atLeastOnce()).onNext(requestCaptor.capture());
      ArgumentCaptor<StreamObserver> captor = ArgumentCaptor.forClass(StreamObserver.class);
      verify(mClient).writeBlock(captor.capture());
      captor.getValue().onCompleted();
      long checksum = 0;
      long pos = 0;
      for (WriteRequest request : requestCaptor.getAllValues()) {
        validateWriteRequest(request, pos);
        if (request.hasChunk()) {
          Chunk chunk = request.getChunk();
          assertTrue(chunk.hasData());
          ByteString buf = chunk.getData();
          for (byte b : buf.toByteArray()) {
            if (pos >= checksumStart && pos <= checksumEnd) {
              checksum += BufferUtils.byteToInt(b);
            }
            pos++;
          }
        }
      }
      return checksum;
    } catch (Throwable throwable) {
      LOG.error("Failed to verify write requests.", throwable);
      fail();
      throw throwable;
    }
  }

  /**
   * Validates the read request sent.
   *
   * @param request the request
   * @param offset the offset
   */
  private void validateWriteRequest(WriteRequest request, long offset) {
    if (request.hasCommand()) {
      assertEquals(BLOCK_ID, request.getCommand().getId());
      assertEquals(offset, request.getCommand().getOffset());
    } else {
      assertTrue(request.hasChunk());
    }
  }
}


text:
#include "elog.h"
#include <stdio.h>
#include <stm32f10x_conf.h>

/**
 * EasyLogger port initialize
 *
 * @return result
 */
ElogErrCode elog_port_init(void) {
    ElogErrCode result = ELOG_NO_ERR;

    return result;
}

/**
 * output log port interface
 *
 * @param log output of log
 * @param size log size
 */
void elog_port_output(const char *log, size_t size) {
    /* output to terminal */
    printf("%.*s", size, log);
    //TODO output to flash
}

/**
 * output lock
 */
void elog_port_output_lock(void) {
    __disable_irq();
}

/**
 * output unlock
 */
void elog_port_output_unlock(void) {
    __enable_irq();
}

/**
 * get current time interface
 *
 * @return current time
 */
const char *elog_port_get_time(void) {
    return "10:08:12";
}

/**
 * get current process name interface
 *
 * @return current process name
 */
const char *elog_port_get_p_info(void) {
    return "pid:1008";
}

/**
 * get current thread name interface
 *
 * @return current thread name
 */
const char *elog_port_get_t_info(void) {
    return "tid:24";
}


text:
+ Add Data Bucket

Edit Bucket Settings

  <form
     novalidate
     ng-submit="bucketsDetailsDialogCtl.onSubmit()"
     mn-spinner="bucketsDetailsDialogCtl.viewLoading || !bucketsDetailsDialogCtl.validationKeeper.result">

      Cancel
      <button type="submit">
        Add Bucket
        Save Changes
      </button>

  </form>


text:
package org.apache.polygene.sample.swing.binding;

import org.apache.polygene.bootstrap.Assembler;
import org.apache.polygene.bootstrap.AssemblyException;
import org.apache.polygene.bootstrap.ModuleAssembly;
import org.apache.polygene.sample.swing.binding.adapters.StringToTextFieldAdapterService;
import org.apache.polygene.sample.swing.binding.internal.BoundProperty;
import org.apache.polygene.sample.swing.binding.internal.StateInvocationHandler;

public class SwingBindingAssembler
    implements Assembler
{

    @Override
    public void assemble( ModuleAssembly module )
    {
        module.objects( StateModel.class, StateInvocationHandler.class, BoundProperty.class );
        addStringToTextFieldAdapter( module );
    }

    protected void addStringToTextFieldAdapter( ModuleAssembly module )
        throws AssemblyException
    {
        module.services( StringToTextFieldAdapterService.class );
    }
}


text:
cask :v1 => 'quicklook-pfm' do
  version '1.1'
  sha256 '53308ac3d7f0f8ed02adb2feff282764fdeadb32352b0776caeaec3d6a514333'

  # googlecode.com is the official download host per the vendor homepage
  url "https://quicklook-pfm.googlecode.com/files/quicklook-pfm-#{version}.zip"
  name 'quicklook-pfm'
  homepage 'https://github.com/lnxbil/quicklook-pfm'
  license :oss

  qlplugin 'Quicklook-PFM.qlgenerator'
end


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
        'ngRoute',
        'getStateNames',
        'myApp.view1',
        'myApp.view2',
        'myApp.version'
    ])
    .config(['$routeProvider', function ($routeProvider) {
        console.log("in Route provider");
        $routeProvider
            .when('/view1', {
                templateUrl: 'view1/view1.html',
                controller: 'View1Ctrl'
            })
            .otherwise({redirectTo: '/view2'});
    }]);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="38dp"
    android:background="@drawable/toast_bg"
    android:gravity="center" >
    <TextView
        android:id="@+id/toast_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="@dimen/toast_word_size"
        android:textColor="@color/white"/>

</LinearLayout>


text:
<?php

namespace modules\users\models;

use modules\users\models\frontend\User;
use modules\users\Module;
use modules\users\traits\ModuleTrait;
use Yii;
use yii\base\Model;

class PerformerRegForm extends Model
{

    use ModuleTrait;

    public $login;
    public $password;
    public $repassword;
    public $email;
    public $email_for_order;
    public $company_name;
    public $company_about;
    public $company_specialization;
    public $company_count_years;
    public $site;
    public $phone_country_code_1;
    public $phone_city_code_1;
    public $phone_num_1;
    public $phone_country_code_2;
    public $phone_city_code_2;
    public $phone_num_2;
    public $country;
    public $state;
    public $city;
    public $street;
    public $house;
    public $corpus;
    public $building;
    public $logo;
    public $examples_of_works = [];
    public $additional_info;
    public $confirm;
    public $captcha;
    public $role = 'performer';

    public function rules()
    {
        return [
            ['confirm', 'filter', 'filter' => function ($v) {
                return $v ? $v : null;
            }],
            [['company_name', 'email', 'password', 'repassword', 'login'], 'trim'],
            [['password', 'repassword'], 'string', 'min' => 6, 'max' => 30],
            [['company_name', 'login'], 'string', 'min' => 2, 'max' => 64],
            [['email'], 'string', 'max' => 100],
            [['confirm'], 'required', 'message'=>'Необходимо согласиться с правилами использования сервиса'],
            [['captcha', 'login', 'password', 'repassword', 'company_name', 'email', 'site',
                'phone_country_code_1', 'phone_city_code_1', 'phone_num_1',
                'phone_country_code_2', 'phone_city_code_2', 'phone_num_2',
                'city', 'street', 'email_for_order', 'company_specialization', 'company_count_years', 'company_about', 'additional_info',
            ], 'required'],
            [['house', 'building', 'company_count_years'], 'number'],
            [['corpus'], 'string', 'max' => 5],
            ['captcha', 'captcha', 'captchaAction'=>'/site/default/captcha'],
            ['repassword', 'compare', 'compareAttribute' => 'password'],
            [['email', 'email_for_order'], 'email'],
            [['login', 'email'], 'unique', 'targetClass' => User::className()],
            [['phone_country_code_1', 'phone_city_code_1', 'phone_num_1', 'phone_country_code_2', 'phone_city_code_2', 'phone_num_2'], 'number'],
            [['role', 'login', 'examples_of_works', 'additional_info', 'company_count_years', 'company_about'], 'safe'],
            [['logo'], 'file', 'mimeTypes'=> ['image/png', 'image/jpeg', 'image/gif'], 'wrongMimeType'=>Module::t('image', 'IMAGE_MESSAGE_FILE_TYPES').' jpg, png, gif'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'performer_registration' => Module::t('REGISTRATION_FORM_PERFORMER', 'NAME_OF_PERFORMER_REG_FORM'),
            'registration_date' => Module::t('REGISTRATION_FORM_PERFORMER', 'DATE_OF_REGISTRATION_PERFORMER_REG_FORM'),
            'login' => Module::t('REGISTRATION_FORM_PERFORMER', 'LOGIN_PERFORMER_REG_FORM'),
            'password' => Module::t('REGISTRATION_FORM_PERFORMER', 'PASSWORD1_PERFORMER_REG_FORM'),
            'repassword' => Module::t('REGISTRATION_FORM_PERFORMER', 'PASSWORD2_PERFORMER_REG_FORM'),
            'company_name' => Module::t('REGISTRATION_FORM_PERFORMER', 'COMPANY_NAME_PERFORMER_REG_FORM'),
            'company_about' => Module::t('REGISTRATION_FORM_PERFORMER', 'ABOUT_COMPANY_PERFORMER_REG_FORM'),
            'company_specialization' => Module::t('REGISTRATION_FORM_PERFORMER', 'COMPANY_SPECIALIZATION_PERFORMER_REG_FORM'),
            'company_count_years' => Module::t('REGISTRATION_FORM_PERFORMER', 'YEARS_IN_THE_MARKET_PERFORMER_REG_FORM'),
            'site' => Module::t('REGISTRATION_FORM_PERFORMER', 'COMPANY_SITE_PERFORMER_REG_FORM'),
            'email' => Module::t('REGISTRATION_FORM_PERFORMER', 'EMAIL_PERFORMER_REG_FORM'),
            'email_for_order' => Module::t('REGISTRATION_FORM_PERFORMER', 'EMAIL_FOR_OBTAINING_ORDERS_REG_FORM'),
            'phone_country_code_1' => Module::t('REGISTRATION_FORM_PERFORMER', 'COUNTRY_PHONE_CODE1_PERFORMER_REG_FORM'),
            'phone_city_code_1' => Module::t('REGISTRATION_FORM_PERFORMER', 'CITY_PHONE_CODE1_PERFORMER_REG_FORM'),
            'phone_num_1' => Module::t('REGISTRATION_FORM_PERFORMER', 'PHONE_NUMBER1_PERFORMER_REG_FORM'),
            'phone_1' => Module::t('REGISTRATION_FORM_PERFORMER', 'PHONE1_PERFORMER_REG_FORM'),
            'phone_country_code_2' => Module::t('REGISTRATION_FORM_PERFORMER', 'COUNTRY_PHONE_CODE2_PERFORMER_REG_FORM'),
            'phone_city_code_2' => Module::t('REGISTRATION_FORM_PERFORMER', 'CITY_PHONE_CODE2_PERFORMER_REG_FORM'),
            'phone_num_2' => Module::t('REGISTRATION_FORM_PERFORMER', 'PHONE_NUMBER2_PERFORMER_REG_FORM'),
            'phone_2' => Module::t('REGISTRATION_FORM_PERFORMER', 'PHONE2_PERFORMER_REG_FORM'),
            'country' => Module::t('ALL_INTERFACES', 'TERRITORIAL_FILTER_COUNTRY'),
            'state' => Module::t('ALL_INTERFACES', 'TERRITORIAL_FILTER_STATE'),
            'city' => Module::t('ALL_INTERFACES', 'TERRITORIAL_FILTER_CITY'),
            'street' => Module::t('REGISTRATION_FORM_PERFORMER', 'STREET_PERFORMER_REG_FORM'),
            'house' => Module::t('REGISTRATION_FORM_PERFORMER', 'HOUSE_PERFORMER_REG_FORM'),
            'building' => Module::t('REGISTRATION_FORM_PERFORMER', 'BUILDING_PERFORMER_REG_FORM'),
            'corpus' => Module::t('REGISTRATION_FORM_PERFORMER', 'STRUCTURE_PERFORMER_REG_FORM'),
            'logo' => Module::t('REGISTRATION_FORM_PERFORMER', 'COMPANY_LOGO_PERFORMER_REG_FORM'),
            'confirm' => Module::t('REGISTRATION_FORM_PERFORMER', 'LICENSE_AGREEMENT_PERFORMER_REG_FORM'),
            'captcha' => Module::t('REGISTRATION_FORM_PERFORMER', 'ENTER_SYMBOLS_FROM_THE_PICTURE_PERFORMER_REG_FORM'),
            'directions' => Module::t('REGISTRATION_FORM_PERFORMER', 'COMPANY_ACTIVITIES_PERFORMER_REG_FORM'),
            'examples_of_works' => Module::t('REGISTRATION_FORM_PERFORMER', 'LOAD_FOTO_EXAMPLES_OF_WORKS_PERFOMER_REG_FORM'),
            'additional_info' => Module::t('REGISTRATION_FORM_PERFORMER', 'ADDITIONAL_INFO'),
            'customer_registration' => Module::t('REGISTRATION_FORM_PERFORMER', 'NAME_OF_PERFORMER_REG_FORM'),
            'cancel_button' => Module::t('REGISTRATION_FORM_PERFORMER', 'CANCEL_BUTTON_PERFORMER_REG_FORM'),
            'submit_button' => Module::t('REGISTRATION_FORM_PERFORMER', 'REGISTRATION_BUTTON_PERFORMER_REG_FORM'),
        ];
    }

    public function scenarios()
    {
        return [
            'ajax' => [
                'login', 'password', 'repassword', 'email', 'email_for_order',
                'company_name', 'company_about','company_specialization','company_count_years','site',
                'phone_country_code_1','phone_city_code_1','phone_num_1','phone_country_code_2','phone_city_code_2','phone_num_2',
                'country', 'state', 'city', 'street', 'house', 'corpus', 'building',
                'examples_of_works',
                'additional_info',
                'confirm',
//                'captcha',
            ],
            'default' => [
                'login', 'password', 'repassword', 'email', 'email_for_order',
                'company_name', 'company_about','company_specialization','company_count_years','site',
                'phone_country_code_1','phone_city_code_1','phone_num_1','phone_country_code_2','phone_city_code_2','phone_num_2',
                'country', 'state', 'city', 'street', 'house', 'corpus', 'building',
                'examples_of_works',
                'additional_info',
                'confirm',
                'captcha',
            ]
        ];
    }
}


text:
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

namespace System.Activities.DurableInstancing
{
    using System;
    using System.Collections.Generic;
    using System.Runtime;
    using System.Runtime.DurableInstancing;
    using System.Xml.Linq;

    [Fx.Tag.XamlVisible(false)]
    public sealed class CreateWorkflowOwnerCommand : InstancePersistenceCommand
    {
        Dictionary<XName, InstanceValue> instanceOwnerMetadata;

        public CreateWorkflowOwnerCommand()
            : base(InstancePersistence.ActivitiesCommandNamespace.GetName("CreateWorkflowOwner"))
        {
        }

        public IDictionary<XName, InstanceValue> InstanceOwnerMetadata
        {
            get
            {
                if (this.instanceOwnerMetadata == null)
                {
                    this.instanceOwnerMetadata = new Dictionary<XName, InstanceValue>();
                }
                return this.instanceOwnerMetadata;
            }
        }

        protected internal override bool IsTransactionEnlistmentOptional
        {
            get
            {
                return this.instanceOwnerMetadata == null || this.instanceOwnerMetadata.Count == 0;
            }
        }

        protected internal override void Validate(InstanceView view)
        {
            if (view.IsBoundToInstanceOwner)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SRCore.AlreadyBoundToOwner));
            }
            InstancePersistence.ValidatePropertyBag(this.instanceOwnerMetadata);
        }
    }
}


text:
import React, { Component } from 'react';
import CurrencyStore from '../stores/CurrencyStore';
import Graph from './Graph.react';
import DateInput from './DateInput.react';
import SelectInput from './SelectInput.react';
import FloatingActiveButton from './FloatingActiveButton.react';
import AppActions from '../actions/AppActions';

/**
 * Retrieve the current data from the CurrencyStore
 */
function getCurrencyState() {
	return CurrencyStore.getCurrency();
}

class CurrencyApp extends Component {
	constructor( props ) {
		super( props );
		this._onChange = this._onChange.bind(this);
	}

	state = getCurrencyState();

	componentDidMount() {
		CurrencyStore.addChangeListener( this._onChange );
		AppActions.refresh();
	}

	componentWillUnmount() {
		CurrencyStore.removeChangeListener( this._onChange );
	}

	_onChange() {
		this.setState( getCurrencyState() );
	}

	_onFirstDateSave( value ) {
		AppActions.update( true, value );
	}

	_onLastDateSave( value ) {
		AppActions.update( false, value );
	}

	render() {
		return (
			<div>
				<Graph
					className = "graph"
					id = "firstDate"
					width = {860}
					height = {300}
					label = { this.state.selected }
					data = { this.state.graphData }
					options = { { scaleBeginAtZero: false } }
				/>
				<SelectInput
					className = "select-input"
					id = "currencyTypes"
					value = { this.state.selected }
					options = { this.state.currency }
					onSave = { AppActions.updateSelected.bind( AppActions ) }
				/>
				<DateInput
					className = "date-input date-input__first"
					inputClassName = "date-input__input"
					labelClassName = "date-input__label"
					labelText = "From:"
					id = "firstDate"
					value = { this.state.getFirstDate() }
					onSave = { AppActions.update.bind( AppActions, true ) }
				/>
				<DateInput
					className = "date-input date-input__last"
					inputClassName = "date-input__input"
					labelClassName = "date-input__label"
					labelText = "To:"
					id = "lastDate"
					value = { this.state.getLastDate() }
					onSave = { AppActions.update.bind( AppActions, false ) }
				/>
				<FloatingActiveButton
					className = "floating-action-button"
					title = "Refresh"
				/>
			</div>
		);
	}
}

export default CurrencyApp;


text:
#include "config.h"
#include "core/editing/SplitTextNodeCommand.h"

#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
#include "core/dom/Text.h"
#include "core/editing/markers/DocumentMarkerController.h"
#include "wtf/Assertions.h"

namespace blink {

SplitTextNodeCommand::SplitTextNodeCommand(PassRefPtrWillBeRawPtr<Text> text, int offset)
    : SimpleEditCommand(text->document())
    , m_text2(text)
    , m_offset(offset)
{
    // NOTE: Various callers rely on the fact that the original node becomes
    // the second node (i.e. the new node is inserted before the existing one).
    // That is not a fundamental dependency (i.e. it could be re-coded), but
    // rather is based on how this code happens to work.
    ASSERT(m_text2);
    ASSERT(m_text2->length() > 0);
    ASSERT(m_offset > 0);
    ASSERT(m_offset < m_text2->length());
}

void SplitTextNodeCommand::doApply()
{
    ContainerNode* parent = m_text2->parentNode();
    if (!parent || !parent->hasEditableStyle())
        return;

    String prefixText = m_text2->substringData(0, m_offset, IGNORE_EXCEPTION);
    if (prefixText.isEmpty())
        return;

    m_text1 = Text::create(document(), prefixText);
    ASSERT(m_text1);
    document().markers().copyMarkers(m_text2.get(), 0, m_offset, m_text1.get(), 0);

    insertText1AndTrimText2();
}

void SplitTextNodeCommand::doUnapply()
{
    if (!m_text1 || !m_text1->hasEditableStyle())
        return;

    ASSERT(m_text1->document() == document());

    String prefixText = m_text1->data();

    m_text2->insertData(0, prefixText, ASSERT_NO_EXCEPTION, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);

    document().markers().copyMarkers(m_text1.get(), 0, prefixText.length(), m_text2.get(), 0);
    m_text1->remove(ASSERT_NO_EXCEPTION);
}

void SplitTextNodeCommand::doReapply()
{
    if (!m_text1 || !m_text2)
        return;

    ContainerNode* parent = m_text2->parentNode();
    if (!parent || !parent->hasEditableStyle())
        return;

    insertText1AndTrimText2();
}

void SplitTextNodeCommand::insertText1AndTrimText2()
{
    TrackExceptionState exceptionState;
    m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), exceptionState);
    if (exceptionState.hadException())
        return;
    m_text2->deleteData(0, m_offset, exceptionState, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
}

DEFINE_TRACE(SplitTextNodeCommand)
{
    visitor->trace(m_text1);
    visitor->trace(m_text2);
    SimpleEditCommand::trace(visitor);
}

} // namespace blink


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">docs/stack/StackHeader.js | ugLayout Documentation API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home
  Manual
  Reference
  Source

  Repository

    <input class="search-input">

CDragHost

CDragHostContainer

CDraggable

CLockState

CLockStateChangeEvent

CRootInjector

CRootLayout

CRootLayoutSerializer

CRootSerializer

CStateContext

CTagUtil

CUgPlugin

IDragEvent

IDropTarget

VLOCK_DRAGGING

VLOCK_RESIZING

VConfigurationRef

VContainerRef

VContextType

VDocumentRef

VElementRef

VPatchRef

VRootConfigRef

VUNALLOCATED

TDragOptions

TDropArea

THighlightCoordinateArgs

EBehaviorSubject

EDocument

EHTMLElement

EObservable

ESubject

ESubscription

XYContainer
CColumn

CRow

CSplitter

CXYContainer

CXYContainerSerializer

CXYItemContainer

CXYItemContainerSerializer

VSPLITTER_SIZE

VMAX_RATIO_DISTRIBUTION_ITERATIONS

commands
CCommand

CMakeVisibleCommand

CMinimizeCommand

di
CForwardRef

CInjector

CToken

IClassProvider

IExistingProvider

IFactoryProvider

IInjectionMetadata

IType

IValueProvider

FforwardRef

FInject

FInjectable

FLazy

FOptional

FSelf

VINJECTABLE_META_KEY

VINJECT_PARAM_KEY

TProvider

TProviderArg

dom
CConfiguredRenderable

CRenderable

CRenderableArea

CRenderableInjector

CRenderer

FMemoizeFrom

VINJECTOR_KEY

TAddChildArgs

TBaseModificationArgs

TRemoveChildArgs

events
CBeforeDestroyEvent

CBusEvent

CCancelAction

CCancellable

CEventBus

TBusEventOptions

layout
CLayoutManipulator

CLayoutSerializer

VLayout

TLayoutConfig

TSerializedLayout

serialization
CGenericSerializer

CSerializerContainer

CSerializer

TSerialized

TSerializerContainerConfig

stack
CStack

CStackHeader

CStackItemCloseEvent

CStackItemContainer

CStackSerializer

CStackTab

CTabCloseEvent

CTabDragEvent

CTabSelectionEvent

VDEFAULT_STACK_HEADER_SIZE

TStackConfig

TStackConfigArgs

TStackItemContainerConfig

TStackTabConfig

TStackTabConfigArgs

stack/controls
CCloseStackControl

CMinimizeStackControl

CStackControl

CStackControlSerializer

stack/tabControls
CCloseTabControl

CTabControl

utils
CDeferred

Fclamp

Fdefaults

Feq

Fget

FisBoolean

FisFunction

FisNumber

FisObject

FisObserver

FisPromise

FisString

FisUndefined

Fnegate

Fpartition

FpropEq

Fround

Vuid

view
CCustomViewHookEvent

CView

CViewContainer

CViewFactory

CViewLinker

CViewManager

CViewSerializer

FViewComponent

FViewInsert

FViewLinkInit

FViewQuery

FViewResolve

FgetDefaultMetadata

VLinkerMetatdataRef

VVIEW_CONFIG_KEY

VVIEW_LINKER_METADATA

VViewComponentRef

view/hooks
CViewHookExecutor

FObserveViewHook

VVIEW_HOOK_METADATA

docs/stack/StackHeader.js

import { VNode } from 'snabbdom/vnode';
import h from 'snabbdom/h';

import { Inject, Injector } from '../di';
import {
  Renderable,
  RenderableInjector,
  ConfiguredRenderable,
  RenderableArea,
  AddChildArgs,
  RemoveChildArgs,
  RenderableConfig
} from '../dom';
import { Stack } from './Stack';
import { Draggable } from '../Draggable';
import { DragHost } from '../DragHost';
import { StackTab, StackTabConfigArgs } from './StackTab';
import { TabCloseEvent } from './TabCloseEvent';
import { TabSelectionEvent } from './TabSelectionEvent';
import { TabDragEvent } from './TabDragEvent';
import { get, isNumber, partition, propEq } from '../utils';
import {
  ConfigurationRef,
  ContainerRef,
  DropTarget,
  DropArea,
  HighlightCoordinateArgs,
  DragEvent,
  RenderableArg
} from '../common';
import { Subject, Observable, BeforeDestroyEvent } from '../events';
import { StackControl, StackControlPosition } from './controls';
import { StackItemContainer } from './StackItemContainer';

export interface StackHeaderConfig extends RenderableConfig {
  size: number;
  distribute: boolean;
  droppable: boolean;
}

export type StackHeaderConfigArgs = {
  [P in keyof StackHeaderConfig]?: StackHeaderConfig[P];
}

export const DEFAULT_STACK_HEADER_SIZE = 25;

export class StackHeader extends Renderable implements DropTarget {
  protected _contentItems: StackTab[] = [];
  private _controls: StackControl[] = [];
  private _config: StackHeaderConfig;
  private _tabAreas: RenderableArea[];

  constructor(
    @Inject(ConfigurationRef) _config: StackHeaderConfigArgs|null,
    @Inject(ContainerRef) protected _container: Stack,
    @Inject(DragHost) protected _dragHost: DragHost
  ) {
    super();

    this._config = Object.assign({
      controls: [],
      size: DEFAULT_STACK_HEADER_SIZE,
      droppable: true,
      distribute: false
    }, _config);
  }

  get width(): number {
    return this._container.isHorizontal ? this._container.width : this._config.size;
  }

  get height(): number {
    return this._container.isHorizontal ? this._config.size : this._container.height;
  }

  get size(): number {
    return get(this._config, 'size', DEFAULT_STACK_HEADER_SIZE);
  }

  get droppable(): boolean {
    return get(this._config, 'droppable', true);
  }

  get isHorizontal(): boolean {
    return this._container.isHorizontal;
  }

  get isDistributed(): boolean {
    return get(this._config, 'distribute', false);
  }

  get controls(): StackControl[] {
    return this._controls.slice(0);
  }

  initialize(): void {
    super.initialize();

    this._dragHost.start
      .takeUntil(this.destroyed)
      .subscribe(this._onDragHostStart.bind(this));

    this._dragHost.dropped
      .takeUntil(this.destroyed)
      .subscribe(this._onDragHostDropped.bind(this));
  }

  addTab(config: StackTabConfigArgs, options: AddChildArgs = {}): StackTab {
    const tab = this.createChild(new ConfiguredRenderable(StackTab, config), [ Draggable ]);

    tab.subscribe(TabSelectionEvent, e => this.emit(e));
    tab.subscribe(TabCloseEvent, e => this.emit(e));
    tab.subscribe(TabDragEvent, e => this.emit(e));

    this.addChild(tab, options);

    return tab;
  }

  addControl(_control: RenderableArg<StackControl>): void {
    this._controls.push(this.createChild(_control));
  }

  isTabActive(tab: StackTab): boolean {
    return this._container.isActiveTab(tab);
  }

  getItemFromTab(tab: StackTab): StackItemContainer|null {
    return this._container.getAtIndex(this.getIndexOf(tab)) as StackItemContainer|null;
  }

  render(): VNode {
    const [ postTabControls, preTabControls ] = partition(
      this._controls.filter(c => c.isActive()),
      propEq('position', StackControlPosition.POST_TAB)
    );

    return h('div.ug-layout__stack-header', {
      style: {
        height: `${this.height}px`,
        width: `${this.width}px`
      }
    },
      [
        h('div.ug-layout__stack-controls', preTabControls.map(c => c.render())),
        h('div.ug-layout__tab-container', this._contentItems.map(tab => tab.render())),
        h('div.ug-layout__stack-controls', postTabControls.map(c => c.render()))
      ]
    );
  }

  isDroppable(): boolean {
    return this.droppable;
  }

  getChildren(): Renderable[] {
    return [
      ...this._controls,
      ...this._contentItems
    ];
  }

  handleDrop(item: Renderable, dropArea: DropArea, e: DragEvent<Renderable>): void {
    const index = this._getIndexFromArea(e.pageX, e.pageY, dropArea.area) + 1;

    if (item instanceof StackItemContainer && this._container.getIndexOf(item) === -1) {
      this._container.addChild(item, { index });
      this._container.setActiveIndex(index);
    }

    this.onDropHighlightExit();
  }

  getHighlightCoordinates(args: HighlightCoordinateArgs): RenderableArea {
    let { pageX, pageY, dragArea, dropArea: { item, area: { x, x2, y, y2, height } } } = args;

    const highlightArea = new RenderableArea(x, dragArea.width + x, y, y2);
    let leftMostTabIndex = this._getIndexFromArea(pageX, pageY, args.dropArea.area);
    let leftMostTabArea = this._tabAreas[leftMostTabIndex];

    if (leftMostTabArea) {
      highlightArea.x = leftMostTabArea.x2;
      highlightArea.x2 = leftMostTabArea.x2 + dragArea.width;
    }

    for (const [ index, tab ] of this._contentItems.entries()) {
      if (!tab.isDragging) {
        tab.element.style.transform = index > leftMostTabIndex ? `translateX(${dragArea.width}px)` : 'translateX(0px)';
      }
    }

    return highlightArea;
  }

  onDropHighlightExit(): void {
    for (const tab of this._contentItems) {
      if (!tab.isDragging) {
        tab.element.style.transform = 'translateX(0px)';
      }
    }
  }

  getOffsetXForTab(tab: StackTab): number {
    if (this.isHorizontal) {
      return this._contentItems.slice(0, this.getIndexOf(tab)).reduce((result, tab) => result + tab.width, this.offsetX);
    }

    return this.offsetX;
  }

  getOffsetYForTab(tab: StackTab): number {
    if (!this.isHorizontal) {
      return this._contentItems.slice(0, this.getIndexOf(tab)).reduce((result, tab) => result + tab.height, this.offsetY);
    }

    return this.offsetY;
  }

  private _onDragHostStart(): void {
    this._tabAreas = this._contentItems.map(tab => tab.getArea());
  }

  private _onDragHostDropped(): void {
    this._tabAreas = [];
  }

  private _getIndexFromArea(pageX: number, pageY: number, area: RenderableArea): number {
    let { x, y } = area;

    const deltaX = pageX - x;
    const deltaY = pageY - y;

    let result = -1;

    for (const [ index, tabArea ] of this._tabAreas.entries()) {
      if (deltaX >= (tabArea.x - x) + (tabArea.width / 2)) {
        result = index;
      }
    }

    return result;
  }
}

  Generated by ESDoc(0.5.2)


text:
#ifndef __RTTR_METADATA_CONTAINER_H__
#define __RTTR_METADATA_CONTAINER_H__

#include "rttr/base/core_prerequisites.h"
#include "rttr/variant.h"

#include <string>
#include <unordered_map>

namespace rttr
{
namespace detail
{

/*!
 * This class gives access to a constructor of a rttr::type.
 * Discovers the attributes of a class constructor and provides access to constructor metadata.
 *
 * Calling constructor::invoke will create an instance of the type.
 */
class RTTR_API metadata_container
{
    public:
        variant get_metadata(int key) const;
        variant get_metadata(const std::string& key) const;

        void set_metadata(int key, const variant& value);
        void set_metadata(const std::string& key, const variant& value);

    private:
        typedef std::unordered_map<int, variant> IntKey2ValueMap;
        typedef std::unordered_map<std::string, variant> StringKey2ValueMap;
        IntKey2ValueMap _int_data;
        StringKey2ValueMap _string_data;
};

} // end namespace detail
} // end namespace rttr

#endif // __RTTR_METADATA_CONTAINER_H__