text:
package net.ontopia.topicmaps.webed.impl.utils;

import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import net.ontopia.utils.OntopiaRuntimeException;
import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.topicmaps.core.AssociationIF;
import net.ontopia.topicmaps.core.AssociationRoleIF;
import net.ontopia.topicmaps.core.OccurrenceIF;
import net.ontopia.topicmaps.core.ScopedIF;
import net.ontopia.topicmaps.core.TMObjectIF;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.core.TopicMapIF;
import net.ontopia.topicmaps.core.index.ClassInstanceIndexIF;
import net.ontopia.topicmaps.schema.core.CardinalityConstraintIF;
import net.ontopia.topicmaps.schema.core.ConstraintIF;
import net.ontopia.topicmaps.schema.core.TMObjectMatcherIF;
import net.ontopia.topicmaps.schema.impl.osl.AssociationClass;
import net.ontopia.topicmaps.schema.impl.osl.AssociationRoleConstraint;
import net.ontopia.topicmaps.schema.impl.osl.InternalTopicRefMatcher;
import net.ontopia.topicmaps.schema.impl.osl.OSLSchema;
import net.ontopia.topicmaps.schema.impl.osl.OccurrenceConstraint;
import net.ontopia.topicmaps.schema.impl.osl.ScopeSpecification;
import net.ontopia.topicmaps.schema.impl.osl.SourceLocatorMatcher;
import net.ontopia.topicmaps.schema.impl.osl.SubjectIndicatorMatcher;
import net.ontopia.topicmaps.schema.impl.osl.TopicClass;
import net.ontopia.topicmaps.schema.impl.osl.TopicNameConstraint;
import net.ontopia.topicmaps.schema.impl.osl.TypeSpecification;
import net.ontopia.topicmaps.utils.TypeHierarchyUtils;

/**
 * INTERNAL: Utitlity class for providing help around making topic map
 * schema support available to the web editor.
 */
public class SchemaUtils {

  private static TypeHierarchyUtils hierUtils = new TypeHierarchyUtils();

  /**
   * INTERNAL: Helper method for resolving a topic object from a
   * matcher instance of a schema.
   */
  private TopicIF getTopic(TopicMapIF tm, TMObjectMatcherIF matcher) {
    if (matcher instanceof InternalTopicRefMatcher) {
      InternalTopicRefMatcher m = (InternalTopicRefMatcher) matcher;
      LocatorIF loc = tm.getStore().getBaseAddress()
        .resolveAbsolute(m.getRelativeURI());
      return (TopicIF) tm.getObjectByItemIdentifier(loc);

    } else if (matcher instanceof SourceLocatorMatcher) {
      SourceLocatorMatcher m = (SourceLocatorMatcher) matcher;
      return (TopicIF) tm.getObjectByItemIdentifier(m.getLocator());

    } else if (matcher instanceof SubjectIndicatorMatcher) {
      SubjectIndicatorMatcher m = (SubjectIndicatorMatcher) matcher;
      return tm.getTopicBySubjectIdentifier(m.getLocator());

    } else
      throw new OntopiaRuntimeException("INTERNAL ERROR: Illegal topic class" +
                                        " matcher: " + matcher);
  }

  /**
   * INTERNAL: Add topic(s) matching a topic matcher to a collection.
   */
  private void addTopic(TopicMapIF tm, TMObjectMatcherIF matcher,
                        Collection topics) {
    if (matcher instanceof TypeSpecification) {
      TypeSpecification m = (TypeSpecification) matcher;
      TopicIF type = getTopic(tm, m.getClassMatcher());
      if (type != null) {
        ClassInstanceIndexIF typeIndex = (ClassInstanceIndexIF)
          tm.getIndex("net.ontopia.topicmaps.core.index.ClassInstanceIndexIF");
        topics.addAll(typeIndex.getTopics(type));
      }

    } else {
      TopicIF topic = getTopic(tm, matcher);
      if (topic != null)
        topics.add(topic);
    }
  }

  /**
   * INTERNAL: Gets the topic objects which define a context theme by
   * the given scope specification typically attached to a constraint
   * object.
   *
   * @return A collection of TopicIF objects.
   */
  public Collection getMatchingTopics(TopicMapIF tm, ScopeSpecification scopeSpec) {
    Collection result = new HashSet();
    if (scopeSpec != null) {
      Collection matchers = scopeSpec.getThemeMatchers();
      Iterator itM = matchers.iterator();
      while (itM.hasNext()) {
        TMObjectMatcherIF matcher = (TMObjectMatcherIF) itM.next();
        addTopic(tm, matcher, result);
      }
    }
    return result;
  }

  /**
   * INTERNAL: Gets the topic objects which define a class type by
   * the given type specification typically attached to a constraint
   * object.
   *
   * @return A collection of TopicIF objects.
   */
  public Collection getMatchingTopics(TopicMapIF tm, TypeSpecification typeSpec) {
    Collection result = new HashSet();
    if (typeSpec != null) {
      TMObjectMatcherIF matcher = typeSpec.getClassMatcher();
      addTopic(tm, matcher, result);
    }
    return result;
  }

  // -------------------------------------------------------------------------
  // Constraints about topic names
  // -------------------------------------------------------------------------

  /**
   * INTERNAL: Returns the complete set of topic name constraints in
   * this collection, including those of sub collections.
   *
   * @return A collection of TopicNameConstraint objects.
   */
  public Collection getAllTopicNameConstraints(OSLSchema schema, TopicIF topic) {
    // find appropriate class
    TopicClass klass = (TopicClass) findClass(topic, schema.getTopicClasses());
    if (klass == null)
      return Collections.EMPTY_LIST;
    return klass.getAllTopicNameConstraints();
  }

  /**
   * INTERNAL: Returns a set of topic objects which belong to themes
   * that are allowed to add to the topic name by the given topic.
   *
   * @return A ScopeStorage object containing a collection of TopicIF objects.
   */
  public ScopeStorage getRemainingTopicNameThemes(OSLSchema schema, TopicIF topic) {
    Collection bnC = this.getAllTopicNameConstraints(schema, topic);
    Set bnThemes = new HashSet();
    boolean unconstrainedIncluded = false;
    if (bnC.size() > 0) {
      Collection curTopicNames = topic.getTopicNames();
      Iterator itC = bnC.iterator();
      // loop over all topic name constraints
      while (itC.hasNext()) {
        TopicNameConstraint constraint = (TopicNameConstraint) itC.next();
        // int min = constraint.getMinimum();
        int max = constraint.getMaximum();
        if (max == CardinalityConstraintIF.INFINITY)
          max = Integer.MAX_VALUE;
        ScopeSpecification scsp = constraint.getScopeSpecification();
        Collection topicThemes = this.getMatchingTopics(topic.getTopicMap(), scsp);
        int curNumber = this.getCharacteristicsInScope(curTopicNames, topicThemes).size();
        // check if theme can be added theoretically
        if (curNumber < max) {
          // add the scope to the allowed set of topic name scopes
          Iterator itT = topicThemes.iterator();
          while (itT.hasNext())
            bnThemes.add((TopicIF) itT.next());
          if (topicThemes.isEmpty())
            unconstrainedIncluded = true;
        }
      } // while itC
    }
    return new ScopeStorage(bnThemes, unconstrainedIncluded);
  }

  // -------------------------------------------------------------------------
  // Constraints about Occurrences
  // -------------------------------------------------------------------------

  /**
   * INTERNAL: Returns the complete set of constraints for internal
   * occurrences for the given topic in the specified schema.
   *
   * @return A collection of OccurrenceConstraint objects.
   */
  public Collection getIntOccConstraints(OSLSchema schema, TopicIF topic) {
    return getOccurrenceConstraints(schema, topic, true);
  }

  /**
   * INTERNAL: Returns the complete set of constraints for external
   * occurrences for the given topic in the specified schema.
   *
   * @return A collection of OccurrenceConstraint objects.
   */
  public Collection getExtOccConstraints(OSLSchema schema, TopicIF topic) {
    return getOccurrenceConstraints(schema, topic, false);
  }

  protected Collection getOccurrenceConstraints(OSLSchema schema, TopicIF topic,
                                                boolean internal) {
    List selOccCons = new ArrayList();
    // find appropriate class
    TopicClass klass = (TopicClass) findClass(topic, schema.getTopicClasses());
    if (klass == null)
      return Collections.EMPTY_LIST;

    Collection occConstraints = klass.getAllOccurrenceConstraints();
    Iterator it = occConstraints.iterator();
    while (it.hasNext()) {
      OccurrenceConstraint oc = (OccurrenceConstraint) it.next();
      if ((internal && (oc.getInternal() == OccurrenceConstraint.RESOURCE_INTERNAL
                        || oc.getInternal() == OccurrenceConstraint.RESOURCE_EITHER))
          || (!internal && (oc.getInternal() == OccurrenceConstraint.RESOURCE_EXTERNAL
                            || oc.getInternal() == OccurrenceConstraint.RESOURCE_EITHER)))
        selOccCons.add(oc);
    }
    return selOccCons;
  }

  /**
   * INTERNAL: Returns a set of topic objects which belong to internal
   * occurrence types that are allowed to add to the given topic.
   *
   * @return A TypeStorage object containing a collection of TopicIF objects.
   */
  public TypeStorage getRemainingIntOccTypes(OSLSchema schema, TopicIF topic) {
    return this.getRemainingOccTypes(schema, topic,
                                     this.getIntOccConstraints(schema, topic));
  }

  /**
   * INTERNAL: Returns a set of topic objects which belong to external
   * occurrence types that are allowed to add to the given topic.
   *
   * @return A TypeStorage object containing a collection of TopicIF objects.
   */
  public TypeStorage getRemainingExtOccTypes(OSLSchema schema, TopicIF topic) {
    return this.getRemainingOccTypes(schema, topic,
                                     this.getExtOccConstraints(schema, topic));
  }

  protected TypeStorage getRemainingOccTypes(OSLSchema schema, TopicIF topic,
                                             Collection occCons) {
    Set remOccTypes = new HashSet();
    boolean untypedIncluded = false;
    if (occCons.size() > 0) {
      // get all types of all occurrences of the given topic
      Collection topicOccTypes = new ArrayList();
      // System.out.println("getRemainingOccTypes for topic: " + topic);
      // System.out.println("-----------\n" + topic.getOccurrences() + "\n------");
      Iterator itOT = topic.getOccurrences().iterator();
      while (itOT.hasNext())
        topicOccTypes.add(((OccurrenceIF) itOT.next()).getType());
      // loop over all occurrence constraints
      Iterator itC = occCons.iterator();
      while (itC.hasNext()) {
        OccurrenceConstraint constraint = (OccurrenceConstraint) itC.next();
        // int min = constraint.getMinimum();
        int max = constraint.getMaximum();
        if (max == CardinalityConstraintIF.INFINITY)
          max = Integer.MAX_VALUE;
        TypeSpecification typeSpec = constraint.getTypeSpecification();
        Collection types = this.getMatchingTopics(topic.getTopicMap(), typeSpec);
        int curNumber = this.getObjectsOfType(topicOccTypes, types).size();
        // System.out.println(" - cur types: " + types);
        // System.out.println("   --> " + curNumber);
        // -- check if type can be used for a new occurrence theoretically
        if (curNumber < max) {
          // add the type to the allowed set of role types
          Iterator itT = types.iterator();
          while (itT.hasNext())
            remOccTypes.add((TopicIF) itT.next());
          if (types.isEmpty())
            untypedIncluded = true;
        }
      } // while itC
    }
    return new TypeStorage(remOccTypes, untypedIncluded);
  }

  // -------------------------------------------------------------------------
  // Constraints about Association roles
  // -------------------------------------------------------------------------

  /**
   * INTERNAL: Returns the collection of role constraints in this
   * class definition.
   *
   * @return A collection of AssociationRoleConstraint objects.
   */
  public Collection getRoleConstraints(OSLSchema schema, AssociationIF assoc) {
    // find appropriate class
    AssociationClass klass = (AssociationClass) findClass(assoc, schema.getAssociationClasses());
    if (klass == null)
      return Collections.EMPTY_LIST;
    return klass.getRoleConstraints();
  }

  /**
   * INTERNAL: Returns a collection of association types that can
   * be played by the given topic.
   *
   * @return A collection of TopicIF objects.
   */
  public Collection getAllowedAssocTypes(OSLSchema schema, TopicIF topic) {
    Set result = new HashSet();
    Collection topicTypes = hierUtils.getSupertypes(topic);
    Collection assocClasses = schema.getAssociationClasses();
    Iterator itAC = assocClasses.iterator();
    while (itAC.hasNext()) {
      AssociationClass klass = (AssociationClass) itAC.next();
      Collection assocTypes = this.getMatchingTopics(topic.getTopicMap(),
                                                     klass.getTypeSpecification());
      Collection roleCons = klass.getRoleConstraints();
      // System.out.println("getAllowedAssocTypes for topic: " + topic +
      //                   "\n  roleCons: " + roleCons + "\n----------");
      Iterator itRC = roleCons.iterator();
      while (itRC.hasNext()) {
        AssociationRoleConstraint con = (AssociationRoleConstraint) itRC.next();
        TypeSpecification typeSpec = con.getTypeSpecification();
        Collection types = this.getMatchingTopics(topic.getTopicMap(), typeSpec);
        if (topicTypes.containsAll(types))
          result.addAll(assocTypes);
      } // while itRC
    } // while itAC
    return result;
  }

  /**
   * INTERNAL: Get the allowed association role type for the given
   * association type with the help of the schema.
   */
  public TopicIF getRoleType4AssocType(OSLSchema schema, TopicIF assocType,
                                       TopicIF player) {
    if (assocType == null)
      return null;
    Collection playerTypes = hierUtils.getSupertypes(player);
    Collection assocClasses = schema.getAssociationClasses();
    Iterator itAC = assocClasses.iterator();
    while (itAC.hasNext()) {
      AssociationClass klass = (AssociationClass) itAC.next();
      Collection assocTypes = this.getMatchingTopics(assocType.getTopicMap(),
                                                     klass.getTypeSpecification());
      // figure out if that's the association type we have information about
      if (assocTypes.contains(assocType)) {
        Collection roleCons = klass.getRoleConstraints();
        Iterator itRC = roleCons.iterator();
        while (itRC.hasNext()) {
          AssociationRoleConstraint con = (AssociationRoleConstraint) itRC.next();
          TypeSpecification typeSpec = con.getTypeSpecification();
          Collection roleTypes = this.getMatchingTopics(assocType.getTopicMap(), typeSpec);
          Iterator itRT = roleTypes.iterator();
          while (itRT.hasNext()) {
            TopicIF curRoleType = (TopicIF) itRT.next();
            if (playerTypes.contains(curRoleType))
              return curRoleType;
          } // while itRT
        } // while itRC
      }
    } // while itAC
    return null;
  }

  /**
   * INTERNAL: Returns a set of topic objects which belong to role types
   * that are allowed to add to the given association.
   *
   * @return A TypeStorage object containing a collection of TopicIF objects.
   */
  public TypeStorage getRemainingRoleTypes(OSLSchema schema, AssociationIF assoc) {
    Collection roleCons = this.getRoleConstraints(schema, assoc);
    Set remRoleTypes = new HashSet();
    boolean untypedIncluded = false;
    if (roleCons.size() > 0) {
      // get all types of all roles of the given association
      Collection assocRoleTypes = new ArrayList();
      Iterator itRT = assoc.getRoles().iterator();
      while (itRT.hasNext())
        assocRoleTypes.add(((AssociationRoleIF) itRT.next()).getType());
      // loop over all association role constraints
      Iterator itC = roleCons.iterator();
      while (itC.hasNext()) {
        AssociationRoleConstraint constraint = (AssociationRoleConstraint) itC.next();
        // int min = constraint.getMinimum();
        int max = constraint.getMaximum();
        if (max == CardinalityConstraintIF.INFINITY)
          max = Integer.MAX_VALUE;
        TypeSpecification typeSpec = constraint.getTypeSpecification();
        Collection types = this.getMatchingTopics(assoc.getTopicMap(), typeSpec);
        int curNumber = this.getObjectsOfType(assocRoleTypes, types).size();
        // check if type can be used for a new role theoretically
        if (curNumber < max) {
          // add the type to the allowed set of role types
          Iterator itT = types.iterator();
          while (itT.hasNext())
            remRoleTypes.add((TopicIF) itT.next());
          if (types.isEmpty())
            untypedIncluded = true;
        }
      } // while itC
    }
    return new TypeStorage(remRoleTypes, untypedIncluded);
  }

  // ---------------------------------------------------------------------
  // internal helper methods
  // ---------------------------------------------------------------------

  protected ConstraintIF findClass(TopicIF topic, Collection classes) {
    TopicClass klass = (TopicClass) findClass((TMObjectIF) topic, classes);
    if (klass == null)
      return klass;

    // go through and check if we ought to use a subclass instead
    while (!klass.getSubclasses().isEmpty()) {
      TopicClass prev = klass;
      Iterator it = klass.getSubclasses().iterator();
      while (it.hasNext()) {
        TopicClass candidate = (TopicClass) it.next();
        if (candidate.matches(topic)) {
          klass = candidate;
          break;
        }
      }

      if (prev == klass)
        break;
    }

    return klass;
  }

  protected ConstraintIF findClass(TMObjectIF object, Collection classes) {
    Iterator it = classes.iterator();
    while (it.hasNext()) {
      ConstraintIF candidate = (ConstraintIF) it.next();
      if (candidate.matches(object))
        return candidate;
    }

    return null;
  }

  /**
   * INTERNAL: Return all objects that are in the given scope.
   */
  protected Collection getCharacteristicsInScope(Collection objects, Collection scope) {
    Iterator it = objects.iterator();
    Collection objectsInScope = new ArrayList();
    while (it.hasNext()) {
      ScopedIF scopedObj = (ScopedIF) it.next();
      if (scopedObj.getScope().equals(scope))
        objectsInScope.add(scopedObj);
    }
    return objectsInScope;
  }

  /**
   * INTERNAL: Return all typing objects that are equal to one
   * of the given types.
   */
  protected Collection getObjectsOfType(Collection allTypes, Collection curTypes) {
    Collection objectsOfType = new ArrayList();
    Iterator itA = allTypes.iterator();
    while (itA.hasNext()) {
      Object objAT = itA.next();
      if (objAT == null)
        continue;
      Iterator itB = curTypes.iterator();
      while (itB.hasNext()) {
        Object objCT = itB.next();
        if (objAT.equals(objCT))
          objectsOfType.add(objCT);
      } // while itB
    } // while itA
    return objectsOfType;
  }

}


text:
"""Classes to generate plain text from a message object tree."""

__all__ = ['Generator', 'DecodedGenerator']

import re
import sys
import time
import random
import warnings

from io import StringIO
from email.header import Header

UNDERSCORE = '_'
NL = '\n'

fcre = re.compile(r'^From ', re.MULTILINE)

class Generator:
    """Generates output from a Message object tree.

    This basic generator writes the message to the given file object as plain
    text.
    """
    #
    # Public interface
    #

    def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
        """Create the generator for message flattening.

        outfp is the output file-like object for writing the message to.  It
        must have a write() method.

        Optional mangle_from_ is a flag that, when True (the default), escapes
        From_ lines in the body of the message by putting a `>' in front of
        them.

        Optional maxheaderlen specifies the longest length for a non-continued
        header.  When a header line is longer (in characters, with tabs
        expanded to 8 spaces) than maxheaderlen, the header will split as
        defined in the Header class.  Set maxheaderlen to zero to disable
        header wrapping.  The default is 78, as recommended (but not required)
        by RFC 2822.
        """
        self._fp = outfp
        self._mangle_from_ = mangle_from_
        self._maxheaderlen = maxheaderlen

    def write(self, s):
        # Just delegate to the file object
        self._fp.write(s)

    def flatten(self, msg, unixfrom=False):
        """Print the message object tree rooted at msg to the output file
        specified when the Generator instance was created.

        unixfrom is a flag that forces the printing of a Unix From_ delimiter
        before the first object in the message tree.  If the original message
        has no From_ delimiter, a `standard' one is crafted.  By default, this
        is False to inhibit the printing of any From_ delimiter.

        Note that for subobjects, no From_ line is printed.
        """
        if unixfrom:
            ufrom = msg.get_unixfrom()
            if not ufrom:
                ufrom = 'From nobody ' + time.ctime(time.time())
            print(ufrom, file=self._fp)
        self._write(msg)

    def clone(self, fp):
        """Clone this generator with the exact same options."""
        return self.__class__(fp, self._mangle_from_, self._maxheaderlen)

    #
    # Protected interface - undocumented ;/
    #

    def _write(self, msg):
        # We can't write the headers yet because of the following scenario:
        # say a multipart message includes the boundary string somewhere in
        # its body.  We'd have to calculate the new boundary /before/ we write
        # the headers so that we can write the correct Content-Type:
        # parameter.
        #
        # The way we do this, so as to make the _handle_*() methods simpler,
        # is to cache any subpart writes into a StringIO.  The we write the
        # headers and the StringIO contents.  That way, subpart handlers can
        # Do The Right Thing, and can still modify the Content-Type: header if
        # necessary.
        oldfp = self._fp
        try:
            self._fp = sfp = StringIO()
            self._dispatch(msg)
        finally:
            self._fp = oldfp
        # Write the headers.  First we see if the message object wants to
        # handle that itself.  If not, we'll do it generically.
        meth = getattr(msg, '_write_headers', None)
        if meth is None:
            self._write_headers(msg)
        else:
            meth(self)
        self._fp.write(sfp.getvalue())

    def _dispatch(self, msg):
        # Get the Content-Type: for the message, then try to dispatch to
        # self._handle_<maintype>_<subtype>().  If there's no handler for the
        # full MIME type, then dispatch to self._handle_<maintype>().  If
        # that's missing too, then dispatch to self._writeBody().
        main = msg.get_content_maintype()
        sub = msg.get_content_subtype()
        specific = UNDERSCORE.join((main, sub)).replace('-', '_')
        meth = getattr(self, '_handle_' + specific, None)
        if meth is None:
            generic = main.replace('-', '_')
            meth = getattr(self, '_handle_' + generic, None)
            if meth is None:
                meth = self._writeBody
        meth(msg)

    #
    # Default handlers
    #

    def _write_headers(self, msg):
        for h, v in msg.items():
            print('%s:' % h, end=' ', file=self._fp)
            if isinstance(v, Header):
                print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
            else:
                # Header's got lots of smarts, so use it.
                header = Header(v, maxlinelen=self._maxheaderlen,
                                header_name=h, continuation_ws='\t')
                print(header.encode(), file=self._fp)
        # A blank line always separates headers from body
        print(file=self._fp)

    #
    # Handlers for writing types and subtypes
    #

    def _handle_text(self, msg):
        payload = msg.get_payload()
        if payload is None:
            return
        if not isinstance(payload, str):
            raise TypeError('string payload expected: %s' % type(payload))
        if self._mangle_from_:
            payload = fcre.sub('>From ', payload)
        self._fp.write(payload)

    # Default body handler
    _writeBody = _handle_text

    def _handle_multipart(self, msg):
        # The trick here is to write out each part separately, merge them all
        # together, and then make sure that the boundary we've chosen isn't
        # present in the payload.
        msgtexts = []
        subparts = msg.get_payload()
        if subparts is None:
            subparts = []
        elif isinstance(subparts, str):
            # e.g. a non-strict parse of a message with no starting boundary.
            self._fp.write(subparts)
            return
        elif not isinstance(subparts, list):
            # Scalar payload
            subparts = [subparts]
        for part in subparts:
            s = StringIO()
            g = self.clone(s)
            g.flatten(part, unixfrom=False)
            msgtexts.append(s.getvalue())
        # Now make sure the boundary we've selected doesn't appear in any of
        # the message texts.
        alltext = NL.join(msgtexts)
        # BAW: What about boundaries that are wrapped in double-quotes?
        boundary = msg.get_boundary(failobj=_make_boundary(alltext))
        # If we had to calculate a new boundary because the body text
        # contained that string, set the new boundary.  We don't do it
        # unconditionally because, while set_boundary() preserves order, it
        # doesn't preserve newlines/continuations in headers.  This is no big
        # deal in practice, but turns out to be inconvenient for the unittest
        # suite.
        if msg.get_boundary() != boundary:
            msg.set_boundary(boundary)
        # If there's a preamble, write it out, with a trailing CRLF
        if msg.preamble is not None:
            print(msg.preamble, file=self._fp)
        # dash-boundary transport-padding CRLF
        print('--' + boundary, file=self._fp)
        # body-part
        if msgtexts:
            self._fp.write(msgtexts.pop(0))
        # *encapsulation
        # --> delimiter transport-padding
        # --> CRLF body-part
        for body_part in msgtexts:
            # delimiter transport-padding CRLF
            print('\n--' + boundary, file=self._fp)
            # body-part
            self._fp.write(body_part)
        # close-delimiter transport-padding
        self._fp.write('\n--' + boundary + '--')
        if msg.epilogue is not None:
            print(file=self._fp)
            self._fp.write(msg.epilogue)

    def _handle_message_delivery_status(self, msg):
        # We can't just write the headers directly to self's file object
        # because this will leave an extra newline between the last header
        # block and the boundary.  Sigh.
        blocks = []
        for part in msg.get_payload():
            s = StringIO()
            g = self.clone(s)
            g.flatten(part, unixfrom=False)
            text = s.getvalue()
            lines = text.split('\n')
            # Strip off the unnecessary trailing empty line
            if lines and lines[-1] == '':
                blocks.append(NL.join(lines[:-1]))
            else:
                blocks.append(text)
        # Now join all the blocks with an empty line.  This has the lovely
        # effect of separating each block with an empty line, but not adding
        # an extra one after the last one.
        self._fp.write(NL.join(blocks))

    def _handle_message(self, msg):
        s = StringIO()
        g = self.clone(s)
        # The payload of a message/rfc822 part should be a multipart sequence
        # of length 1.  The zeroth element of the list should be the Message
        # object for the subpart.  Extract that object, stringify it, and
        # write it out.
        g.flatten(msg.get_payload(0), unixfrom=False)
        self._fp.write(s.getvalue())

_FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]'

class DecodedGenerator(Generator):
    """Generator a text representation of a message.

    Like the Generator base class, except that non-text parts are substituted
    with a format string representing the part.
    """
    def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
        """Like Generator.__init__() except that an additional optional
        argument is allowed.

        Walks through all subparts of a message.  If the subpart is of main
        type `text', then it prints the decoded payload of the subpart.

        Otherwise, fmt is a format string that is used instead of the message
        payload.  fmt is expanded with the following keywords (in
        %(keyword)s format):

        type       : Full MIME type of the non-text part
        maintype   : Main MIME type of the non-text part
        subtype    : Sub-MIME type of the non-text part
        filename   : Filename of the non-text part
        description: Description associated with the non-text part
        encoding   : Content transfer encoding of the non-text part

        The default value for fmt is None, meaning

        [Non-text (%(type)s) part of message omitted, filename %(filename)s]
        """
        Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
        if fmt is None:
            self._fmt = _FMT
        else:
            self._fmt = fmt

    def _dispatch(self, msg):
        for part in msg.walk():
            maintype = part.get_content_maintype()
            if maintype == 'text':
                print(part.get_payload(decode=False), file=self)
            elif maintype == 'multipart':
                # Just skip this
                pass
            else:
                print(self._fmt % {
                    'type'       : part.get_content_type(),
                    'maintype'   : part.get_content_maintype(),
                    'subtype'    : part.get_content_subtype(),
                    'filename'   : part.get_filename('[no filename]'),
                    'description': part.get('Content-Description',
                                            '[no description]'),
                    'encoding'   : part.get('Content-Transfer-Encoding',
                                            '[no encoding]'),
                    }, file=self)

# Helper
_width = len(repr(sys.maxsize-1))
_fmt = '%%0%dd' % _width

def _make_boundary(text=None):
    # Craft a random boundary.  If text is given, ensure that the chosen
    # boundary doesn't appear in the text.
    token = random.randrange(sys.maxsize)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b

redpajama_set_name: RedPajamaGithub


text: module.exports = require('debug')('sanity:export')


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Root from '../../core/root/root.js';
import * as IssuesManager from '../../models/issues_manager/issues_manager.js';
import * as IssueCounter from '../../ui/components/issue_counter/issue_counter.js';
import * as UI from '../../ui/legacy/legacy.js';

import {HiddenIssuesRow} from './HiddenIssuesRow.js';
import issuesPaneStyles from './issuesPane.css.js';
import issuesTreeStyles from './issuesTree.css.js';

import {
  Events as IssueAggregatorEvents,
  IssueAggregator,
  type AggregatedIssue,
  type AggregationKey,
} from './IssueAggregator.js';
import {IssueView} from './IssueView.js';
import {IssueKindView, getGroupIssuesByKindSetting, issueKindViewSortPriority} from './IssueKindView.js';

const UIStrings = {
  /**
   * @description Category title for a group of cross origin embedder policy (COEP) issues
   */
  crossOriginEmbedderPolicy: 'Cross Origin Embedder Policy',
  /**
   * @description Category title for a group of mixed content issues
   */
  mixedContent: 'Mixed Content',
  /**
   * @description Category title for a group of SameSite cookie issues
   */
  samesiteCookie: 'SameSite Cookie',
  /**
   * @description Category title for a group of heavy ads issues
   */
  heavyAds: 'Heavy Ads',
  /**
   * @description Category title for a group of content security policy (CSP) issues
   */
  contentSecurityPolicy: 'Content Security Policy',
  /**
   * @description Category title for a group of trusted web activity issues
   */
  trustedWebActivity: 'Trusted Web Activity',
  /**
   * @description Text for other types of items
   */
  other: 'Other',
  /**
   * @description Category title for the different 'low text contrast' issues. Low text contrast refers
   *              to the difference between the color of a text and the background color where that text
   *              appears.
   */
  lowTextContrast: 'Low Text Contrast',
  /**
   * @description Category title for the different 'Cross-Origin Resource Sharing' (CORS) issues. CORS
   *              refers to one origin (e.g 'a.com') loading resources from another origin (e.g. 'b.com').
   */
  cors: 'Cross Origin Resource Sharing',
  /**
   * @description Title for a checkbox which toggles grouping by category in the issues tab
   */
  groupDisplayedIssuesUnder: 'Group displayed issues under associated categories',
  /**
   * @description Label for a checkbox which toggles grouping by category in the issues tab
   */
  groupByCategory: 'Group by category',
  /**
  * @description Title for a checkbox which toggles grouping by kind in the issues tab
    */
  groupDisplayedIssuesUnderKind: 'Group displayed issues as Page errors, Breaking changes and Improvements',
  /**
  * @description Label for a checkbox which toggles grouping by kind in the issues tab
    */
  groupByKind: 'Group by kind',
  /**
   * @description Title for a checkbox. Whether the issues tab should include third-party issues or not.
   */
  includeCookieIssuesCausedBy: 'Include cookie Issues caused by third-party sites',
  /**
   * @description Label for a checkbox. Whether the issues tab should include third-party issues or not.
   */
  includeThirdpartyCookieIssues: 'Include third-party cookie issues',
  /**
   * @description Label on the issues tab
   */
  onlyThirdpartyCookieIssues: 'Only third-party cookie issues detected so far',
  /**
   * @description Label in the issues panel
   */
  noIssuesDetectedSoFar: 'No issues detected so far',
  /**
   * @description Category title for the different 'Attribution Reporting API' issues. The
   * Attribution Reporting API is a newly proposed web API (see https://github.com/WICG/conversion-measurement-api).
   */
  attributionReporting: 'Attribution Reporting `API`',
  /**
   * @description Category title for the different 'Quirks Mode' issues. Quirks Mode refers
   *              to the legacy browser modes that displays web content according to outdated
   *              browser behaviors.
   */
  quirksMode: 'Quirks Mode',
  /**
   * @description Category title for the different 'Generic' issues.
   */
  generic: 'Generic',
};
const str_ = i18n.i18n.registerUIStrings('panels/issues/IssuesPane.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);

class IssueCategoryView extends UI.TreeOutline.TreeElement {
  #category: IssuesManager.Issue.IssueCategory;

  constructor(category: IssuesManager.Issue.IssueCategory) {
    super();
    this.#category = category;

    this.toggleOnClick = true;
    this.listItemElement.classList.add('issue-category');
    this.childrenListElement.classList.add('issue-category-body');
  }

  getCategoryName(): string {
    switch (this.#category) {
      case IssuesManager.Issue.IssueCategory.CrossOriginEmbedderPolicy:
        return i18nString(UIStrings.crossOriginEmbedderPolicy);
      case IssuesManager.Issue.IssueCategory.MixedContent:
        return i18nString(UIStrings.mixedContent);
      case IssuesManager.Issue.IssueCategory.Cookie:
        return i18nString(UIStrings.samesiteCookie);
      case IssuesManager.Issue.IssueCategory.HeavyAd:
        return i18nString(UIStrings.heavyAds);
      case IssuesManager.Issue.IssueCategory.ContentSecurityPolicy:
        return i18nString(UIStrings.contentSecurityPolicy);
      case IssuesManager.Issue.IssueCategory.TrustedWebActivity:
        return i18nString(UIStrings.trustedWebActivity);
      case IssuesManager.Issue.IssueCategory.LowTextContrast:
        return i18nString(UIStrings.lowTextContrast);
      case IssuesManager.Issue.IssueCategory.Cors:
        return i18nString(UIStrings.cors);
      case IssuesManager.Issue.IssueCategory.AttributionReporting:
        return i18nString(UIStrings.attributionReporting);
      case IssuesManager.Issue.IssueCategory.QuirksMode:
        return i18nString(UIStrings.quirksMode);
      case IssuesManager.Issue.IssueCategory.Generic:
        return i18nString(UIStrings.generic);
      case IssuesManager.Issue.IssueCategory.Other:
        return i18nString(UIStrings.other);
    }
  }

  onattach(): void {
    this.#appendHeader();
  }

  #appendHeader(): void {
    const header = document.createElement('div');
    header.classList.add('header');

    const title = document.createElement('div');
    title.classList.add('title');
    title.textContent = this.getCategoryName();
    header.appendChild(title);

    this.listItemElement.appendChild(header);
  }
}

export function getGroupIssuesByCategorySetting(): Common.Settings.Setting<boolean> {
  return Common.Settings.Settings.instance().createSetting('groupIssuesByCategory', false);
}

let issuesPaneInstance: IssuesPane;

export class IssuesPane extends UI.Widget.VBox {
  #categoryViews: Map<IssuesManager.Issue.IssueCategory, IssueCategoryView>;
  #issueViews: Map<AggregationKey, IssueView>;
  #kindViews: Map<IssuesManager.Issue.IssueKind, IssueKindView>;
  #showThirdPartyCheckbox: UI.Toolbar.ToolbarSettingCheckbox|null;
  #issuesTree: UI.TreeOutline.TreeOutlineInShadow;
  #hiddenIssuesRow: HiddenIssuesRow;
  #noIssuesMessageDiv: HTMLDivElement;
  #issuesManager: IssuesManager.IssuesManager.IssuesManager;
  #aggregator: IssueAggregator;
  #issueViewUpdatePromise: Promise<void> = Promise.resolve();

  private constructor() {
    super(true);

    this.contentElement.classList.add('issues-pane');

    this.#categoryViews = new Map();
    this.#kindViews = new Map();
    this.#issueViews = new Map();
    this.#showThirdPartyCheckbox = null;

    this.#createToolbars();

    this.#issuesTree = new UI.TreeOutline.TreeOutlineInShadow();

    this.#issuesTree.setShowSelectionOnKeyboardFocus(true);
    this.#issuesTree.contentElement.classList.add('issues');
    this.contentElement.appendChild(this.#issuesTree.element);

    this.#hiddenIssuesRow = new HiddenIssuesRow();
    this.#issuesTree.appendChild(this.#hiddenIssuesRow);

    this.#noIssuesMessageDiv = document.createElement('div');
    this.#noIssuesMessageDiv.classList.add('issues-pane-no-issues');
    this.contentElement.appendChild(this.#noIssuesMessageDiv);

    this.#issuesManager = IssuesManager.IssuesManager.IssuesManager.instance();
    this.#aggregator = new IssueAggregator(this.#issuesManager);
    this.#aggregator.addEventListener(IssueAggregatorEvents.AggregatedIssueUpdated, this.#issueUpdated, this);
    this.#aggregator.addEventListener(IssueAggregatorEvents.FullUpdateRequired, this.#onFullUpdate, this);
    this.#hiddenIssuesRow.hidden = this.#issuesManager.numberOfHiddenIssues() === 0;
    this.#onFullUpdate();
    this.#issuesManager.addEventListener(
        IssuesManager.IssuesManager.Events.IssuesCountUpdated, this.#updateCounts, this);
  }

  static instance(opts: {forceNew: boolean|null} = {forceNew: null}): IssuesPane {
    const {forceNew} = opts;
    if (!issuesPaneInstance || forceNew) {
      issuesPaneInstance = new IssuesPane();
    }

    return issuesPaneInstance;
  }

  elementsToRestoreScrollPositionsFor(): Element[] {
    return [this.#issuesTree.element];
  }

  #createToolbars(): {toolbarContainer: Element} {
    const toolbarContainer = this.contentElement.createChild('div', 'issues-toolbar-container');
    new UI.Toolbar.Toolbar('issues-toolbar-left', toolbarContainer);
    const rightToolbar = new UI.Toolbar.Toolbar('issues-toolbar-right', toolbarContainer);

    const groupByCategorySetting = getGroupIssuesByCategorySetting();
    const groupByCategoryCheckbox = new UI.Toolbar.ToolbarSettingCheckbox(
        groupByCategorySetting, i18nString(UIStrings.groupDisplayedIssuesUnder), i18nString(UIStrings.groupByCategory));
    // Hide the option to toggle category grouping for now.
    groupByCategoryCheckbox.setVisible(false);
    rightToolbar.appendToolbarItem(groupByCategoryCheckbox);
    groupByCategorySetting.addChangeListener(() => {
      this.#fullUpdate(true);
    });

    const groupByKindSetting = getGroupIssuesByKindSetting();
    const groupByKindSettingCheckbox = new UI.Toolbar.ToolbarSettingCheckbox(
        groupByKindSetting, i18nString(UIStrings.groupDisplayedIssuesUnderKind), i18nString(UIStrings.groupByKind));
    rightToolbar.appendToolbarItem(groupByKindSettingCheckbox);
    groupByKindSetting.addChangeListener(() => {
      this.#fullUpdate(true);
    });
    groupByKindSettingCheckbox.setVisible(Root.Runtime.experiments.isEnabled('groupAndHideIssuesByKind'));

    const thirdPartySetting = IssuesManager.Issue.getShowThirdPartyIssuesSetting();
    this.#showThirdPartyCheckbox = new UI.Toolbar.ToolbarSettingCheckbox(
        thirdPartySetting, i18nString(UIStrings.includeCookieIssuesCausedBy),
        i18nString(UIStrings.includeThirdpartyCookieIssues));
    rightToolbar.appendToolbarItem(this.#showThirdPartyCheckbox);
    this.setDefaultFocusedElement(this.#showThirdPartyCheckbox.inputElement);

    rightToolbar.appendSeparator();
    const issueCounter = new IssueCounter.IssueCounter.IssueCounter();
    issueCounter.data = {
      tooltipCallback: (): void => {
        const issueEnumeration = IssueCounter.IssueCounter.getIssueCountsEnumeration(
            IssuesManager.IssuesManager.IssuesManager.instance(), false);
        issueCounter.title = issueEnumeration;
      },
      displayMode: IssueCounter.IssueCounter.DisplayMode.ShowAlways,
      issuesManager: IssuesManager.IssuesManager.IssuesManager.instance(),
    };
    issueCounter.id = 'console-issues-counter';
    const issuesToolbarItem = new UI.Toolbar.ToolbarItem(issueCounter);
    rightToolbar.appendToolbarItem(issuesToolbarItem);

    return {toolbarContainer};
  }

  #issueUpdated(event: Common.EventTarget.EventTargetEvent<AggregatedIssue>): void {
    this.#scheduleIssueViewUpdate(event.data);
  }

  #scheduleIssueViewUpdate(issue: AggregatedIssue): void {
    this.#issueViewUpdatePromise = this.#issueViewUpdatePromise.then(() => this.#updateIssueView(issue));
  }

  /** Don't call directly. Use `scheduleIssueViewUpdate` instead. */
  async #updateIssueView(issue: AggregatedIssue): Promise<void> {
    let issueView = this.#issueViews.get(issue.aggregationKey());
    if (!issueView) {
      const description = issue.getDescription();
      if (!description) {
        console.warn('Could not find description for issue code:', issue.code());
        return;
      }
      const markdownDescription =
          await IssuesManager.MarkdownIssueDescription.createIssueDescriptionFromMarkdown(description);
      issueView = new IssueView(issue, markdownDescription);
      this.#issueViews.set(issue.aggregationKey(), issueView);
      const parent = this.#getIssueViewParent(issue);
      this.appendIssueViewToParent(issueView, parent);
    } else {
      issueView.setIssue(issue);
      const newParent = this.#getIssueViewParent(issue);
      if (issueView.parent !== newParent &&
          !(newParent instanceof UI.TreeOutline.TreeOutline && issueView.parent === newParent.rootElement())) {
        issueView.parent?.removeChild(issueView);
        this.appendIssueViewToParent(issueView, newParent);
      }
    }
    issueView.update();
    this.#updateCounts();
  }

  appendIssueViewToParent(issueView: IssueView, parent: UI.TreeOutline.TreeOutline|UI.TreeOutline.TreeElement): void {
    parent.appendChild(issueView, (a, b) => {
      if (a instanceof HiddenIssuesRow) {
        return 1;
      }
      if (b instanceof HiddenIssuesRow) {
        return -1;
      }
      if (a instanceof IssueView && b instanceof IssueView) {
        return a.getIssueTitle().localeCompare(b.getIssueTitle());
      }
      console.error('The issues tree should only contain IssueView objects as direct children');
      return 0;
    });
  }

  #getIssueViewParent(issue: AggregatedIssue): UI.TreeOutline.TreeOutline|UI.TreeOutline.TreeElement {
    const groupByKind = Root.Runtime.experiments.isEnabled('groupAndHideIssuesByKind');
    if (issue.isHidden()) {
      return this.#hiddenIssuesRow;
    }
    if (groupByKind && getGroupIssuesByKindSetting().get()) {
      const kind = issue.getKind();
      const view = this.#kindViews.get(kind);
      if (view) {
        return view;
      }

      const newView = new IssueKindView(kind);
      this.#issuesTree.appendChild(newView, (a, b) => {
        if (a instanceof IssueKindView && b instanceof IssueKindView) {
          return issueKindViewSortPriority(a, b);
        }
        return 0;
      });
      this.#kindViews.set(kind, newView);
      return newView;
    }
    if (getGroupIssuesByCategorySetting().get()) {
      const category = issue.getCategory();
      const view = this.#categoryViews.get(category);
      if (view) {
        return view;
      }

      const newView = new IssueCategoryView(category);
      this.#issuesTree.appendChild(newView, (a, b) => {
        if (a instanceof IssueCategoryView && b instanceof IssueCategoryView) {
          return a.getCategoryName().localeCompare(b.getCategoryName());
        }
        return 0;
      });
      this.#categoryViews.set(category, newView);
      return newView;
    }
    return this.#issuesTree;
  }

  #clearViews<T>(views: Map<T, UI.TreeOutline.TreeElement>, preservedSet?: Set<T>): void {
    for (const [key, view] of Array.from(views.entries())) {
      if (preservedSet?.has(key)) {
        continue;
      }
      view.parent && view.parent.removeChild(view);
      views.delete(key);
    }
  }

  #onFullUpdate(): void {
    this.#fullUpdate(false);
  }

  #fullUpdate(force: boolean): void {
    this.#clearViews(this.#categoryViews, force ? undefined : this.#aggregator.aggregatedIssueCategories());
    this.#clearViews(this.#kindViews, force ? undefined : this.#aggregator.aggregatedIssueKinds());
    this.#clearViews(this.#issueViews, force ? undefined : this.#aggregator.aggregatedIssueCodes());
    if (this.#aggregator) {
      for (const issue of this.#aggregator.aggregatedIssues()) {
        this.#scheduleIssueViewUpdate(issue);
      }
    }
    this.#updateCounts();
  }

  #updateIssueKindViewsCount(): void {
    for (const view of this.#kindViews.values()) {
      const count = this.#issuesManager.numberOfIssues(view.getKind());
      view.update(count);
    }
  }

  #updateCounts(): void {
    const groupByKind = Root.Runtime.experiments.isEnabled('groupAndHideIssuesByKind');
    this.#showIssuesTreeOrNoIssuesDetectedMessage(
        this.#issuesManager.numberOfIssues(), this.#issuesManager.numberOfHiddenIssues());
    if (groupByKind && getGroupIssuesByKindSetting().get()) {
      this.#updateIssueKindViewsCount();
    }
  }

  #showIssuesTreeOrNoIssuesDetectedMessage(issuesCount: number, hiddenIssueCount: number): void {
    if (issuesCount > 0 || hiddenIssueCount > 0) {
      this.#hiddenIssuesRow.hidden = hiddenIssueCount === 0;
      this.#hiddenIssuesRow.update(hiddenIssueCount);
      this.#issuesTree.element.hidden = false;
      this.#noIssuesMessageDiv.style.display = 'none';
      const firstChild = this.#issuesTree.firstChild();
      if (firstChild) {
        firstChild.select(/* omitFocus= */ true);
        this.setDefaultFocusedElement(firstChild.listItemElement);
      }
    } else {
      this.#issuesTree.element.hidden = true;
      if (this.#showThirdPartyCheckbox) {
        this.setDefaultFocusedElement(this.#showThirdPartyCheckbox.inputElement);
      }
      // We alreay know that issesCount is zero here.
      const hasOnlyThirdPartyIssues = this.#issuesManager.numberOfAllStoredIssues() > 0;
      this.#noIssuesMessageDiv.textContent = hasOnlyThirdPartyIssues ?
          i18nString(UIStrings.onlyThirdpartyCookieIssues) :
          i18nString(UIStrings.noIssuesDetectedSoFar);
      this.#noIssuesMessageDiv.style.display = 'flex';
    }
  }

  async reveal(issue: IssuesManager.Issue.Issue): Promise<void> {
    await this.#issueViewUpdatePromise;
    const key = this.#aggregator.keyForIssue(issue);
    const issueView = this.#issueViews.get(key);
    const groupByKind = Root.Runtime.experiments.isEnabled('groupAndHideIssuesByKind');
    if (issueView) {
      if (issueView.isForHiddenIssue()) {
        this.#hiddenIssuesRow.expand();
        this.#hiddenIssuesRow.reveal();
      }
      if (groupByKind && getGroupIssuesByKindSetting().get() && !issueView.isForHiddenIssue()) {
        const kindView = this.#kindViews.get(issueView.getIssueKind());
        kindView?.expand();
        kindView?.reveal();
      }
      issueView.expand();
      issueView.reveal();
      issueView.select(false, true);
    }
  }

  wasShown(): void {
    super.wasShown();
    this.#issuesTree.registerCSSFiles([issuesTreeStyles]);
    this.registerCSSFiles([issuesPaneStyles]);
  }
}


text:
import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {JigsawBoxModule, JigsawButtonModule, JigsawHeaderModule} from "jigsaw/public_api";
import {JigsawDemoDescriptionModule} from "app/for-internal/description/demo-description";
import {BoxNgIfNgForDemoComponent} from "./demo.component";

@NgModule({
    declarations: [BoxNgIfNgForDemoComponent],
    exports: [BoxNgIfNgForDemoComponent],
    imports: [JigsawDemoDescriptionModule, JigsawBoxModule, CommonModule, JigsawHeaderModule, JigsawButtonModule]
})
export class BoxNgIfNgForDemoModule {

}


text:
<?php

namespace ZendTest\Filter\File;

use Zend\Filter\File\Rename as FileRename;

/**
 * @group      Zend_Filter
 */
class RenameTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Path to test files
     *
     * @var string
     */
    protected $tmpPath;

    /**
     * Original testfile
     *
     * @var string
     */
    protected $origFile;

    /**
     * Testfile
     *
     * @var string
     */
    protected $oldFile;

    /**
     * Testfile
     *
     * @var string
     */
    protected $newFile;

    /**
     * Testdirectory
     *
     * @var string
     */
    protected $newDir;

    /**
     * Testfile in Testdirectory
     *
     * @var string
     */
    protected $newDirFile;

    /**
     * Sets the path to test files
     *
     * @return void
     */
    public function setUp()
    {
        $control = sprintf('%s/_files/testfile.txt', dirname(__DIR__));
        $this->tmpPath = sprintf('%s%s%s', sys_get_temp_dir(), DIRECTORY_SEPARATOR, uniqid('zfilter'));
        mkdir($this->tmpPath, 0775, true);

        $this->oldFile = sprintf('%s%stestfile.txt', $this->tmpPath, DIRECTORY_SEPARATOR);
        $this->origFile = sprintf('%s%soriginal.file', $this->tmpPath, DIRECTORY_SEPARATOR);
        $this->newFile = sprintf('%s%snewfile.xml', $this->tmpPath, DIRECTORY_SEPARATOR);
        $this->newDir = sprintf('%s%stestdir', $this->tmpPath, DIRECTORY_SEPARATOR);
        $this->newDirFile = sprintf('%s%stestfile.txt', $this->newDir, DIRECTORY_SEPARATOR);

        copy($control, $this->oldFile);
        copy($control, $this->origFile);
        mkdir($this->newDir, 0775, true);
    }

    /**
     * Sets the path to test files
     *
     * @return void
     */
    public function tearDown()
    {
        if (is_dir($this->tmpPath)) {
            if (file_exists($this->oldFile)) {
                unlink($this->oldFile);
            }
            if (file_exists($this->origFile)) {
                unlink($this->origFile);
            }
            if (file_exists($this->newFile)) {
                unlink($this->newFile);
            }
            if (is_dir($this->newDir)) {
                if (file_exists($this->newDirFile)) {
                    unlink($this->newDirFile);
                }
                rmdir($this->newDir);
            }
            rmdir($this->tmpPath);
        }
    }

    /**
     * Test single parameter filter
     *
     * @return void
     */
    public function testConstructSingleValue()
    {
        $filter = new FileRename($this->newFile);

        $this->assertEquals(
            [0 => [
                'source'    => '*',
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single parameter filter
     *
     * @return void
     */
    public function testConstructSingleValueWithFilesArray()
    {
        $filter = new FileRename($this->newFile);

        $this->assertEquals(
            [0 => [
                'source'    => '*',
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals(
            ['tmp_name' => $this->newFile],
            $filter(['tmp_name' => $this->oldFile])
        );
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter
     *
     * @return void
     */
    public function testConstructSingleArray()
    {
        $filter = new FileRename([
            'source' => $this->oldFile,
            'target' => $this->newFile]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test full array parameter filter
     *
     * @return void
     */
    public function testConstructFullOptionsArray()
    {
        $filter = new FileRename([
            'source' => $this->oldFile,
            'target' => $this->newFile,
            'overwrite' => true,
            'randomize' => false,
            'unknown'   => false
        ]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => true,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter
     *
     * @return void
     */
    public function testConstructDoubleArray()
    {
        $filter = new FileRename([
            0 => [
                'source' => $this->oldFile,
                'target' => $this->newFile]]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter
     *
     * @return void
     */
    public function testConstructTruncatedTarget()
    {
        $filter = new FileRename([
            'source' => $this->oldFile]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => '*',
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->oldFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter
     *
     * @return void
     */
    public function testConstructTruncatedSource()
    {
        $filter = new FileRename([
            'target' => $this->newFile]);

        $this->assertEquals(
            [0 => [
                'source'    => '*',
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single parameter filter by using directory only
     *
     * @return void
     */
    public function testConstructSingleDirectory()
    {
        $filter = new FileRename($this->newDir);

        $this->assertEquals(
            [0 => [
                'source'    => '*',
                'target'    => $this->newDir,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newDirFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter by using directory only
     *
     * @return void
     */
    public function testConstructSingleArrayDirectory()
    {
        $filter = new FileRename([
            'source' => $this->oldFile,
            'target' => $this->newDir]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newDir,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newDirFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter by using directory only
     *
     * @return void
     */
    public function testConstructDoubleArrayDirectory()
    {
        $filter = new FileRename([
            0 => [
                'source' => $this->oldFile,
                'target' => $this->newDir]]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newDir,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newDirFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * Test single array parameter filter by using directory only
     *
     * @return void
     */
    public function testConstructTruncatedSourceDirectory()
    {
        $filter = new FileRename([
            'target' => $this->newDir]);

        $this->assertEquals(
            [0 => [
                'source'    => '*',
                'target'    => $this->newDir,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newDirFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * @return void
     */
    public function testAddSameFileAgainAndOverwriteExistingTarget()
    {
        $filter = new FileRename([
            'source' => $this->oldFile,
            'target' => $this->newDir]);

        $filter->addFile([
            'source' => $this->oldFile,
            'target' => $this->newFile]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * @return void
     */
    public function testGetNewName()
    {
        $filter = new FileRename([
            'source' => $this->oldFile,
            'target' => $this->newDir,
        ]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newDir,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newDirFile, $filter->getNewName($this->oldFile));
    }

    /**
     * @return void
     */
    public function testGetNewNameExceptionWithExistingFile()
    {
        $filter = new FileRename([
            'source' => $this->oldFile,
            'target' => $this->newFile]);

        copy($this->oldFile, $this->newFile);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'could not be renamed');
        $this->assertEquals($this->newFile, $filter->getNewName($this->oldFile));
    }

    /**
     * @return void
     */
    public function testGetNewNameOverwriteWithExistingFile()
    {
        $filter = new FileRename([
            'source'    => $this->oldFile,
            'target'    => $this->newFile,
            'overwrite' => true]);

        copy($this->oldFile, $this->newFile);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => true,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter->getNewName($this->oldFile));
    }

    /**
     * @return void
     */
    public function testGetRandomizedFile()
    {
        $filter = new FileRename([
            'source'    => $this->oldFile,
            'target'    => $this->newFile,
            'randomize' => true
        ]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => true,
            ]],
            $filter->getFile()
        );
        $fileNoExt = $this->tmpPath . DIRECTORY_SEPARATOR . 'newfile';
        $this->assertRegExp('#' . preg_quote($fileNoExt) . '_.{13}\.xml#', $filter->getNewName($this->oldFile));
    }

    /**
     * @return void
     */
    public function testGetRandomizedFileWithoutExtension()
    {
        $fileNoExt = $this->tmpPath . DIRECTORY_SEPARATOR . 'newfile';
        $filter = new FileRename([
            'source'    => $this->oldFile,
            'target'    => $fileNoExt,
            'randomize' => true
        ]);

        $this->assertEquals(
            [0 => [
                'source'    => $this->oldFile,
                'target'    => $fileNoExt,
                'overwrite' => false,
                'randomize' => true,
            ]],
            $filter->getFile()
        );
        $this->assertRegExp('#' . preg_quote($fileNoExt) . '_.{13}#', $filter->getNewName($this->oldFile));
    }

    /**
     * @return void
     */
    public function testAddFileWithString()
    {
        $filter = new FileRename($this->oldFile);
        $filter->addFile($this->newFile);

        $this->assertEquals(
            [0 => [
                'source'    => '*',
                'target'    => $this->newFile,
                'overwrite' => false,
                'randomize' => false,
            ]],
            $filter->getFile()
        );
        $this->assertEquals($this->newFile, $filter($this->oldFile));
        $this->assertEquals('falsefile', $filter('falsefile'));
    }

    /**
     * @return void
     */
    public function testAddFileWithInvalidOption()
    {
        $filter = new FileRename($this->oldFile);
        $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'Invalid options');
        $filter->addFile(1234);
    }

    /**
     * @return void
     */
    public function testInvalidConstruction()
    {
        $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'Invalid options');
        $filter = new FileRename(1234);
    }

    public function returnUnfilteredDataProvider()
    {
        return [
            [null],
            [new \stdClass()],
            [[
                $this->oldFile,
                $this->origFile
            ]]
        ];
    }

    /**
     * @dataProvider returnUnfilteredDataProvider
     * @return void
     */
    public function testReturnUnfiltered($input)
    {
        $filter = new FileRename($this->newFile);

        $this->assertEquals($input, $filter($input));
    }
}


text:
Github Repositories

            Enter Username
            <input type="search" id="search" name="search" title="Search repositories" placeholder="e.g. Kibo007" ng-model='vm.username' ng-model-options="{ debounce: 300 }" >

{{vm.error.message}}

    <loading-spinner show-if="vm.loading"></loading-spinner>
    <listing-repositories></listing-repositories>


text:
$VerbosePreference = 'Continue'

# Load Localization Data
Import-LocalizedData LocalizedData -filename xSQLServer.strings.psd1 -ErrorAction SilentlyContinue
Import-LocalizedData USLocalizedData -filename xSQLServer.strings.psd1 -UICulture en-US -ErrorAction SilentlyContinue

function Connect-SQL
{
[CmdletBinding()]
    param
    (   [ValidateNotNull()]
        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [ValidateNotNull()]
        [System.String]
        $SQLInstanceName = "MSSQLSERVER",

        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    $null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo')

    if($SQLInstanceName -eq "MSSQLSERVER")
    {
        $ConnectSQL = $SQLServer
    }
    else
    {
        $ConnectSQL = "$SQLServer\$SQLInstanceName"
    }
    if ($SetupCredential)
    {
        $SQL = New-Object Microsoft.SqlServer.Management.Smo.Server
        $SQL.ConnectionContext.ConnectAsUser = $true
        $SQL.ConnectionContext.ConnectAsUserPassword = $SetupCredential.GetNetworkCredential().Password
        $SQL.ConnectionContext.ConnectAsUserName = $SetupCredential.GetNetworkCredential().UserName
        $SQL.ConnectionContext.ServerInstance = $ConnectSQL
        $SQL.ConnectionContext.connect()
    }
    else
    {
        $SQL = New-Object Microsoft.SqlServer.Management.Smo.Server $ConnectSQL
    }
    if($SQL)
    {
        New-VerboseMessage -Message "Connected to SQL $ConnectSQL"
        $SQL
    }
    else
    {
        Throw -Message "Failed connecting to SQL $ConnectSQL"
        Exit
    }
}

function New-TerminatingError
{
    [CmdletBinding()]
    [OutputType([System.Management.Automation.ErrorRecord])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ErrorType,

        [Parameter(Mandatory = $false)]
        [String[]]
        $FormatArgs,

        [Parameter(Mandatory = $false)]
        [System.Management.Automation.ErrorCategory]
        $ErrorCategory = [System.Management.Automation.ErrorCategory]::OperationStopped,

        [Parameter(Mandatory = $false)]
        [Object]
        $TargetObject = $null,

        [Parameter(Mandatory = $false)]
        [System.Exception]
        $InnerException = $null
    )

    $errorMessage = $LocalizedData.$ErrorType

    if(!$errorMessage)
    {
        $errorMessage = ($LocalizedData.NoKeyFound -f $ErrorType)

        if(!$errorMessage)
        {
            $errorMessage = ("No Localization key found for key: {0}" -f $ErrorType)
        }
    }

    $errorMessage = ($errorMessage -f $FormatArgs)

    if( $InnerException )
    {
        $errorMessage += " InnerException: $($InnerException.Message)"
    }

    $callStack = Get-PSCallStack

    # Get Name of calling script
    if($callStack[1] -and $callStack[1].ScriptName)
    {
        $scriptPath = $callStack[1].ScriptName

        $callingScriptName = $scriptPath.Split('\')[-1].Split('.')[0]

        $errorId = "$callingScriptName.$ErrorType"
    }
    else
    {
        $errorId = $ErrorType
    }

    Write-Verbose -Message "$($USLocalizedData.$ErrorType -f $FormatArgs) | ErrorType: $errorId"

    $exception = New-Object System.Exception $errorMessage, $InnerException
    $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $ErrorCategory, $TargetObject

    return $errorRecord
}

function New-VerboseMessage
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([String])]
    Param
    (
        [Parameter(Mandatory=$true)]
        $Message
    )
    Write-Verbose -Message ((Get-Date -format yyyy-MM-dd_HH-mm-ss) + ": $Message");

}

function Grant-ServerPerms
{
[CmdletBinding()]
    param
    (
        [ValidateNotNull()]
        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [ValidateNotNull()]
        [System.String]
        $SQLInstanceName= "MSSQLSERVER",

        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential,

        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [System.String]
        $AuthorizedUser
    )

    if(!$SQL)
    {
        $SQL = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential
    }
    Try{
        $sps = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet([Microsoft.SqlServer.Management.Smo.ServerPermission]::AlterAnyAvailabilityGroup)
        $sps.Add([Microsoft.SqlServer.Management.Smo.ServerPermission]::ViewServerState)
        $SQL.Grant($sps,$AuthorizedUser)
        New-VerboseMessage -Message "Granted Permissions to $AuthorizedUser"
        }
    Catch{
        Write-Error "Failed to grant Permissions to $AuthorizedUser."
        }
}

function Grant-CNOPerms
{
[CmdletBinding()]
    Param
    (
        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupNameListener,

        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [System.String]
        $CNO
    )

    #Verify Active Directory Tools are installed, if they are load if not Throw Error
    If (!(Get-Module -ListAvailable | Where-Object {$_.Name -eq "ActiveDirectory"})){
        Throw "Active Directory Module is not installed and is Required."
        Exit
    }
    else{Import-Module ActiveDirectory -ErrorAction Stop -Verbose:$false}
    Try{
        $AG = Get-ADComputer $AvailabilityGroupNameListener

        $comp = $AG.DistinguishedName  # input AD computer distinguishedname
        $acl = Get-Acl "AD:\$comp"
        $u = Get-ADComputer $CNO                        # get the AD user object given full control to computer
        $SID = [System.Security.Principal.SecurityIdentifier] $u.SID

        $identity = [System.Security.Principal.IdentityReference] $SID
        $adRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"
        $type = [System.Security.AccessControl.AccessControlType] "Allow"
        $inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"
        $ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$inheritanceType

        $acl.AddAccessRule($ace)
        Set-Acl -AclObject $acl "AD:\$comp"
        New-VerboseMessage -Message "Granted privileges on $comp to $CNO"
        }
    Catch{
        Throw "Failed to grant Permissions on $comp."
        Exit
        }
}

function New-ListenerADObject
{
[CmdletBinding()]
    Param
    (
        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupNameListener,

        [ValidateNotNull()]
        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [ValidateNotNull()]
        [System.String]
        $SQLInstanceName = "MSSQLSERVER",

        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    if(!$SQL)
    {
        $SQL = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential
    }

    $CNO= $SQL.ClusterName

    #Verify Active Directory Tools are installed, if they are load if not Throw Error
    If (!(Get-Module -ListAvailable | Where-Object {$_.Name -eq "ActiveDirectory"})){
        Throw "Active Directory Module is not installed and is Required."
        Exit
    }
    else{Import-Module ActiveDirectory -ErrorAction Stop -Verbose:$false}
    try{
        $CNO_OU = Get-ADComputer $CNO
        #Accounts for the comma and CN= at the start of Distinguished Name
        #We want to remove these plus the ClusterName to get the actual OU Path.
        $AdditionalChars = 4
        $Trim = $CNO.Length+$AdditionalChars
        $CNOlgth = $CNO_OU.DistinguishedName.Length - $trim
        $OUPath = $CNO_OU.ToString().Substring($Trim,$CNOlgth)
        }
    catch{
        Throw ": Failed to find Computer in AD"
        exit
    }

    $m = Get-ADComputer -Filter {Name -eq $AvailabilityGroupNameListener} -Server $env:USERDOMAIN | Select-Object -Property * | Measure-Object

    If ($m.Count -eq 0)
    {
        Try{
            #Create Computer Object for the AgListenerName
            New-ADComputer -Name $AvailabilityGroupNameListener -SamAccountName $AvailabilityGroupNameListener -Path $OUPath -Enabled $false -Credential $SetupCredential
            New-VerboseMessage -Message "Created Computer Object $AvailabilityGroupNameListener"
            }
        Catch{
               Throw "Failed to Create $AvailabilityGroupNameListener in $OUPath"
            Exit
            }

            $SucccessChk =0

        #Check for AD Object Validate at least three successful attempts
        $i=1
        While ($i -le 5) {
            Try{
                $ListChk = Get-ADComputer -filter {Name -like $AvailabilityGroupNameListener}
                If ($ListChk){$SuccessChk++}
                Start-Sleep -Seconds 10
                If($SuccesChk -eq 3){break}
               }
            Catch{
                 Throw "Failed Validate $AvailabilityGroupNameListener was created in $OUPath"
                 Exit
            }
            $i++
        }
    }
    Try{
        Grant-CNOPerms -AvailabilityGroupNameListener $AvailabilityGroupNameListener -CNO $CNO
        }
    Catch{
          Throw "Failed Validate grant permissions on $AvailabilityGroupNameListener in location $OUPAth to $CNO"
          Exit
        }

}

function Import-SQLPSModule {
    [CmdletBinding()]
    param()

    <# If SQLPS is not removed between resources (if it was started by another DSC resource) getting
    objects with the SQL PS provider will fail in some instances because of some sort of inconsistency. Uncertain why this happens. #>
    if( (Get-Module SQLPS).Count -ne 0 ) {
        Write-Debug "Unloading SQLPS module."
        Remove-Module -Name SQLPS -Force -Verbose:$False
    }

    Write-Debug "SQLPS module changes CWD to SQLSERVER:\ when loading, pushing location to pop it when module is loaded."
    Push-Location

    try {
        New-VerboseMessage -Message "Importing SQLPS module."
        Import-Module -Name SQLPS -DisableNameChecking -Verbose:$False -ErrorAction Stop # SQLPS has unapproved verbs, disable checking to ignore Warnings.
        Write-Debug "SQLPS module imported."
    }
    catch {
        throw New-TerminatingError -ErrorType FailedToImportSQLPSModule -ErrorCategory InvalidOperation -InnerException $_.Exception
    }
    finally {
        Write-Debug "Popping location back to what it was before importing SQLPS module."
        Pop-Location
    }

}

function Get-SQLPSInstanceName
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $InstanceName
    )

    if( $InstanceName -eq "MSSQLSERVER" ) {
        $InstanceName = "DEFAULT"
    }

    return $InstanceName
}

function Get-SQLPSInstance
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $InstanceName,

        [Parameter(Mandatory = $true)]
        [System.String]
        $NodeName
    )

    $InstanceName = Get-SQLPSInstanceName -InstanceName $InstanceName
    $Path = "SQLSERVER:\SQL\$NodeName\$InstanceName"

    New-VerboseMessage -Message "Connecting to $Path as $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"

    Import-SQLPSModule
    $instance = Get-Item $Path

    return $instance
}

function Get-SQLAlwaysOnEndpoint
{
    [CmdletBinding()]
    [OutputType()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Name,

        [Parameter(Mandatory = $true)]
        [System.String]
        $InstanceName,

        [Parameter(Mandatory = $true)]
        [System.String]
        $NodeName
    )

    $instance = Get-SQLPSInstance -InstanceName $InstanceName -NodeName $NodeName
    $Path = "$($instance.PSPath)\Endpoints"

    Write-Debug "Connecting to $Path as $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"

    [String[]] $presentEndpoint = Get-ChildItem $Path
    if( $presentEndpoint.Count -ne 0 -and $presentEndpoint.Contains("[$Name]") ) {
        Write-Debug "Connecting to endpoint $Name as $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
        $endpoint = Get-Item "$Path\$Name"
    } else {
        $endpoint = $null
    }

    return $endpoint
}


text:
package org.jbpm.casemgmt.impl.command;

import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.impl.RegistryContext;
import org.jbpm.casemgmt.impl.event.CaseEventSupport;
import org.jbpm.runtime.manager.impl.PerCaseRuntimeManager;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.internal.identity.IdentityProvider;
import org.kie.api.runtime.Context;

import java.util.Collections;

public abstract class CaseCommand<T> implements ExecutableCommand<T> {

    private static final long serialVersionUID = 4116744986913465571L;

    private CaseEventSupport emptyCaseEventSupport;
    private IdentityProvider identityProvider;

    public CaseCommand(IdentityProvider identityProvider) {
        this.identityProvider = identityProvider;
        this.emptyCaseEventSupport = new CaseEventSupport(identityProvider, Collections.emptyList());
    }

    protected CaseEventSupport getCaseEventSupport(Context context) {
        RuntimeManager runtimeManager = getRuntimeManager(context);
        if (runtimeManager instanceof PerCaseRuntimeManager) {
            CaseEventSupport caseEventSupport = (CaseEventSupport) ((PerCaseRuntimeManager) runtimeManager).getCaseEventSupport();
            if (caseEventSupport != null) {
                return caseEventSupport;
            }
        }

        return emptyCaseEventSupport;
    }

    protected RuntimeManager getRuntimeManager(Context context) {
        KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
        RuntimeManager runtimeManager = (RuntimeManager) ksession.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);

        return runtimeManager;
    }

    public IdentityProvider getIdentityProvider() {
        return this.identityProvider;
    }
}


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

<TITLE>
Uses of Class org.apache.hadoop.metrics.spi.OutputRecord (Hadoop 0.10.0 API)
</TITLE>

<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

Uses of Class
org.apache.hadoop.metrics.spi.OutputRecord

Packages that use OutputRecord

org.apache.hadoop.metrics.file
Implementation of the metrics package that writes the metrics to a file.

org.apache.hadoop.metrics.ganglia
Implementation of the metrics package that sends metric data to
Ganglia.

org.apache.hadoop.metrics.spi
The Service Provider Interface for the Metrics API.

Uses of OutputRecord in org.apache.hadoop.metrics.file

Methods in org.apache.hadoop.metrics.file with parameters of type OutputRecord

 void
FileContext.emitRecord(String contextName,
           String recordName,
           OutputRecord outRec)

          Emits a metrics record to a file.

Uses of OutputRecord in org.apache.hadoop.metrics.ganglia

Methods in org.apache.hadoop.metrics.ganglia with parameters of type OutputRecord

 void
GangliaContext.emitRecord(String contextName,
           String recordName,
           OutputRecord outRec)

Uses of OutputRecord in org.apache.hadoop.metrics.spi

Methods in org.apache.hadoop.metrics.spi with parameters of type OutputRecord

protected  void
NullContext.emitRecord(String contextName,
           String recordName,
           OutputRecord outRec)

          Do-nothing version of emitRecord

protected abstract  void
AbstractMetricsContext.emitRecord(String contextName,
           String recordName,
           OutputRecord outRec)

          Sends a record to the metrics system.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2006 The Apache Software Foundation


text:
class CreateUserChatNamesTable < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  def change
    create_table :chat_names do |t|
      t.integer :user_id, null: false
      t.integer :service_id, null: false
      t.string :team_id, null: false
      t.string :team_domain
      t.string :chat_id, null: false
      t.string :chat_name
      t.datetime :last_used_at
      t.timestamps null: false
    end

    add_index :chat_names, [:user_id, :service_id], unique: true
    add_index :chat_names, [:service_id, :team_id, :chat_id], unique: true
  end
end


text:
    Name
    <input class="form-control" type="text" id="UserAppName" ng-model="UserAppSvc.item.name"/>

    Client ID
    <input type="text" class="form-control" id="UserAppClientId"
           ng-model="UserAppSvc.item.client_id" disabled/>

    Client secret
    <input type="text" class="form-control" id="UserAppClientSecret"
           ng-model="UserAppSvc.item.client_secret" disabled/>

    Redirect uris
    <input type="text" class="form-control" id="UserAppClientRedirectUris"
           ng-model="UserAppSvc.item.redirect_uris" placeholder="{{ 'allowed URIs list, space separated' | translate}}"/>


text:
/*global webapp, Backbone, JST*/

webapp.Views = webapp.Views || {};

(function () {
    'use strict';

    webapp.Views.MachinesEdit = Backbone.ModernView.extend({

        el: "#page-wrapper",

        template: JST['app/scripts/templates/machines/edit.ejs'],

        events: {
            "submit form": "saveMachine"
        },

        serialize: function (renderTemplate) {
            var view = this;

            view.machine = new webapp.Models.Machine({
                id: view.options.machineID
            });

            view.machine.fetch().done(function () {
                renderTemplate({
                    json: {
                        machineID: view.options.machineID,
                        machine: view.machine.toJSON()
                    }
                });
            }).fail(function () {
                renderTemplate({
                    error: {
                        message: "Failed to load machine's data"
                    }
                });
            });
        },

        saveMachine: function (evt) {
            evt.preventDefault();
            var view = this;

            var $form = view.$("form");
            var formData = $form.serializeObject();
            formData.port = parseInt(formData.port, 10);

            var machine = view.machine;

            machine.save(
                formData,
                {
                    wait: true,
                    patch: true,
                    errorPlaceholder: view.$(".alert-placeholder"),
                    success: function () {
                        webapp.router.navigate("machines", { trigger: true });
                    }
                }
            );
        }
    });

})();


text:
#ifndef QTURTLEGUI_HPP_
#define QTURTLEGUI_HPP_

#include <QMainWindow>
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <vector>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <sightedturtlesim/MapSettings.h>
#include <sightedturtlesim/LoadSingleImageMap.h>
#include <sightedturtlesim/Spawn.h>
#include <sightedturtlesim/Kill.h>
#include <opencv2/core/core.hpp>
#include <utility>

class QAction;
class QMenu;
class QScrollArea;
class QScrollBar;
class AbstractImageServer;
class TurtleFrame;
class QImageWidget;
class QSocketNotifier;

class QTurtleGUI : public QMainWindow {
  Q_OBJECT;

public:
  QTurtleGUI();
  ~QTurtleGUI();

  void spin();

  static void sigintHandler(int unused) {
    char a = 1;
    ::write(sigintFd[0], &a, sizeof(a));
  };

public slots:
  void open();
  void spawn();
  void kill();
  void zoomIn();
  void zoomOut();
  void normalSize();
  void fitToWindow();
  void toggleUpdates();
  void autoRefresh();
  void handleSigint();

  bool loadSingleImageMap(QString filename, double ppm);
  std::string spawnTurtle(double x, double y, double z, double angle,
      double hfovDeg, double aspectRatio,
      unsigned int imWidth, unsigned int imHeight, double imFPS, double scale);
  bool killTurtle(const std::string& name);

signals:
  void requestLoadSingleImageMap(QString filename, double ppm);
  void requestSpawnTurtle(double x, double y, double z, double angle,
    double hfovDeg, double aspectRatio,
    unsigned int imWidth, unsigned int imHeight, double imFPS, double scale);
  void requestKillTurtle(const std::string& name);

protected:
  void createActions();
  void createMenus();
  void updateActions();
  void scaleImage(double factor);
  void adjustScrollBar(QScrollBar *scrollBar, double factor);

  bool loadSingleImageMapCB(sightedturtlesim::LoadSingleImageMap::Request& req,
      sightedturtlesim::LoadSingleImageMap::Response& res);
  bool spawnCB(sightedturtlesim::Spawn::Request& req,
      sightedturtlesim::Spawn::Response& res);
  bool killCB(sightedturtlesim::Kill::Request& req,
      sightedturtlesim::Kill::Response& res);

  QMenu* fileMenu;
    QAction* openAct;
    QAction* spawnAct;
    QAction* killAct;
    QAction *closeAct;
  QMenu* viewMenu;
    QAction* zoomInAct;
    QAction* zoomOutAct;
    QAction* normalSizeAct;
    QAction* fitToWindowAct;
    QAction* toggleUpdatesAct;
    QAction* autoRefreshAct;

  QImageWidget* imageWidget;
  QScrollArea* scrollArea;
  double scaleFactor;

  ros::NodeHandle node;
  ros::NodeHandle localNode;
  ros::Publisher mapSettingsPub;
  ros::ServiceServer loadSingleImageMapSrv;
  ros::ServiceServer spawnSrv;
  ros::ServiceServer killSrv;

  AbstractImageServer* imageServer;
  sightedturtlesim::MapSettings mapSettings;
  TurtleFrame* robots;
  boost::mutex robotsMutex;

  boost::thread spinThread;
  double spinRateHz;

  static int sigintFd[2];
  QSocketNotifier* snSigint;

  std::list< std::pair< std::string, cv::Mat > > cachedImageMaps;
};

#endif /* QTURTLEGUI_HPP_ */


text:
<<<<<<< HEAD
<?php

namespace Teaching\GeneralBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Teaching\GeneralBundle\Entity\Activities;
use Teaching\GeneralBundle\Entity\Students;

/**
 * ActivitiesStudents
 *
 * @ORM\Table(  name="activities_students",
 *              uniqueConstraints=
 *                  {@ORM\UniqueConstraint(
 *                      name="as_idx",
 *                      columns={"activity_id", "student_id"}
 *                  )}
 * )
 * @ORM\Entity
 */
class ActivitiesStudents
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Activities")
     */
    private $activity;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Students")
     */
    private $student;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime", nullable=true)
     */
    private $date;

    /**
     * @var integer
     *
     * @ORM\Column(name="score", type="integer", nullable=true)
     */
    private $score;

    /**
     * @var string
     *
     * @ORM\Column(name="state", type="string", length=9, nullable=true)
     */
    private $state;

    /**
     * @var string
     *
     * @ORM\Column(name="observations", type="string", length=255, nullable=true)
     */
    private $observations;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return ActivitiesStudents
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set score
     *
     * @param integer $score
     * @return ActivitiesStudents
     */
    public function setScore($score)
    {
        $this->score = $score;

        return $this;
    }

    /**
     * Get score
     *
     * @return integer
     */
    public function getScore()
    {
        return $this->score;
    }

    /**
     * Set observations
     *
     * @param string $observations
     * @return ActivitiesStudents
     */
    public function setObservations($observations)
    {
        $this->observations = $observations;

        return $this;
    }

    /**
     * Get observations
     *
     * @return string
     */
    public function getObservations()
    {
        return $this->observations;
    }

    /**
     * Set activity
     *
     * @param string $activity
     * @return ActivitiesStudents
     */
    public function setActivity(Activities $activity)
    {
        $this->activity = $activity;

        return $this;
    }

    /**
     * Get activity
     *
     * @return string
     */
    public function getActivity()
    {
        return $this->activity;
    }

    /**
     * Set student
     *
     * @param string $student
     * @return ActivitiesStudents
     */
    public function setStudent(Students $student)
    {
        $this->student = $student;

        return $this;
    }

    /**
     * Get student
     *
     * @return string
     */
    public function getStudent()
    {
        return $this->student;
    }

    /**
     * Set state
     *
     * @param string $state
     * @return ActivitiesStudents
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return string
     */
    public function getState()
    {
        return $this->state;
    }
}
=======
<?php

namespace Teaching\GeneralBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Teaching\GeneralBundle\Entity\Activities;
use Teaching\GeneralBundle\Entity\Students;

/**
 * ActivitiesStudents
 *
 * @ORM\Table(  name="activities_students",
 *              uniqueConstraints=
 *                  {@ORM\UniqueConstraint(
 *                      name="as_idx",
 *                      columns={"activity_id", "student_id"}
 *                  )}
 * )
 * @ORM\Entity
 */
class ActivitiesStudents
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Activities")
     */
    private $activity;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Students")
     */
    private $student;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime", nullable=true)
     */
    private $date;

    /**
     * @var integer
     *
     * @ORM\Column(name="score", type="integer", nullable=true)
     */
    private $score;

    /**
     * @var string
     *
     * @ORM\Column(name="state", type="string", length=9, nullable=true)
     */
    private $state;

    /**
     * @var string
     *
     * @ORM\Column(name="observations", type="string", length=255, nullable=true)
     */
    private $observations;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return ActivitiesStudents
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set score
     *
     * @param integer $score
     * @return ActivitiesStudents
     */
    public function setScore($score)
    {
        $this->score = $score;

        return $this;
    }

    /**
     * Get score
     *
     * @return integer
     */
    public function getScore()
    {
        return $this->score;
    }

    /**
     * Set observations
     *
     * @param string $observations
     * @return ActivitiesStudents
     */
    public function setObservations($observations)
    {
        $this->observations = $observations;

        return $this;
    }

    /**
     * Get observations
     *
     * @return string
     */
    public function getObservations()
    {
        return $this->observations;
    }

    /**
     * Set activity
     *
     * @param string $activity
     * @return ActivitiesStudents
     */
    public function setActivity(Activities $activity)
    {
        $this->activity = $activity;

        return $this;
    }

    /**
     * Get activity
     *
     * @return string
     */
    public function getActivity()
    {
        return $this->activity;
    }

    /**
     * Set student
     *
     * @param string $student
     * @return ActivitiesStudents
     */
    public function setStudent(Students $student)
    {
        $this->student = $student;

        return $this;
    }

    /**
     * Get student
     *
     * @return string
     */
    public function getStudent()
    {
        return $this->student;
    }

    /**
     * Set state
     *
     * @param string $state
     * @return ActivitiesStudents
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return string
     */
    public function getState()
    {
        return $this->state;
    }
}
>>>>>>> master