text:
#define CUSTOM_LAYOUT

using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

[CustomEditor(typeof(OVRCameraController))]

//-------------------------------------------------------------------------------------
// ***** OVRCameraControllerEditor
//
// OVRCameraControllerEditor adds extra functionality in the inspector for the currently
// selected OVRCameraController.
//
public class OVRCameraControllerEditor : Editor
{
	// target component
	private OVRCameraController m_Component;

	// OnEnable
	void OnEnable()
	{
		m_Component = (OVRCameraController)target;
	}

	// OnDestroy
	void OnDestroy()
	{
	}

	// OnInspectorGUI
	public override void OnInspectorGUI()
	{
		GUI.color = Color.white;

		Undo.SetSnapshotTarget(m_Component, "OVRCameraController");

		{
#if CUSTOM_LAYOUT
			OVREditorGUIUtility.Separator();

			m_Component.VerticalFOV         = EditorGUILayout.FloatField("Vertical FOV", m_Component.VerticalFOV);
			m_Component.IPD         		= EditorGUILayout.FloatField("IPD", m_Component.IPD);

			OVREditorGUIUtility.Separator();

			m_Component.CameraRootPosition  = EditorGUILayout.Vector3Field("Camera Root Position", m_Component.CameraRootPosition);
			m_Component.NeckPosition 		= EditorGUILayout.Vector3Field("Neck Position", m_Component.NeckPosition);
			m_Component.EyeCenterPosition 	= EditorGUILayout.Vector3Field("Eye Center Position", m_Component.EyeCenterPosition);

			OVREditorGUIUtility.Separator();

			m_Component.UsePlayerEyeHeight  = EditorGUILayout.Toggle ("Use Player Eye Height", m_Component.UsePlayerEyeHeight);

			OVREditorGUIUtility.Separator();

			m_Component.FollowOrientation = EditorGUILayout.ObjectField("Follow Orientation",
																		m_Component.FollowOrientation,
																		typeof(Transform), true) as Transform;
			m_Component.TrackerRotatesY 	= EditorGUILayout.Toggle("Tracker Rotates Y", m_Component.TrackerRotatesY);

			OVREditorGUIUtility.Separator();

			// Remove Portrait Mode from Inspector window for now
			//m_Component.PortraitMode        = EditorGUILayout.Toggle ("Portrait Mode", m_Component.PortraitMode);
			m_Component.PredictionOn        = EditorGUILayout.Toggle ("Prediction On", m_Component.PredictionOn);
			m_Component.CallInPreRender     = EditorGUILayout.Toggle ("Call in Pre-Render", m_Component.CallInPreRender);
			m_Component.WireMode     		= EditorGUILayout.Toggle ("Wire-Frame Mode", m_Component.WireMode);
			m_Component.LensCorrection     	= EditorGUILayout.Toggle ("Lens Correction", m_Component.LensCorrection);
			m_Component.Chromatic     		= EditorGUILayout.Toggle ("Chromatic", m_Component.Chromatic);

			OVREditorGUIUtility.Separator();

			m_Component.BackgroundColor 	= EditorGUILayout.ColorField("Background Color", m_Component.BackgroundColor);
			m_Component.NearClipPlane       = EditorGUILayout.FloatField("Near Clip Plane", m_Component.NearClipPlane);
			m_Component.FarClipPlane        = EditorGUILayout.FloatField("Far Clip Plane", m_Component.FarClipPlane);

			OVREditorGUIUtility.Separator();
#else
			DrawDefaultInspector ();
#endif
		}

		if (GUI.changed)
		{
			Undo.CreateSnapshot();
			Undo.RegisterSnapshot();
			EditorUtility.SetDirty(m_Component);
		}

		Undo.ClearSnapshotTarget();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.thingsboard.server.service.telemetry.cmd.v2;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import org.thingsboard.server.common.data.query.EntityCountQuery;
import org.thingsboard.server.common.data.query.EntityDataQuery;

public class EntityCountCmd extends DataCmd {

    @Getter
    private final EntityCountQuery query;

    @JsonCreator
    public EntityCountCmd(@JsonProperty("cmdId") int cmdId,
                          @JsonProperty("query") EntityCountQuery query) {
        super(cmdId);
        this.query = query;
    }
}


text:
#ifdef __cplusplus
extern "C" {
#endif

#import <UIKit/UIKit.h>
	static inline CGContextRef ccTexGenContext(CGSize s)
	{
		int tx = s.width;
		int ty = s.height;

		int bitsPerComponent			= 8;
		//int bitsPerPixel				= 32;
		int bytesPerPixel				= (bitsPerComponent * 4)/8;
		int bytesPerRow					= bytesPerPixel * tx;
		//NSInteger myDataLength			= bytesPerRow * ty;

		CGBitmapInfo bitmapInfo			= kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault;

		CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
		CGContextRef context = CGBitmapContextCreate(nil, tx, ty, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
		CGColorSpaceRelease(colorSpace);
		return context;
	}

	static inline UIImage* UIImageFromRectData(NSDictionary *rectData)
	{
		CGSize size = CGSizeFromString([rectData valueForKeyPath:@"size"]);
		float border = [[rectData valueForKeyPath:@"border"] floatValue];
		float radius = [[rectData valueForKeyPath:@"radius"] floatValue];
		float shadowBlur = 0.f;

		if([rectData valueForKeyPath:@"shadow-blur"]){
			shadowBlur = [[rectData valueForKeyPath:@"shadow-blur"] floatValue];
		}

		CGContextRef context = ccTexGenContext(CGSizeMake(size.width+(border+shadowBlur)*2,size.height+(border+shadowBlur)*2));
		CGContextSetLineCap(context, kCGLineCapRound);

		CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
		CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.f);

		if ([rectData valueForKeyPath:@"stroke-color"]) {
			CGRect color = CGRectFromString([rectData valueForKeyPath:@"stroke-color"]);
			CGContextSetRGBStrokeColor(context, color.origin.x, color.origin.y, color.size.width, color.size.height);
		}
		if ([rectData valueForKeyPath:@"fill-color"]) {
			CGRect color = CGRectFromString([rectData valueForKeyPath:@"fill-color"]);
			CGContextSetRGBFillColor(context, color.origin.x, color.origin.y, color.size.width, color.size.height);
		}

		if(shadowBlur > 0.f){
			float shadowColor[] = {0, 0, 0, 1.f};
			CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
			CGColorRef color = CGColorCreate(colorSpace,shadowColor);
			CGColorSpaceRelease(colorSpace);
			CGContextSetShadowWithColor(context, CGSizeZero, shadowBlur, color);
			CGColorRelease(color);
		}

		CGContextSetLineWidth(context, border);
		CGRect rrect = CGRectMake((border+shadowBlur), (border+shadowBlur), size.width , size.height );
		// Make sure corner radius isn't larger than half the shorter side
		if (radius > size.width/2.0)
			radius = size.width/2.0;
		if (radius > size.height/2.0)
			radius = size.height/2.0;
		CGFloat minx = CGRectGetMinX(rrect);
		CGFloat midx = CGRectGetMidX(rrect);
		CGFloat maxx = CGRectGetMaxX(rrect);
		CGFloat miny = CGRectGetMinY(rrect);
		CGFloat midy = CGRectGetMidY(rrect);
		CGFloat maxy = CGRectGetMaxY(rrect);
		CGContextMoveToPoint(context, minx, midy);
		CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
		CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
		CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
		CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);

		CGContextClosePath(context);
		CGContextDrawPath(context, kCGPathFillStroke);
		CGImageRef cgImage = CGBitmapContextCreateImage(context);
		UIImage *image = [UIImage imageWithCGImage:cgImage];
		CGImageRelease(cgImage);
		CGContextRelease(context);
		return image;
	}
#ifdef __cplusplus
}
#endif


text:
package fs

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strconv"

	"github.com/docker/libcontainer/cgroups"
	"github.com/docker/libcontainer/configs"
)

type MemoryGroup struct {
}

func (s *MemoryGroup) Apply(d *data) error {
	dir, err := d.join("memory")
	// only return an error for memory if it was specified
	if err != nil && (d.c.Memory != 0 || d.c.MemoryReservation != 0 || d.c.MemorySwap != 0) {
		return err
	}
	defer func() {
		if err != nil {
			os.RemoveAll(dir)
		}
	}()

	if err := s.Set(dir, d.c); err != nil {
		return err
	}

	return nil
}

func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error {
	if cgroup.Memory != 0 {
		if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Memory, 10)); err != nil {
			return err
		}
	}
	if cgroup.MemoryReservation != 0 {
		if err := writeFile(path, "memory.soft_limit_in_bytes", strconv.FormatInt(cgroup.MemoryReservation, 10)); err != nil {
			return err
		}
	}
	// By default, MemorySwap is set to twice the size of Memory.
	if cgroup.MemorySwap == 0 && cgroup.Memory != 0 {
		if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.Memory*2, 10)); err != nil {
			return err
		}
	}
	if cgroup.MemorySwap > 0 {
		if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.MemorySwap, 10)); err != nil {
			return err
		}
	}

	if cgroup.OomKillDisable {
		if err := writeFile(path, "memory.oom_control", "1"); err != nil {
			return err
		}
	}

	return nil
}

func (s *MemoryGroup) Remove(d *data) error {
	return removePath(d.path("memory"))
}

func (s *MemoryGroup) GetStats(path string, stats *cgroups.Stats) error {
	// Set stats from memory.stat.
	statsFile, err := os.Open(filepath.Join(path, "memory.stat"))
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	defer statsFile.Close()

	sc := bufio.NewScanner(statsFile)
	for sc.Scan() {
		t, v, err := getCgroupParamKeyValue(sc.Text())
		if err != nil {
			return fmt.Errorf("failed to parse memory.stat (%q) - %v", sc.Text(), err)
		}
		stats.MemoryStats.Stats[t] = v
	}

	// Set memory usage and max historical usage.
	value, err := getCgroupParamUint(path, "memory.usage_in_bytes")
	if err != nil {
		return fmt.Errorf("failed to parse memory.usage_in_bytes - %v", err)
	}
	stats.MemoryStats.Usage = value
	value, err = getCgroupParamUint(path, "memory.max_usage_in_bytes")
	if err != nil {
		return fmt.Errorf("failed to parse memory.max_usage_in_bytes - %v", err)
	}
	stats.MemoryStats.MaxUsage = value
	value, err = getCgroupParamUint(path, "memory.failcnt")
	if err != nil {
		return fmt.Errorf("failed to parse memory.failcnt - %v", err)
	}
	stats.MemoryStats.Failcnt = value

	return nil
}


text:
1. Out of a spritesheet (if you have a separately saved icon already go to 2.):
   - Open a spritesheet with the icon of interest, like `largeIcons.svg` in
     Inkscape.
   - Make sure it's the `src/` version of the spritesheet.
   - Copy-paste the icon to a new page. Make sure it preserved its
     original size and aspect ratio, and isn't otherwise altered.
   - To make sure step (3) below doesn't destroy the icon, it might be
     necessary to resize it. Just select everything and use the elements
     in the top toolbar to resize the icon (make sure the aspect ratio is
     preserved).
   - Set the size of the page to match the icon. You may use Inkscape's
     Edit>Resize Page to Selection command to accomplish this.
   - If you chose to include padding in the icon, make sure the icon is
     centered within the page.
   - Save the icon with `_icon.svg` suffix. For instance `list_icon.svg`.

2. Add respective entries to `.gni` files.
   - Update the `devtols_image_files` list in `config/gni/devtools_image_files.gni`.
   - Update the `grd_files_release_sources` list in `config/gni/devtools_grd_files.gni`.

3. Use Icon component in the DevTools front-end:
   - Visit https://docs.google.com/document/d/1EA--IokG6YW51y7unS8dIKUx6EtyjETT0uglmvIpfsg/edit#heading=h.xgjl2srtytjt for more information on that.


text:
package com.helger.schematron.pure.exchange;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.EntityResolver;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.error.SingleError;
import com.helger.commons.io.resource.IReadableResource;
import com.helger.commons.location.SimpleLocation;
import com.helger.commons.string.StringParser;
import com.helger.commons.string.ToStringGenerator;
import com.helger.schematron.CSchematron;
import com.helger.schematron.CSchematronXML;
import com.helger.schematron.SchematronDebug;
import com.helger.schematron.SchematronHelper;
import com.helger.schematron.pure.errorhandler.IPSErrorHandler;
import com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler;
import com.helger.schematron.pure.model.*;
import com.helger.schematron.pure.model.PSDir.EDirValue;
import com.helger.schematron.pure.model.PSRichGroup.ESpace;
import com.helger.xml.microdom.IMicroDocument;
import com.helger.xml.microdom.IMicroElement;
import com.helger.xml.microdom.IMicroText;
import com.helger.xml.microdom.serialize.MicroWriter;
import com.helger.xml.serialize.read.SAXReaderSettings;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
 * Utility class for reading all Schematron elements from a resource.
 *
 * @author Philip Helger
 */
@Immutable
@SuppressFBWarnings ("JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS")
public class PSReader
{
  private static final Logger LOGGER = LoggerFactory.getLogger (PSReader.class);

  private final IReadableResource m_aResource;
  private final IPSErrorHandler m_aErrorHandler;
  private final EntityResolver m_aEntityResolver;
  private boolean m_bLenient = CSchematron.DEFAULT_ALLOW_DEPRECATED_NAMESPACES;

  /**
   * Constructor without an error handler
   *
   * @param aResource
   *        The resource to read the Schematron from. May not be
   *        null.
   */
  public PSReader (@Nonnull final IReadableResource aResource)
  {
    this (aResource, null, null);
  }

  /**
   * Constructor with an error handler
   *
   * @param aResource
   *        The resource to read the Schematron from. May not be
   *        null.
   * @param aErrorHandler
   *        The error handler to use. May be null. If the error
   *        handler is null a {@link LoggingPSErrorHandler} is
   *        automatically created and used.
   * @param aEntityResolver
   *        The XML entity resolver to be used. May be null.
   * @since 4.1.1
   */
  public PSReader (@Nonnull final IReadableResource aResource,
                   @Nullable final IPSErrorHandler aErrorHandler,
                   @Nullable final EntityResolver aEntityResolver)
  {
    ValueEnforcer.notNull (aResource, "Resource");
    m_aResource = aResource;
    m_aErrorHandler = aErrorHandler != null ? aErrorHandler : new LoggingPSErrorHandler ();
    m_aEntityResolver = aEntityResolver;
  }

  /**
   * @return The resource from which the Schematron schema is read. Never
   *         null.
   */
  @Nonnull
  public final IReadableResource getResource ()
  {
    return m_aResource;
  }

  /**
   * @return The error handler used. If no error handler was passed in the
   *         constructor, than a {@link LoggingPSErrorHandler} is automatically
   *         used.
   */
  @Nonnull
  public final IPSErrorHandler getErrorHandler ()
  {
    return m_aErrorHandler;
  }

  /**
   * @return true if the old Schematron namespace is supported,
   *         false if not.
   * @since 5.4.1
   */
  public final boolean isLenient ()
  {
    return m_bLenient;
  }

  /**
   * Allow or disallow the support for old namespace prefix. By default this is
   * deprecated.
   *
   * @param bLenient
   *        true to enable support for old namespace URIs.
   * @return this for chaining
   * @since 5.4.1
   */
  @Nonnull
  public final PSReader setLenient (final boolean bLenient)
  {
    m_bLenient = bLenient;
    return this;
  }

  /**
   * Utility method to get a real attribute value, by trimming spaces, if the
   * value is non-null.
   *
   * @param sAttrValue
   *        The source attribute value. May be null.
   * @return null if the input parameter is null.
   */
  @Nullable
  private static String _getAttributeValue (@Nullable final String sAttrValue)
  {
    return sAttrValue == null ? null : sAttrValue.trim ();
  }

  /**
   * Emit a warning with the registered error handler.
   *
   * @param aSourceElement
   *        The source element where the error occurred.
   * @param sMessage
   *        The main warning message.
   */
  private void _warn (@Nonnull final IPSElement aSourceElement, @Nonnull final String sMessage)
  {
    ValueEnforcer.notNull (aSourceElement, "SourceElement");
    ValueEnforcer.notNull (sMessage, "Message");

    m_aErrorHandler.handleError (SingleError.builderWarn ()
                                            .errorLocation (new SimpleLocation (m_aResource.getPath ()))
                                            .errorFieldName (IPSErrorHandler.getErrorFieldName (aSourceElement))
                                            .errorText (sMessage)
                                            .build ());
  }

  /**
   * Read an <active> element
   *
   * @param eActive
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSActive readActiveFromXML (@Nonnull final IMicroElement eActive)
  {
    final PSActive ret = new PSActive ();
    eActive.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_PATTERN))
        ret.setPattern (sAttrValue);
      else
        ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eActive.forAllChildren (aActiveChild -> {
      switch (aActiveChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aActiveChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aActiveChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            final String sLocalName = eElement.getLocalName ();
            if (sLocalName.equals (CSchematronXML.ELEMENT_DIR))
              ret.addDir (readDirFromXML (eElement));
            else
              if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH))
                ret.addEmph (readEmphFromXML (eElement));
              else
                if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN))
                  ret.addSpan (readSpanFromXML (eElement));
                else
                  _warn (ret, "Unsupported Schematron element '" + sLocalName + "'");
          }
          else
            ret.addForeignElement (eElement.getClone ());

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aActiveChild);
      }
    });
    return ret;
  }

  private static void _handleRichGroup (@Nonnull final String sAttrName,
                                        @Nonnull final String sAttrValue,
                                        @Nonnull final PSRichGroup aRichGroup)
  {
    if (sAttrName.equals (CSchematronXML.ATTR_ICON))
      aRichGroup.setIcon (sAttrValue);
    else
      if (sAttrName.equals (CSchematronXML.ATTR_SEE))
        aRichGroup.setSee (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_FPI))
          aRichGroup.setFPI (sAttrValue);
        else
          if (sAttrName.equals (CSchematronXML.ATTR_XML_LANG))
            aRichGroup.setXmlLang (sAttrValue);
          else
            if (sAttrName.equals (CSchematronXML.ATTR_XML_SPACE))
              aRichGroup.setXmlSpace (ESpace.getFromIDOrNull (sAttrValue));
  }

  private static void _handleLinkableGroup (@Nonnull final String sAttrName,
                                            @Nonnull final String sAttrValue,
                                            @Nonnull final PSLinkableGroup aLinkableGroup)
  {
    if (sAttrName.equals (CSchematronXML.ATTR_ROLE))
      aLinkableGroup.setRole (sAttrValue);
    else
      if (sAttrName.equals (CSchematronXML.ATTR_SUBJECT))
        aLinkableGroup.setSubject (sAttrValue);
  }

  /**
   * Read an <assert> or a <report> element
   *
   * @param eAssertReport
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSAssertReport readAssertReportFromXML (@Nonnull final IMicroElement eAssertReport)
  {
    final PSAssertReport ret = new PSAssertReport (eAssertReport.getLocalName ().equals (CSchematronXML.ELEMENT_ASSERT));

    final PSRichGroup aRichGroup = new PSRichGroup ();
    final PSLinkableGroup aLinkableGroup = new PSLinkableGroup ();
    eAssertReport.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_TEST))
        ret.setTest (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_FLAG))
          ret.setFlag (sAttrValue);
        else
          if (sAttrName.equals (CSchematronXML.ATTR_ID))
            ret.setID (sAttrValue);
          else
            if (sAttrName.equals (CSchematronXML.ATTR_DIAGNOSTICS))
              ret.setDiagnostics (sAttrValue);
            else
              if (PSRichGroup.isRichAttribute (sAttrName))
                _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
              else
                if (PSLinkableGroup.isLinkableAttribute (sAttrName))
                  _handleLinkableGroup (sAttrName, sAttrValue, aLinkableGroup);
                else
                  ret.addForeignAttribute (sAttrName, sAttrValue);
    });
    ret.setRich (aRichGroup);
    ret.setLinkable (aLinkableGroup);

    eAssertReport.forAllChildren (aAssertReportChild -> {
      switch (aAssertReportChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aAssertReportChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aAssertReportChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            final String sLocalName = eElement.getLocalName ();
            if (sLocalName.equals (CSchematronXML.ELEMENT_NAME))
              ret.addName (readNameFromXML (eElement));
            else
              if (sLocalName.equals (CSchematronXML.ELEMENT_VALUE_OF))
                ret.addValueOf (readValueOfFromXML (eElement));
              else
                if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH))
                  ret.addEmph (readEmphFromXML (eElement));
                else
                  if (sLocalName.equals (CSchematronXML.ELEMENT_DIR))
                    ret.addDir (readDirFromXML (eElement));
                  else
                    if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN))
                      ret.addSpan (readSpanFromXML (eElement));
                    else
                      _warn (ret, "Unsupported Schematron element '" + sLocalName + "'");
          }
          else
            ret.addForeignElement (eElement.getClone ());

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aAssertReportChild);
      }
    });
    return ret;
  }

  /**
   * Read a <diagnostic> element
   *
   * @param eDiagnostic
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSDiagnostic readDiagnosticFromXML (@Nonnull final IMicroElement eDiagnostic)
  {
    final PSDiagnostic ret = new PSDiagnostic ();

    final PSRichGroup aRichGroup = new PSRichGroup ();
    eDiagnostic.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_ID))
        ret.setID (sAttrValue);
      else
        if (PSRichGroup.isRichAttribute (sAttrName))
          _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
        else
          ret.addForeignAttribute (sAttrName, sAttrValue);
    });
    ret.setRich (aRichGroup);

    eDiagnostic.forAllChildren (aDiagnosticChild -> {
      switch (aDiagnosticChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aDiagnosticChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aDiagnosticChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            final String sLocalName = eElement.getLocalName ();
            if (sLocalName.equals (CSchematronXML.ELEMENT_VALUE_OF))
              ret.addValueOf (readValueOfFromXML (eElement));
            else
              if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH))
                ret.addEmph (readEmphFromXML (eElement));
              else
                if (sLocalName.equals (CSchematronXML.ELEMENT_DIR))
                  ret.addDir (readDirFromXML (eElement));
                else
                  if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN))
                    ret.addSpan (readSpanFromXML (eElement));
                  else
                    _warn (ret, "Unsupported Schematron element '" + sLocalName + "'");
          }
          else
            ret.addForeignElement (eElement.getClone ());

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aDiagnosticChild);
      }
    });
    return ret;
  }

  /**
   * Read a <diagnostics> element
   *
   * @param eDiagnostics
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSDiagnostics readDiagnosticsFromXML (@Nonnull final IMicroElement eDiagnostics)
  {
    final PSDiagnostics ret = new PSDiagnostics ();

    eDiagnostics.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eDiagnostics.forAllChildElements (eDiagnosticsChild -> {
      if (isValidSchematronNS (eDiagnosticsChild.getNamespaceURI ()))
      {
        if (eDiagnosticsChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE))
          ret.addInclude (readIncludeFromXML (eDiagnosticsChild));
        else
          if (eDiagnosticsChild.getLocalName ().equals (CSchematronXML.ELEMENT_DIAGNOSTIC))
            ret.addDiagnostic (readDiagnosticFromXML (eDiagnosticsChild));
          else
            _warn (ret, "Unsupported Schematron element '" + eDiagnosticsChild.getLocalName () + "'");
      }
      else
        ret.addForeignElement (eDiagnosticsChild.getClone ());
    });
    return ret;
  }

  /**
   * Read a <dir> element
   *
   * @param eDir
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSDir readDirFromXML (@Nonnull final IMicroElement eDir)
  {
    final PSDir ret = new PSDir ();

    eDir.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_VALUE))
        ret.setValue (EDirValue.getFromIDOrNull (sAttrValue));
      else
        ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eDir.forAllChildren (aDirChild -> {
      switch (aDirChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aDirChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aDirChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            _warn (ret, "Unsupported Schematron element '" + eElement.getLocalName () + "'");
          }
          else
            ret.addForeignElement (eElement.getClone ());

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aDirChild);
      }
    });
    return ret;
  }

  /**
   * Read an <emph> element
   *
   * @param eEmph
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSEmph readEmphFromXML (@Nonnull final IMicroElement eEmph)
  {
    final PSEmph ret = new PSEmph ();

    eEmph.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'");
    });

    eEmph.forAllChildren (aEmphChild -> {
      switch (aEmphChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aEmphChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aEmphChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            _warn (ret, "Unsupported Schematron element '" + eElement.getLocalName () + "'");
          }
          else
            _warn (ret, "Unsupported namespace URI '" + eElement.getNamespaceURI () + "'");

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aEmphChild);
      }
    });
    return ret;
  }

  /**
   * Read an <extends> element
   *
   * @param eExtends
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSExtends readExtendsFromXML (@Nonnull final IMicroElement eExtends)
  {
    final PSExtends ret = new PSExtends ();

    eExtends.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_RULE))
        ret.setRule (sAttrValue);
      else
        ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eExtends.forAllChildElements (eChild -> {
      if (isValidSchematronNS (eChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read an <include> element
   *
   * @param eInclude
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSInclude readIncludeFromXML (@Nonnull final IMicroElement eInclude)
  {
    final PSInclude ret = new PSInclude ();

    eInclude.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_HREF))
        ret.setHref (sAttrValue);
      else
        _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'");
    });

    eInclude.forAllChildElements (eValueOfChild -> {
      if (isValidSchematronNS (eValueOfChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eValueOfChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eValueOfChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read a <let> element
   *
   * @param eLet
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSLet readLetFromXML (@Nonnull final IMicroElement eLet)
  {
    final PSLet ret = new PSLet ();

    eLet.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_NAME))
        ret.setName (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_VALUE))
          ret.setValue (sAttrValue);
        else
          _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'");
    });

    eLet.forAllChildElements (eLetChild -> {
      if (isValidSchematronNS (eLetChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eLetChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eLetChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read a <name> element
   *
   * @param eName
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSName readNameFromXML (@Nonnull final IMicroElement eName)
  {
    final PSName ret = new PSName ();

    eName.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_PATH))
        ret.setPath (sAttrValue);
      else
        ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eName.forAllChildElements (eNameChild -> {
      if (isValidSchematronNS (eNameChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eNameChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eNameChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read a <ns> element
   *
   * @param eNS
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSNS readNSFromXML (@Nonnull final IMicroElement eNS)
  {
    final PSNS ret = new PSNS ();

    eNS.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_URI))
        ret.setUri (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_PREFIX))
          ret.setPrefix (sAttrValue);
        else
          ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eNS.forAllChildElements (eLetChild -> {
      if (isValidSchematronNS (eLetChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eLetChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eLetChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read a <p> element
   *
   * @param eP
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSP readPFromXML (@Nonnull final IMicroElement eP)
  {
    final PSP ret = new PSP ();
    eP.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_ID))
        ret.setID (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_CLASS))
          ret.setClazz (sAttrValue);
        else
          if (sAttrName.equals (CSchematronXML.ATTR_ICON))
            ret.setIcon (sAttrValue);
          else
            ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eP.forAllChildren (aChild -> {
      switch (aChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            final String sLocalName = eElement.getLocalName ();
            if (sLocalName.equals (CSchematronXML.ELEMENT_DIR))
              ret.addDir (readDirFromXML (eElement));
            else
              if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH))
                ret.addEmph (readEmphFromXML (eElement));
              else
                if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN))
                  ret.addSpan (readSpanFromXML (eElement));
                else
                  _warn (ret, "Unsupported Schematron element '" + sLocalName + "'");
          }
          else
            ret.addForeignElement (eElement.getClone ());

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aChild);
      }
    });
    return ret;
  }

  /**
   * Read a <param> element
   *
   * @param eParam
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSParam readParamFromXML (@Nonnull final IMicroElement eParam)
  {
    final PSParam ret = new PSParam ();

    eParam.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_NAME))
        ret.setName (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_VALUE))
          ret.setValue (sAttrValue);
        else
          _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'");
    });

    eParam.forAllChildElements (eParamChild -> {
      if (isValidSchematronNS (eParamChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eParamChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eParamChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read a <pattern> element
   *
   * @param ePattern
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSPattern readPatternFromXML (@Nonnull final IMicroElement ePattern)
  {
    final PSPattern ret = new PSPattern ();

    final PSRichGroup aRichGroup = new PSRichGroup ();
    ePattern.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_ABSTRACT))
        ret.setAbstract (StringParser.parseBool (sAttrValue));
      else
        if (sAttrName.equals (CSchematronXML.ATTR_ID))
          ret.setID (sAttrValue);
        else
          if (sAttrName.equals (CSchematronXML.ATTR_IS_A))
            ret.setIsA (sAttrValue);
          else
            if (PSRichGroup.isRichAttribute (sAttrName))
              _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
            else
              ret.addForeignAttribute (sAttrName, sAttrValue);
    });
    ret.setRich (aRichGroup);

    ePattern.forAllChildElements (ePatternChild -> {
      if (isValidSchematronNS (ePatternChild.getNamespaceURI ()))
      {
        if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE))
          ret.addInclude (readIncludeFromXML (ePatternChild));
        else
          if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_TITLE))
            ret.setTitle (readTitleFromXML (ePatternChild));
          else
            if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_P))
              ret.addP (readPFromXML (ePatternChild));
            else
              if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET))
                ret.addLet (readLetFromXML (ePatternChild));
              else
                if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_RULE))
                  ret.addRule (readRuleFromXML (ePatternChild));
                else
                  if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_PARAM))
                    ret.addParam (readParamFromXML (ePatternChild));
                  else
                    _warn (ret, "Unsupported Schematron element '" + ePatternChild.getLocalName () + "' in " + ret.toString ());
      }
      else
        ret.addForeignElement (ePatternChild.getClone ());
    });
    return ret;
  }

  /**
   * Read a <phase> element
   *
   * @param ePhase
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSPhase readPhaseFromXML (@Nonnull final IMicroElement ePhase)
  {
    final PSPhase ret = new PSPhase ();

    final PSRichGroup aRichGroup = new PSRichGroup ();
    ePhase.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_ID))
        ret.setID (sAttrValue);
      else
        if (PSRichGroup.isRichAttribute (sAttrName))
          _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
        else
          ret.addForeignAttribute (sAttrName, sAttrValue);
    });
    ret.setRich (aRichGroup);

    ePhase.forAllChildElements (ePhaseChild -> {
      if (isValidSchematronNS (ePhaseChild.getNamespaceURI ()))
      {
        if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE))
          ret.addInclude (readIncludeFromXML (ePhaseChild));
        else
          if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_P))
            ret.addP (readPFromXML (ePhaseChild));
          else
            if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET))
              ret.addLet (readLetFromXML (ePhaseChild));
            else
              if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_ACTIVE))
                ret.addActive (readActiveFromXML (ePhaseChild));
              else
                _warn (ret, "Unsupported Schematron element '" + ePhaseChild.getLocalName () + "'");
      }
      else
        ret.addForeignElement (ePhaseChild.getClone ());
    });
    return ret;
  }

  /**
   * Read a <rule> element
   *
   * @param eRule
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSRule readRuleFromXML (@Nonnull final IMicroElement eRule)
  {
    final PSRule ret = new PSRule ();

    final PSRichGroup aRichGroup = new PSRichGroup ();
    final PSLinkableGroup aLinkableGroup = new PSLinkableGroup ();
    eRule.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_FLAG))
        ret.setFlag (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_ABSTRACT))
          ret.setAbstract (StringParser.parseBool (sAttrValue));
        else
          if (sAttrName.equals (CSchematronXML.ATTR_CONTEXT))
            ret.setContext (sAttrValue);
          else
            if (sAttrName.equals (CSchematronXML.ATTR_ID))
              ret.setID (sAttrValue);
            else
              if (PSRichGroup.isRichAttribute (sAttrName))
                _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
              else
                if (PSLinkableGroup.isLinkableAttribute (sAttrName))
                  _handleLinkableGroup (sAttrName, sAttrValue, aLinkableGroup);
                else
                  ret.addForeignAttribute (sAttrName, sAttrValue);
    });
    ret.setRich (aRichGroup);
    ret.setLinkable (aLinkableGroup);

    eRule.forAllChildElements (eRuleChild -> {
      if (isValidSchematronNS (eRuleChild.getNamespaceURI ()))
      {
        final String sLocalName = eRuleChild.getLocalName ();
        if (sLocalName.equals (CSchematronXML.ELEMENT_INCLUDE))
          ret.addInclude (readIncludeFromXML (eRuleChild));
        else
          if (sLocalName.equals (CSchematronXML.ELEMENT_LET))
            ret.addLet (readLetFromXML (eRuleChild));
          else
            if (sLocalName.equals (CSchematronXML.ELEMENT_ASSERT) || sLocalName.equals (CSchematronXML.ELEMENT_REPORT))
              ret.addAssertReport (readAssertReportFromXML (eRuleChild));
            else
              if (sLocalName.equals (CSchematronXML.ELEMENT_EXTENDS))
                ret.addExtends (readExtendsFromXML (eRuleChild));
              else
                _warn (ret, "Unsupported Schematron element '" + sLocalName + "'");
      }
      else
        ret.addForeignElement (eRuleChild.getClone ());
    });
    return ret;
  }

  public boolean isValidSchematronNS (@Nullable final String sNamespaceURI)
  {
    return SchematronHelper.isValidSchematronNS (sNamespaceURI, isLenient ());
  }

  /**
   * Parse the Schematron into a pure Java object. This method makes no
   * assumptions on the validity of the document!
   *
   * @param eSchema
   *        The XML element to use. May not be null.
   * @return The created {@link PSSchema} object or null in case of
   *         null document or a fatal error.
   * @throws SchematronReadException
   *         If reading fails
   */
  @Nonnull
  public PSSchema readSchemaFromXML (@Nonnull final IMicroElement eSchema) throws SchematronReadException
  {
    ValueEnforcer.notNull (eSchema, "Schema");

    if (!isLenient () && SchematronHelper.isDeprecatedSchematronNS (eSchema.getNamespaceURI ()))
      LOGGER.warn ("OLD Schematron NS '" +
                   eSchema.getNamespaceURI () +
                   "' is deprecated, use '" +
                   CSchematron.NAMESPACE_SCHEMATRON +
                   "' instead");

    if (!isValidSchematronNS (eSchema.getNamespaceURI ()))
      throw new SchematronReadException (m_aResource, "The passed element is not an ISO Schematron element!");

    final PSSchema ret = new PSSchema (m_aResource);
    final PSRichGroup aRichGroup = new PSRichGroup ();
    eSchema.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_ID))
        ret.setID (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_SCHEMA_VERSION))
          ret.setSchemaVersion (sAttrValue);
        else
          if (sAttrName.equals (CSchematronXML.ATTR_DEFAULT_PHASE))
            ret.setDefaultPhase (sAttrValue);
          else
            if (sAttrName.equals (CSchematronXML.ATTR_QUERY_BINDING))
              ret.setQueryBinding (sAttrValue);
            else
              if (PSRichGroup.isRichAttribute (sAttrName))
                _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
              else
                ret.addForeignAttribute (sAttrName, sAttrValue);
    });
    ret.setRich (aRichGroup);

    eSchema.forAllChildElements (eSchemaChild -> {
      if (isValidSchematronNS (eSchemaChild.getNamespaceURI ()))
      {
        if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE))
          ret.addInclude (readIncludeFromXML (eSchemaChild));
        else
          if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_TITLE))
            ret.setTitle (readTitleFromXML (eSchemaChild));
          else
            if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_NS))
              ret.addNS (readNSFromXML (eSchemaChild));
            else
              if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_P))
              {
                final PSP aP = readPFromXML (eSchemaChild);
                if (ret.hasNoPatterns ())
                  ret.addStartP (aP);
                else
                  ret.addEndP (aP);
              }
              else
                if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET))
                  ret.addLet (readLetFromXML (eSchemaChild));
                else
                  if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_PHASE))
                    ret.addPhase (readPhaseFromXML (eSchemaChild));
                  else
                    if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_PATTERN))
                      ret.addPattern (readPatternFromXML (eSchemaChild));
                    else
                      if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_DIAGNOSTICS))
                        ret.setDiagnostics (readDiagnosticsFromXML (eSchemaChild));
                      else
                        _warn (ret, "Unsupported Schematron element '" + eSchemaChild.getLocalName () + "'");
      }
      else
        ret.addForeignElement (eSchemaChild.getClone ());
    });
    return ret;
  }

  /**
   * Read a <span> element
   *
   * @param eSpan
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSSpan readSpanFromXML (@Nonnull final IMicroElement eSpan)
  {
    final PSSpan ret = new PSSpan ();

    eSpan.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_CLASS))
        ret.setClazz (sAttrValue);
      else
        ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eSpan.forAllChildren (aSpanChild -> {
      switch (aSpanChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aSpanChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aSpanChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            _warn (ret, "Unsupported Schematron element '" + eElement.getLocalName () + "'");
          }
          else
            ret.addForeignElement (eElement.getClone ());

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aSpanChild);
      }
    });
    return ret;
  }

  /**
   * Read a <title> element
   *
   * @param eTitle
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSTitle readTitleFromXML (@Nonnull final IMicroElement eTitle)
  {
    final PSTitle ret = new PSTitle ();

    eTitle.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'");
    });

    eTitle.forAllChildren (aTitleChild -> {
      switch (aTitleChild.getType ())
      {
        case TEXT:
          ret.addText (((IMicroText) aTitleChild).getNodeValue ());
          break;
        case ELEMENT:
          final IMicroElement eElement = (IMicroElement) aTitleChild;
          if (isValidSchematronNS (eElement.getNamespaceURI ()))
          {
            final String sLocalName = eElement.getLocalName ();
            if (sLocalName.equals (CSchematronXML.ELEMENT_DIR))
              ret.addDir (readDirFromXML (eElement));
            else
              _warn (ret, "Unsupported Schematron element '" + sLocalName + "'");
          }
          else
            _warn (ret, "Unsupported namespace URI '" + eElement.getNamespaceURI () + "'");

          break;
        case COMMENT:
          // Ignore comments
          break;
        default:
          _warn (ret, "Unsupported child node: " + aTitleChild);
      }
    });
    return ret;
  }

  /**
   * Read a <value-of> element
   *
   * @param eValueOf
   *        The source micro element. Never null.
   * @return The created domain object. May not be null.
   */
  @Nonnull
  public PSValueOf readValueOfFromXML (@Nonnull final IMicroElement eValueOf)
  {
    final PSValueOf ret = new PSValueOf ();

    eValueOf.forAllAttributes ( (sNS, sAttrName, sVal) -> {
      final String sAttrValue = _getAttributeValue (sVal);
      if (sAttrName.equals (CSchematronXML.ATTR_SELECT))
        ret.setSelect (sAttrValue);
      else
        ret.addForeignAttribute (sAttrName, sAttrValue);
    });

    eValueOf.forAllChildElements (eValueOfChild -> {
      if (isValidSchematronNS (eValueOfChild.getNamespaceURI ()))
      {
        _warn (ret, "Unsupported Schematron element '" + eValueOfChild.getLocalName () + "'");
      }
      else
        _warn (ret, "Unsupported namespace URI '" + eValueOfChild.getNamespaceURI () + "'");
    });
    return ret;
  }

  /**
   * Read the schema from the resource supplied in the constructor. First all
   * includes are resolved and than {@link #readSchemaFromXML(IMicroElement)} is
   * called.
   *
   * @return The read {@link PSSchema}.
   * @throws SchematronReadException
   *         If reading fails
   */
  @Nonnull
  public PSSchema readSchema () throws SchematronReadException
  {
    // Resolve all includes as the first action
    final SAXReaderSettings aSettings = new SAXReaderSettings ().setEntityResolver (m_aEntityResolver);

    final IMicroDocument aDoc = SchematronHelper.getWithResolvedSchematronIncludes (m_aResource, aSettings, m_aErrorHandler, m_bLenient);
    if (aDoc == null || aDoc.getDocumentElement () == null)
      throw new SchematronReadException (m_aResource, "Failed to resolve includes in Schematron resource " + m_aResource);

    if (SchematronDebug.isShowResolvedSourceSchematron ())
      LOGGER.info ("Resolved source Schematron:\n" + MicroWriter.getNodeAsString (aDoc));

    return readSchemaFromXML (aDoc.getDocumentElement ());
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("resource", m_aResource).append ("errorHandler", m_aErrorHandler).getToString ();
  }
}


text:
package multiplex

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"net"
	"sync"
	"time"

	mpool "gx/ipfs/QmRQhVisS8dmPbjBUthVkenn81pBxrx1GxE281csJhm2vL/go-msgio/mpool"
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
)

var log = logging.Logger("multiplex")

var MaxMessageSize = 1 << 20

const (
	NewStream = iota
	Receiver
	Initiator
	CloseLocal
	Close
)

type Multiplex struct {
	con       net.Conn
	buf       *bufio.Reader
	nextID    uint64
	closed    chan struct{}
	initiator bool

	wrLock sync.Mutex

	nstreams chan *Stream
	errs     chan error

	hdrBuf []byte

	channels map[uint64]*Stream
	chLock   sync.Mutex
}

func NewMultiplex(con net.Conn, initiator bool) *Multiplex {
	mp := &Multiplex{
		con:       con,
		initiator: initiator,
		buf:       bufio.NewReader(con),
		channels:  make(map[uint64]*Stream),
		closed:    make(chan struct{}),
		nstreams:  make(chan *Stream, 16),
		errs:      make(chan error),
		hdrBuf:    make([]byte, 20),
	}

	go mp.handleIncoming()

	return mp
}

func (mp *Multiplex) newStream(id uint64, name string, initiator bool) *Stream {
	var hfn uint64
	if initiator {
		hfn = Initiator
	} else {
		hfn = Receiver
	}
	return &Stream{
		id:     id,
		name:   name,
		header: (id << 3) | hfn,
		dataIn: make(chan []byte, 8),
		mp:     mp,
	}
}

func (m *Multiplex) Accept() (*Stream, error) {
	select {
	case s, ok := <-m.nstreams:
		if !ok {
			return nil, errors.New("multiplex closed")
		}
		return s, nil
	case err := <-m.errs:
		return nil, err
	case <-m.closed:
		return nil, errors.New("multiplex closed")
	}
}

func (mp *Multiplex) Close() error {
	if mp.IsClosed() {
		return nil
	}
	close(mp.closed)
	var streams []*Stream
	mp.chLock.Lock()
	for _, s := range mp.channels {
		streams = append(streams, s)
	}
	mp.chLock.Unlock()
	var retErr error
	for _, s := range streams {
		if err := s.Close(); err != nil {
			retErr = err
		}
	}
	mp.con.Close()
	return retErr
}

func (mp *Multiplex) IsClosed() bool {
	select {
	case <-mp.closed:
		return true
	default:
		return false
	}
}

func (mp *Multiplex) sendMsg(header uint64, data []byte, dl time.Time) error {
	mp.wrLock.Lock()
	defer mp.wrLock.Unlock()
	if !dl.IsZero() {
		if err := mp.con.SetWriteDeadline(dl); err != nil {
			return err
		}
	}
	n := binary.PutUvarint(mp.hdrBuf, header)
	n += binary.PutUvarint(mp.hdrBuf[n:], uint64(len(data)))
	_, err := mp.con.Write(mp.hdrBuf[:n])
	if err != nil {
		return err
	}

	if len(data) != 0 {
		_, err = mp.con.Write(data)
		if err != nil {
			return err
		}
	}
	if !dl.IsZero() {
		if err := mp.con.SetWriteDeadline(time.Time{}); err != nil {
			return err
		}
	}

	return nil
}

func (mp *Multiplex) nextChanID() (out uint64) {
	if mp.initiator {
		out = mp.nextID + 1
	} else {
		out = mp.nextID
	}
	mp.nextID += 2
	return
}

func (mp *Multiplex) NewStream() (*Stream, error) {
	return mp.NewNamedStream("")
}

func (mp *Multiplex) NewNamedStream(name string) (*Stream, error) {
	mp.chLock.Lock()
	sid := mp.nextChanID()
	header := (sid << 3) | NewStream

	if name == "" {
		name = fmt.Sprint(sid)
	}
	s := mp.newStream(sid, name, true)
	mp.channels[sid] = s
	mp.chLock.Unlock()

	err := mp.sendMsg(header, []byte(name), time.Time{})
	if err != nil {
		return nil, err
	}

	return s, nil
}

func (mp *Multiplex) sendErr(err error) {
	select {
	case mp.errs <- err:
	case <-mp.closed:
	}
}

func (mp *Multiplex) handleIncoming() {
	defer mp.Close()
	for {
		ch, tag, err := mp.readNextHeader()
		if err != nil {
			mp.sendErr(err)
			return
		}

		b, err := mp.readNext()
		if err != nil {
			mp.sendErr(err)
			return
		}

		mp.chLock.Lock()
		msch, ok := mp.channels[ch]
		mp.chLock.Unlock()
		switch tag {
		case NewStream:
			if ok {
				log.Debugf("received NewStream message for existing stream: %d", ch)
				continue
			}

			name := string(b)
			msch = mp.newStream(ch, name, false)
			mp.chLock.Lock()
			mp.channels[ch] = msch
			mp.chLock.Unlock()
			select {
			case mp.nstreams <- msch:
			case <-mp.closed:
				return
			}

		case Close, CloseLocal:
			if !ok {
				continue
			}

			mp.chLock.Lock()
			msch.clLock.Lock()
			if msch.closedLocal {
				delete(mp.channels, ch)
			}
			msch.closedRemote = true
			close(msch.dataIn)
			msch.clLock.Unlock()
			mp.chLock.Unlock()
		default:
			if !ok {
				log.Debugf("message for non-existant stream, dropping data: %d", ch)
				continue
			}
			msch.receive(b)
		}
	}
}

func (mp *Multiplex) readNextHeader() (uint64, uint64, error) {
	h, err := binary.ReadUvarint(mp.buf)
	if err != nil {
		return 0, 0, err
	}

	// get channel ID
	ch := h >> 3

	rem := h & 7

	return ch, rem, nil
}

func (mp *Multiplex) readNext() ([]byte, error) {
	// get length
	l, err := binary.ReadUvarint(mp.buf)
	if err != nil {
		return nil, err
	}

	if l > uint64(MaxMessageSize) {
		return nil, fmt.Errorf("message size too large!")
	}

	if l == 0 {
		return nil, nil
	}

	buf := mpool.ByteSlicePool.Get(uint32(l)).([]byte)[:l]
	n, err := io.ReadFull(mp.buf, buf)
	if err != nil {
		return nil, err
	}

	return buf[:n], nil
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm8s_gpio.h"

/** @addtogroup STM8S_StdPeriph_Driver
  * @{
  */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/* Public functions ----------------------------------------------------------*/

/**
  * @addtogroup GPIO_Public_Functions
  * @{
  */

/**
  * @brief  Deinitializes the GPIOx peripheral registers to their default reset values.
  * @param  GPIOx: Select the GPIO peripheral number (x = A to I).
  * @retval None
  */
void GPIO_DeInit(GPIO_TypeDef* GPIOx)
{
    GPIOx->ODR = GPIO_ODR_RESET_VALUE; /* Reset Output Data Register */
    GPIOx->DDR = GPIO_DDR_RESET_VALUE; /* Reset Data Direction Register */
    GPIOx->CR1 = GPIO_CR1_RESET_VALUE; /* Reset Control Register 1 */
    GPIOx->CR2 = GPIO_CR2_RESET_VALUE; /* Reset Control Register 2 */
}

/**
  * @brief  Initializes the GPIOx according to the specified parameters.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : This parameter contains the pin number, it can be any value
  *         of the @ref GPIO_Pin_TypeDef enumeration.
  * @param  GPIO_Mode : This parameter can be a value of the
  *         @Ref GPIO_Mode_TypeDef enumeration.
  * @retval None
  */

void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin, GPIO_Mode_TypeDef GPIO_Mode)
{
    /*----------------------*/
    /* Check the parameters */
    /*----------------------*/

    assert_param(IS_GPIO_MODE_OK(GPIO_Mode));
    assert_param(IS_GPIO_PIN_OK(GPIO_Pin));

  /* Reset corresponding bit to GPIO_Pin in CR2 register */
  GPIOx->CR2 &= (uint8_t)(~(GPIO_Pin));

    /*-----------------------------*/
    /* Input/Output mode selection */
    /*-----------------------------*/

    if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x80) != (uint8_t)0x00) /* Output mode */
    {
        if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x10) != (uint8_t)0x00) /* High level */
        {
            GPIOx->ODR |= (uint8_t)GPIO_Pin;
        }
        else /* Low level */
        {
            GPIOx->ODR &= (uint8_t)(~(GPIO_Pin));
        }
        /* Set Output mode */
        GPIOx->DDR |= (uint8_t)GPIO_Pin;
    }
    else /* Input mode */
    {
        /* Set Input mode */
        GPIOx->DDR &= (uint8_t)(~(GPIO_Pin));
    }

    /*------------------------------------------------------------------------*/
    /* Pull-Up/Float (Input) or Push-Pull/Open-Drain (Output) modes selection */
    /*------------------------------------------------------------------------*/

    if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x40) != (uint8_t)0x00) /* Pull-Up or Push-Pull */
    {
        GPIOx->CR1 |= (uint8_t)GPIO_Pin;
    }
    else /* Float or Open-Drain */
    {
        GPIOx->CR1 &= (uint8_t)(~(GPIO_Pin));
    }

    /*-----------------------------------------------------*/
    /* Interrupt (Input) or Slope (Output) modes selection */
    /*-----------------------------------------------------*/

    if ((((uint8_t)(GPIO_Mode)) & (uint8_t)0x20) != (uint8_t)0x00) /* Interrupt or Slow slope */
    {
        GPIOx->CR2 |= (uint8_t)GPIO_Pin;
    }
    else /* No external interrupt or No slope control */
    {
        GPIOx->CR2 &= (uint8_t)(~(GPIO_Pin));
    }
}

/**
  * @brief  Writes data to the specified GPIO data port.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_PortVal : Specifies the value to be written to the port output
  *         data register.
  * @retval None
  */
void GPIO_Write(GPIO_TypeDef* GPIOx, uint8_t PortVal)
{
    GPIOx->ODR = PortVal;
}

/**
  * @brief  Writes high level to the specified GPIO pins.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  PortPins : Specifies the pins to be turned high to the port output.
  *         data register.
  * @retval None
  */
void GPIO_WriteHigh(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef PortPins)
{
    GPIOx->ODR |= (uint8_t)PortPins;
}

/**
  * @brief  Writes low level to the specified GPIO pins.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  PortPins : Specifies the pins to be turned low to the port output.
  *         data register.
  * @retval None
  */
void GPIO_WriteLow(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef PortPins)
{
    GPIOx->ODR &= (uint8_t)(~PortPins);
}

/**
  * @brief  Writes reverse level to the specified GPIO pins.
  * @note   The port must be configured in output mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  PortPins : Specifies the pins to be reversed to the port output.
  *         data register.
  * @retval None
  */
void GPIO_WriteReverse(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef PortPins)
{
    GPIOx->ODR ^= (uint8_t)PortPins;
}

/**
  * @brief  Reads the specified GPIO output data port.
  * @note   The port must be configured in input mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @retval GPIO output data port value.
  */
uint8_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx)
{
    return ((uint8_t)GPIOx->ODR);
}

/**
  * @brief  Reads the specified GPIO input data port.
  * @note   The port must be configured in input mode.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @retval GPIO input data port value.
  */
uint8_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx)
{
    return ((uint8_t)GPIOx->IDR);
}

/**
  * @brief  Reads the specified GPIO input data pin.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pin number.
  * @retval BitStatus : GPIO input pin status.
  */
BitStatus GPIO_ReadInputPin(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin)
{
    return ((BitStatus)(GPIOx->IDR & (uint8_t)GPIO_Pin));
}

/**
  * @brief  Configures the external pull-up on GPIOx pins.
  * @param  GPIOx : Select the GPIO peripheral number (x = A to I).
  * @param  GPIO_Pin : Specifies the pin number
  * @param  NewState : The new state of the pull up pin.
  * @retval None
  */
void GPIO_ExternalPullUpConfig(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin, FunctionalState NewState)
{
    /* Check the parameters */
    assert_param(IS_GPIO_PIN_OK(GPIO_Pin));
    assert_param(IS_FUNCTIONALSTATE_OK(NewState));

    if (NewState != DISABLE) /* External Pull-Up Set*/
    {
        GPIOx->CR1 |= (uint8_t)GPIO_Pin;
    } else /* External Pull-Up Reset*/
    {
        GPIOx->CR1 &= (uint8_t)(~(GPIO_Pin));
    }
}

/**
  * @}
  */

/**
  * @}
  */

/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/


text:
use nom::{be_u16, IResult};

use attribute_info::attribute_parser;

use field_info::{FieldAccessFlags, FieldInfo};

pub fn field_parser(input: &[u8]) -> IResult<&[u8], FieldInfo> {
    do_parse!(
        input,
        access_flags: be_u16
            >> name_index: be_u16
            >> descriptor_index: be_u16
            >> attributes_count: be_u16
            >> attributes: count!(attribute_parser, attributes_count as usize)
            >> (FieldInfo {
                access_flags: FieldAccessFlags::from_bits_truncate(access_flags),
                name_index,
                descriptor_index,
                attributes_count,
                attributes,
            })
    )
}


text:
@interface OCTSymlinkContent : OCTContent

// The path to the symlink target.
@property (nonatomic, copy, readonly) NSString *target;

@end


text:
package com.mapswithme.maps.uber;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mapswithme.maps.R;
import com.mapswithme.maps.routing.RoutingController;

import java.util.List;

public class UberAdapter extends PagerAdapter
{
  @NonNull
  private final Context mContext;
  @NonNull
  private final List<UberInfo.Product> mProducts;

  public UberAdapter(@NonNull Context context, @NonNull List<UberInfo.Product> products)
  {
    mContext = context;
    mProducts = products;
  }

  @Override
  public int getCount()
  {
    return mProducts.size();
  }

  @Override
  public boolean isViewFromObject(View view, Object object)
  {
    return view == object;
  }

  @Override
  public Object instantiateItem(ViewGroup container, int position)
  {
    UberInfo.Product product = mProducts.get(position);

    View v = LayoutInflater.from(mContext).inflate(R.layout.uber_pager_item, container, false);
    TextView name = (TextView) v.findViewById(R.id.product_name);
    name.setText(product.getName());
    TextView timeAndPrice = (TextView) v.findViewById(R.id.arrival_time_price);
    int time = Integer.parseInt(product.getTime());
    CharSequence waitTime = RoutingController.formatRoutingTime(mContext, time, R.dimen.text_size_body_3);
    timeAndPrice.setText(mContext.getString(R.string.taxi_wait, waitTime + " • " + product.getPrice()));
    container.addView(v, 0);
    return v;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object)
  {
    container.removeView((View) object);
  }
}


text:
pip install --upgrade .

python ./tests/tests.py


text:
package sshutils

import (
	"crypto/rand"
	"crypto/rsa"
	"time"

	"github.com/gravitational/trace"
	"golang.org/x/crypto/ssh"

	"github.com/gravitational/teleport/api/constants"
)

// MakeTestSSHCA generates a new SSH certificate authority for tests.
func MakeTestSSHCA() (ssh.Signer, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, constants.RSAKeySize)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	ca, err := ssh.NewSignerFromKey(privateKey)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return ca, nil
}

// MakeSpoofedHostCert makes an SSH host certificate that claims to be signed
// by the provided CA but in fact is signed by a different CA.
func MakeSpoofedHostCert(realCA ssh.Signer) (ssh.Signer, error) {
	fakeCA, err := MakeTestSSHCA()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return makeHostCert(realCA.PublicKey(), fakeCA)
}

// MakeRealHostCert makes an SSH host certificate that is signed by the
// provided CA.
func MakeRealHostCert(realCA ssh.Signer) (ssh.Signer, error) {
	return makeHostCert(realCA.PublicKey(), realCA)
}

func makeHostCert(signKey ssh.PublicKey, signer ssh.Signer) (ssh.Signer, error) {
	priv, err := rsa.GenerateKey(rand.Reader, constants.RSAKeySize)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	privSigner, err := ssh.NewSignerFromKey(priv)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	pub, err := ssh.NewPublicKey(priv.Public())
	if err != nil {
		return nil, trace.Wrap(err)
	}

	nonce := make([]byte, 32)
	if _, err = rand.Read(nonce); err != nil {
		return nil, trace.Wrap(err)
	}

	cert := &ssh.Certificate{
		Nonce:           nonce,
		Key:             pub,
		CertType:        ssh.HostCert,
		SignatureKey:    signKey,
		ValidPrincipals: []string{"127.0.0.1"},
		ValidBefore:     uint64(time.Now().Add(time.Hour).Unix()),
	}

	// We cannot use ssh.Certificate SignCert method since we're intentionally
	// setting invalid signature key to make a spoofed cert in some tests.
	//
	// When marshaling cert for signing, last 4 bytes containing trailing
	// signature length are dropped:
	//
	// https://cs.opensource.google/go/x/crypto/+/32db7946:ssh/certs.go;l=456-462
	bytesForSigning := cert.Marshal()
	bytesForSigning = bytesForSigning[:len(bytesForSigning)-4]

	cert.Signature, err = signer.Sign(rand.Reader, bytesForSigning)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	certSigner, err := ssh.NewCertSigner(cert, privSigner)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return certSigner, nil
}


text:
class Admin::PostsController <  Admin::ArticleBaseController
    after_filter(:except => :index) {|c| c.chito_cache_expire(:type => "posts_index/*")}
    after_filter(:except => [:index, :update, :recategory_selected]) do |c|
        c.sidebar_cache_expire(:archive)
        c.sidebar_cache_expire(:calendar)
    end

    def index
        @categories = @user.categories
        @posts = @user.find_articles(:type => :posts, :category_id => params[:category_id], :page => params[:page], :per_page => 20)
    end

    def create
        super
        @article.published_at = Time.now unless @article.published_at
        save_and_redirect
        send_trackback(params[:trackbacks], @article)
    end

    def update
        super
        @article.published_at = Time.now unless @article.published_at
        save_and_redirect
        send_trackback(params[:trackbacks], @article)
    end

    def destroy
        super
        notice_stickie t(:post_successfully_deleted, :scope => [:txt, :controller, :admin, :posts])
        redirect_to admin_posts_path(:page => params[:page])
    end

    def destroy_selected
        super
        notice_stickie t(:posts_successfully_deleted, :scope => [:txt, :controller, :admin, :posts])
        redirect_to admin_posts_path(:page => params[:page])
    end

    def recategory_selected
        if params[:ids] && @category = @user.categories.find(params[:recategory])
            for article in @user.articles.find(params[:ids])
                article.category = @category
                article.save
            end
        end
        notice_stickie t(:posts_successfully_recategoried, :scope => [:txt, :controller, :admin, :posts])
        redirect_to admin_posts_path(:page => params[:page])
    end

    private

    def save_and_redirect
        @article.is_draft = false
        @article.is_page = false
        unless_continue_edit { redirect_to chito_post_path(@article, :format => :html) }
    end

    def send_trackback(url, post)
        return if url.blank?
        post_url = post_url(post, :format => html)
        query = post.trackback_params.merge(:url => post_url).to_query
        trackback_url = URI.parse(url)
        Net::HTTP.start(trackback_url.host, trackback_url.port) do |http|
            path = trackback_url.path
            path << "?#{trackback_url.query}" if trackback_url.query
            http.post(path, query,'Content-type' => 'application/x-www-form-urlencoded; charset=utf-8')
        end

        rescue
    end

end


text:
/*!
 * Bootstrap Context Menu
 * Version: 2.1
 * A small variation of the dropdown plugin by @sydcanem
 * https://github.com/sydcanem/bootstrap-contextmenu
 *
 * New options added by @jeremyhubble for javascript launching
 *  $('#elem').contextmenu({target:'#menu',before:function(e) { return true; } });
 *
 *
 * Twitter Bootstrap (http://twitter.github.com/bootstrap).
 */

/* =========================================================
 * bootstrap-contextmenu.js
 * =========================================================
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!(function($) {

	"use strict"; // jshint ;_;

	/* CONTEXTMENU CLASS DEFINITION
	 * ============================ */

	var ContextMenu = function (elements, options) {
			this.$elements = $(elements)
			this.options = options
			this.before = this.options.before || this.before
			this.onItem = this.options.onItem || this.onItem
			if (this.options.target)
				this.$elements.attr('data-target',this.options.target)

			this.listen()
		}

	ContextMenu.prototype = {

		constructor: ContextMenu
		,show: function(e) {

			var $this = $(this)
				, $menu
				, $contextmenu
				, evt;

			if ($this.is('.disabled, :disabled')) return;

			evt = $.Event('context');
			if (!this.before.call(this,e,$(e.currentTarget))) return;
			this.$elements.trigger(evt);

			$menu = this.getMenu();

			var tp = this.getPosition(e, $menu);
			$menu.attr('style', '')
				.css(tp)
				.data('_context_this_ref', this)
				.addClass('open');

			return false;
		}

		,closemenu: function(e) {
			this.getMenu().removeClass('open');
		}

		,before: function(e) {
			return true;
		}

		,onItem: function(e, context) {
			return true;
		}

		,listen: function () {
			var _this = this;
			this.$elements
					.on('contextmenu.context.data-api', $.proxy(this.show, this));
			$('html')
					.on('click.context.data-api', $.proxy(this.closemenu, this));

			var $target = $(this.$elements.attr('data-target'));

			$target.on('click.context.data-api', function (e) {
				if($(this).data('_context_this_ref') == _this) {
					_this.onItem.call(this,e,$(e.target));
				}
			});

			$('html').on('click.context.data-api', function (e) {
				if (!e.ctrlKey) {
					$target.removeClass('open');
				}
			});
		}

		,destroy: function() {
			this.$elements.off('.context.data-api').removeData('context');
			$('html').off('.context.data-api');

			var $target = $(this.$elements.attr('data-target'));
			$target.off('.context.data-api');
		}

		,getMenu: function () {
			var selector = this.$elements.attr('data-target')
				, $menu;

			if (!selector) {
				selector = this.$elements.attr('href')
				selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
			}

			$menu = $(selector);

			return $menu;
		}

		,getPosition: function(e, $menu) {
			var mouseX = e.clientX
				, mouseY = e.clientY
				, boundsX = $(window).width()
				, boundsY = $(window).height()
				, menuWidth = $menu.find('.dropdown-menu').outerWidth()
				, menuHeight = $menu.find('.dropdown-menu').outerHeight()
				, tp = {"position":"fixed"}
				, Y, X;

			if (mouseY + menuHeight > boundsY) {
				Y = {"top": mouseY - menuHeight};
			} else {
				Y = {"top": mouseY};
			}

			if ((mouseX + menuWidth > boundsX) && ((mouseX - menuWidth) > 0)) {
				X = {"left": mouseX - menuWidth};
			} else {
				X = {"left": mouseX};
			}

			return $.extend(tp, Y, X);
		}

		,clearMenus: function(e) {
			if (!e.ctrlKey) {
				$('[data-toggle=context]').each(function() {
					this.getMenu()
						.removeClass('open');
				});
			}
		}
	}

	/* CONTEXT MENU PLUGIN DEFINITION
	 * ========================== */

	$.fn.contextmenu = function (option,e) {
		var $this = this;
		return (function () {
			var data = $this.data('context')
				, options = typeof option == 'object' && option

			if (!data) $this.data('context', (data = new ContextMenu($this, options)));
			// "show" method must also be passed the event for positioning
			if (typeof option == 'string') data[option].call(data,e);
		})();
	}

	$.fn.contextmenu.Constructor = ContextMenu;

	/* APPLY TO STANDARD CONTEXT MENU ELEMENTS
	 * =================================== */

	$(document)
		.on('contextmenu.context.data-api', '[data-toggle=context]', function(e) {
				$(this).contextmenu('show',e);
				e.preventDefault();
		});

}(window.jQuery));


text:
package com.czbix.v2ex.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.czbix.v2ex.R;
import com.czbix.v2ex.common.UserState;
import com.czbix.v2ex.common.exception.ConnectionException;
import com.czbix.v2ex.common.exception.FatalException;
import com.czbix.v2ex.common.exception.RemoteException;
import com.czbix.v2ex.common.exception.RequestException;
import com.czbix.v2ex.dao.NodeDao;
import com.czbix.v2ex.model.Node;
import com.czbix.v2ex.model.db.Draft;
import com.czbix.v2ex.model.db.TopicDraft;
import com.czbix.v2ex.network.RequestHelper;
import com.czbix.v2ex.ui.util.Html;
import com.czbix.v2ex.ui.widget.ExArrayAdapter;
import com.czbix.v2ex.ui.widget.SearchListView;
import com.czbix.v2ex.util.ExecutorUtils;
import com.czbix.v2ex.util.MiscUtils;
import com.czbix.v2ex.util.ViewUtils;
import com.google.android.material.snackbar.Snackbar;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TopicEditActivity extends AppCompatActivity {
    public static final String KEY_NODE = "node";

    private Node mNode;
    private TextView mSelectedNode;
    private EditText mTitle;
    private EditText mContent;
    private View mLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_edit);

        mLayout = findViewById(R.id.edit_layout);
        mSelectedNode = (TextView) findViewById(R.id.select_node);
        mTitle = (EditText) findViewById(R.id.title);
        mContent = (EditText) findViewById(R.id.content);

        mSelectedNode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectNodeDialog();
            }
        });

        final ActionBar actionBar = getSupportActionBar();
        Preconditions.checkNotNull(actionBar);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Nullable
    private Node getNodeFromIntent() {
        final Intent intent = getIntent();

        return intent.getParcelableExtra(KEY_NODE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_topic_edit, menu);
        final MenuItem item = menu.findItem(R.id.action_post);
        if (UserState.INSTANCE.isLoggedIn()) {
            final Drawable icon = getDrawable(R.drawable.ic_send_black_24dp);
            icon.setTint(Color.WHITE);
            item.setIcon(icon);
        } else {
            item.setVisible(false);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.action_post:
                postTopic();
                return true;
            case R.id.action_upload:
                MiscUtils.openUrl(this, "https://m.imgur.com/upload/redirect");
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void postTopic() {
        if (TextUtils.isEmpty(mTitle.getText())) {
            mTitle.setError(getString(R.string.error_field_required));
            return;
        }

        ViewUtils.hideInputMethod(mContent);

        final String title = mTitle.getText().toString();
        final String content = mContent.getText().toString();

        final ScheduledFuture<?> future = ExecutorUtils.schedule(new Runnable() {
            @Override
            public void run() {
                final int id;
                try {
                    id = RequestHelper.INSTANCE.newTopic(mNode.getName(), title, content);
                } catch (ConnectionException | RemoteException e) {
                    throw new FatalException(e);
                } catch (RequestException e) {
                    final String html = e.getErrorHtml();
                    if (Strings.isNullOrEmpty(html)) {
                        throw e;
                    }

                    showErrMsg(html);
                    return;
                }

                mLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        final Intent intent = new Intent(TopicEditActivity.this, TopicActivity.class);
                        intent.putExtra(TopicActivity.KEY_TOPIC_ID, id);
                        startActivity(intent);
                        finish();
                    }
                });
            }
        }, 3, TimeUnit.SECONDS);

        mLayout.setEnabled(false);
        Snackbar.make(mLayout, R.string.toast_sending, Snackbar.LENGTH_LONG)
                .setAction(R.string.action_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelRequest(future);
                    }
                }).show();
    }

    private void showErrMsg(final String html) {
        mLayout.post(new Runnable() {
            @Override
            public void run() {
                final View layout = getLayoutInflater().inflate(R.layout.view_alert_dialog, null);
                final TextView textView = (TextView) layout.findViewById(R.id.content);
                textView.setText(Html.fromHtml(html));

                final AlertDialog.Builder builder = new AlertDialog.Builder(TopicEditActivity.this);
                builder.setTitle(R.string.toast_post_failed).setView(layout)
                        .setCancelable(false)
                        .setPositiveButton(R.string.action_edit, null)
                        .setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();
            }
        });
    }

    private void cancelRequest(Future<?> future) {
        mLayout.setEnabled(true);
        if (future.cancel(false)) {
            return;
        }

        Snackbar.make(mLayout, R.string.toast_cancel_failed, Snackbar.LENGTH_LONG).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mNode != null) {
            return;
        }

        loadNodeFromIntent();
    }

    private void loadNodeFromIntent() {
        mNode = getNodeFromIntent();
        if (mNode == null) {
            showSelectNodeDialog();
        } else {
            updateNodeText();
        }
    }

    private void showSelectNodeDialog() {
        final SearchListView listView = new SearchListView(this);
        new AsyncTask<Void, Void, List<Node>>() {
            @Override
            protected List<Node> doInBackground(Void... params) {
                return NodeDao.getAll();
            }

            @Override
            protected void onPostExecute(List<Node> nodes) {
                listView.setAdapter(new ExArrayAdapter<>(TopicEditActivity.this,
                        android.R.layout.simple_list_item_1, nodes));
            }
        }.execute();

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.setTitle(R.string.title_select_node)
                .setView(listView)
                .setCancelable(false)
                .setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mNode == null) {
                            finish();
                        }
                        // reselect node mode
                    }
                }).create();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();

                mNode = (Node) parent.getItemAtPosition(position);
                updateNodeText();
            }
        });
        dialog.show();
    }

    private void showDraftDialog(final Draft draft) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.title_load_topic_from_draft)
                .setMessage(R.string.dest_load_topic_from_draft)
                .setCancelable(false)
                .setPositiveButton(R.string.action_load, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final TopicDraft topicDraft = TopicDraft.fromJson(draft.mContent);
                        mNode = NodeDao.get(topicDraft.mNodeName);
                        updateNodeText();

                        mTitle.setText(topicDraft.mTitle);
                        mContent.setText(topicDraft.mContent);
                    }
                })
                .setNegativeButton(R.string.action_discard, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        DraftDao.delete(draft.mId);

                        loadNodeFromIntent();
                    }
                }).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mNode == null) {
            // not inited yet
            return;
        }
        if (TextUtils.isEmpty(mTitle.getText()) && TextUtils.isEmpty(mContent.getText())) {
            return;
        }

        /*
        final String nodeName = mNode.getName();
        final String title = mTitle.getText().toString();
        final String content = mContent.getText().toString();

        final TopicDraft topicDraft = new TopicDraft(nodeName, title, content);
        DraftDao.update(DraftDao.ID_TOPIC_DRAFT, topicDraft.toJson());
        TODO
         */
        Toast.makeText(this, R.string.action_discard, Toast.LENGTH_SHORT).show();
    }

    private void updateNodeText() {
        mSelectedNode.setText(Html.fromHtml(getString(R.string.tv_selected_node, mNode.getTitle())));
    }
}


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the Fortune Cookie skill, try saying...

* *Alexa Open Fortune Cookie*

* *Alexa Ask Fortune Cookie to tell me a fortune*

* *Alexa Ask Fortune Cookie for a fortune*

Fortune will tell you a fortune without having those cookie calories.
Ask Fortune Cookie for a Fortune and listen.

***

### Skill Details

* **Invocation Name:** fortune cookie
* **Category:** null
* **ID:** amzn1.ask.skill.a4165a36-1eb6-4ff9-9574-dd91606f3569
* **ASIN:** B01N1L6BEB
* **Author:** AntlerVision
* **Release Date:** November 29, 2016 @ 04:36:08
* **In-App Purchasing:** No


text:
package com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2;

import com.netflix.spinnaker.halyard.config.model.v1.ha.ClouddriverHaService;
import com.netflix.spinnaker.halyard.config.model.v1.ha.HaServices;
import com.netflix.spinnaker.halyard.config.model.v1.node.DeploymentConfiguration;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.Profile;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.GateService;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.DistributedService.DeployPriority;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Delegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Data
@Component
@EqualsAndHashCode(callSuper = true)
public class KubernetesV2GateService extends GateService
    implements KubernetesV2Service<GateService.Gate> {
  final DeployPriority deployPriority = new DeployPriority(0);

  @Delegate @Autowired KubernetesV2ServiceDelegate serviceDelegate;

  @Override
  public ServiceSettings defaultServiceSettings(DeploymentConfiguration deploymentConfiguration) {
    return new Settings(
        deploymentConfiguration.getSecurity().getApiSecurity(),
        getActiveSpringProfiles(deploymentConfiguration));
  }

  @Override
  public Optional<String> buildAddress(String namespace) {
    return Optional.empty();
  }

  @Override
  protected boolean hasServiceOverrides(DeploymentConfiguration deployment) {
    HaServices haServices = deployment.getDeploymentEnvironment().getHaServices();
    return haServices.getClouddriver().isEnabled() || haServices.getEcho().isEnabled();
  }

  @Override
  protected List<Type> overrideServiceEndpoints() {
    return Arrays.asList(Type.CLOUDDRIVER_RO, Type.ECHO_WORKER);
  }

  @Override
  protected void appendReadonlyClouddriverForDeck(
      Profile profile,
      DeploymentConfiguration deploymentConfiguration,
      SpinnakerRuntimeSettings endpoints) {
    ClouddriverHaService clouddriverHaService =
        deploymentConfiguration.getDeploymentEnvironment().getHaServices().getClouddriver();
    if (clouddriverHaService.isEnabled() && !clouddriverHaService.isDisableClouddriverRoDeck()) {
      Map<String, Map<String, Map<String, Map<String, Map<String, String>>>>> services =
          Collections.singletonMap(
              "services",
              Collections.singletonMap(
                  "clouddriver",
                  Collections.singletonMap(
                      "config",
                      Collections.singletonMap(
                          "dynamicEndpoints",
                          Collections.singletonMap(
                              "deck",
                              endpoints
                                  .getServiceSettings(Type.CLOUDDRIVER_RO_DECK)
                                  .getBaseUrl())))));
      profile.appendContents(getYamlParser().dump(services));
    }
  }
}


text:
'user strict';

const Sequelize = require('sequelize');
const Profile = require('../models/profile');

function createProfile (req, res) {
    //instancia de nuevo usuario, asume desde modelo USER
    const profile = Profile.build({
        name: req.body.name,
        status: true
    });

    profile.save()
    .then(function(data){
        return res.status(200).send({message: 'perfil grabado correctamente'});
    })
    .catch(function(error){
        console.log(error);
        res.status(500).send({message: `error al registrar el perfil: ${error}`})
    })
}

module.exports = {
    createProfile
}