text:
class NetworksController < ApplicationController

  auto_complete_for :network, :name

  layout 'application', :except => [:get_network, :view]

  # GET /networks
  # GET /networks.xml
  def index

    @networks = Network.search(params[:network], { :order => "created_at DESC"})
    @pages = @networks.paginate :page => params[:page], :per_page => 50

    respond_to do |format|
      format.html # index.html.erb
      format.rss { render :layout => false, :collection => @networks }
      format.xml  { render :xml => @networks }
    end
  end

  # GET /networks/tag/name
  # GET /networks/tag/name.xml
  def tag
    @networks = Network.find_tagged_with(params[:name])
    @pages = @networks.paginate :page => params[:page], :order => 'name', :per_page => 5
    respond_to do |format|
      format.html { render :action => :index , :collection => @pages }
      format.rss { render :action => :index, :layout => false, :collection => @networks }
      format.xml  { render :xml => @networks }
    end
  end

  # GET /networks/1
  # GET /networks/1.xml
  def show
    @network = Network.find(params[:id])
    # TODO Ajax pagination
    @comments = @network.comments.find(:all, :order => 'created_at DESC')
    @comment_pages = @comments.paginate :page => params[:page], :per_page => 5
    @comment = @network.comments.build
    respond_to do |format|
      format.html # show.html.erb
      format.rss { render :layout => false }
      format.xml  { render :xml => @network }
    end
  end

   # GET /networks/1/view
  def view
    @network = Network.find(params[:id])
    respond_to do |format|
      format.html { render :action => :view, :layout => 'fullscreen' }
    end
  end

  # AJAX action to get a record
  def get_network
    begin
      @network = Network.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid network #{params[:id]}")
      redirect_to_index("Invalid Network ID")
    else
      render :partial => 'applet', :locals => {
        :height => 300,
        :width => 400,
        :codebase => '/applet/400x300',
        :applet_class => "appletsmall" }
    end
  end

  # GET /networks/new
  # GET /networks/new.xml
  def new
    @network = Network.new
    @service = Fileservice.new(@network)

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @network }
    end
  end

  # POST /networks
  # POST /networks.xml
  def create
    @network = Network.new(params[:network])
    @service = Fileservice.new(@network)
    @service.create_files(params)
    @edgefile = @service.edgefile
    @configfile = @service.configfile
    @annotationfile = @service.annotationfile
    respond_to do |format|
      if @service.save
        flash[:notice] = 'Network was successfully created.'
        format.html { redirect_to(@network) }
        format.xml  { render :xml => @network, :status => :created, :location => @network }
      else
        format.html { render :action => :new }
        format.xml  { render :xml => @network.errors, :status => :unprocessable_entity }
      end
    end
  end

  private
  def redirect_to_index(msg = nil)
    flash[:notice] = msg if msg
    redirect_to :action => :index
  end
end


text: func_tion foo(){ return 'fail';} foo();

redpajama_set_name: RedPajamaGithub


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.9-03/31/2009 04:14 PM(snajper)-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.05.19 at 10:15:07 AM CEST
//

package org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs21.rs;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "RequestAcceptedResponse")
public class RequestAcceptedResponse {

}


text:
$(document).ready(function(){
    main();
});

function main() {
    console.log( "ready!" );
    attach_events();
}

function attach_events() {
    $(".delete").on("click", delete_event);
}

function delete_event(e) {
    e.preventDefault();
    id = $(this).attr('id');
    node = $(e.target)[0].parentNode.parentNode;
    $.post("del_url", { "id":id }, function(data) {
        node.remove();
    });
}


text:
class CGGraphicBufferImage : public __CGImage
{
public:
    CGGraphicBufferImage(DWORD width, DWORD height, surfaceFormat fmt);
    CGGraphicBufferImage(DWORD width, DWORD height, surfaceFormat fmt, DisplayTexture *nativeTexture, DisplayTextureLocking *locking);
};

class EbrFastTexture;

class CGGraphicBufferImageBacking : public CGImageBacking
{
private:
    void *_imageData;
    cairo_surface_t *_surface;
    surfaceFormat _bitmapFmt;
    DWORD _width, _height;
    DWORD _internalWidth, _internalHeight;
    DWORD _bytesPerRow;
    DWORD _bytesPerPixel;

public:
    DisplayTexture *_nativeTexture;
    DisplayTextureLocking *_nativeTextureLocking;

    CGGraphicBufferImageBacking(DWORD width, DWORD height, surfaceFormat fmt, DisplayTexture *nativeTexture, DisplayTextureLocking *locking);
    ~CGGraphicBufferImageBacking();

    CGImageRef Copy();

    CGContextImpl *CreateDrawingContext(CGContextRef base);
    void GetPixel(int x, int y, float &r, float &g, float &b, float &a);
    int InternalWidth();
    int InternalHeight();
    int Width();
    int Height();
    int BytesPerRow();
    int BytesPerPixel();
    surfaceFormat SurfaceFormat();
    void *StaticImageData();
    void *LockImageData();
    void ReleaseImageData();
    cairo_surface_t *LockCairoSurface();
    void ReleaseCairoSurface();
    void SetFreeWhenDone(bool freeWhenDone);
    DisplayTexture *GetDisplayTexture();
};


text:
class CreateLoginTickets < ActiveRecord::Migration
  def change
    create_table :login_tickets do |t|
      t.string :name, null: false
      t.boolean :active, default: true
      t.timestamps
    end
  end
end


text:
/*
  $Id: UDF_SortXML.java,v 1.1.2.11 2003/07/25 02:04:29 seta Exp $
 */
package com.udfv.util;

import java.io.*;
import java.util.*;
import java.lang.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.*;
import org.apache.xerces.dom.*;
import org.apache.xml.serialize.*;
import com.udfv.exception.*;
import com.udfv.udf250.*;
import com.udfv.core.*;
import com.udfv.util.*;
import com.udfv.access.*;
import com.udfv.exception.*;
import com.udfv.ecma167.*;

/**

概要

XMLドキュメントをlbn またはsec 属性値でソートするためのクラス。

詳細

UDF_XMLクラスは、指定されたXMLドキュメント内のudfノード直下のノードリストを、
sec 属性値に従って昇順で配置し直す。パーティション内のデータについては
lbn 属性値が付加されているので、XML ヘッダ部のパーティション情報を元に
sec 値へと変換してソートを行う。

*/
public class UDF_XML
{
    //DTD関連
    static public final String UDF_DTD2 = "-//Heart Solutions, Inc.//DTD UDF TEST TOOL//EN";
    static public final String UDF_DTD = "http://udfv.com/udf.dtd";
    //static public final String NS_UDF = "http://udfv.com/udf/";
    //static public final String NS_ECMA119 = "http://udfv.com/ecma119/";
    static public final String NS_UDF = "file:/udfv.com/udf/";
    static public final String NS_ECMA119 = "file:/udfv.com/ecma119/";

    public static final String SYSTEM                     = "system";
    public static final String EXTENT_OF_PARTITION        = "extent-of-partitions";
    public static final String MIRROR_EXTENT_OF_PARTITION = "mirror-extent-of-partitions";
    public static final String VRS                        = "vrs";
    public static final String CD9660_VDS                 = "cd9660-vds";
    public static final String AVDP                       = "avdp";
    public static final String IS                         = "is";
    public static final String MVDS                       = "mvds";
    public static final String RVDS                       = "rvds";
    public static final String FSDS                       = "fsds";
    public static final String PARTITION                  = "partition";
    public static final String UDF_EXTENT                 = "UDF_Extent";
    //public static final String UDF_METADATA_MAIN          = "metadata-main";
    //public static final String UDF_METADATA_MIRROR        = "metadata-mirror";
    public static final String DIRECTORY                  = "UDF_Directory";
    public static final String SDIRECTORY                 = "UDF_SDirectory";

    static private class UDFElementInfo{

	Element elem;
	long    partno;
    }

    static private class UDFPartInfo{

	long  sec;
	long  length;
    }

    static private class UDFPartInfo2{

	long    sec;
	long    length;
	String  parttype;
    }

    /**
        コンストラクタ。
    */
    public UDF_XML() {}

    /**
        コンストラクタ。

        指定したXMLファイルをソートし、出力する。
        @param args 入力ファイルと出力ファイル名。
    */
    public UDF_XML(String args[]){

	try{
	    String input_xml = args[0];
	    String output_xml = args[1];
	    // インプットXMLドキュメントを取得する
	    DOMParser parser = new DOMParser();
	    parser.parse(input_xml);
	    Document inDoc = parser.getDocument();

	    // ドキュメントをソートする
	    sortDocument(inDoc, -1);

	    // ドキュメントをXMLファイルに整形する
	    OutputFormat format    = new OutputFormat(inDoc, "UTF-8", true);
	    format.setLineWidth(0);

	    StringWriter stringOut = new StringWriter();
	    XMLSerializer serial   = new XMLSerializer(stringOut, format);
	    serial.serialize(inDoc.getDocumentElement());

	    // ファイルに出力する
	    FileOutputStream fos   = new FileOutputStream(output_xml);
	    byte b[] = stringOut.toString().getBytes("UTF-8");
	    fos.write(b, 0, b.length);
	}
	catch(Exception e){

	    e.printStackTrace();
	}
    }

    /**
       ドキュメントをpos属性値でソートする。

       @param inputdoc ソート対象となるXMLドキュメント。
       @param mirrorloc  Metadata Mirror File の位置。Mirror が存在しない場合は-1 を指定する。
    */
    static public void sortDocument(Document inputdoc, int mirrorloc){
	try{
	    NodeList nlist   = inputdoc.getElementsByTagName("udf");
	    Node     udfnode = nlist.item(0);
	    NodeList childlist  = udfnode.getChildNodes();
	    TreeMap  partinfo   = getPartInfo2(inputdoc, UDF_XML.PARTITION, false);
	    TreeMap  mirrorinfo = getPartInfo2(inputdoc, UDF_XML.PARTITION, true);
	    TreeMap  extentinfo = getUDFElementInfo(udfnode, partinfo, mirrorinfo, mirrorloc);

	    // ソート順にエレメントを追加していく
	    Object[] sec = (extentinfo.keySet().toArray());

	    for(int i = 0; i < sec.length; i++){

		UDFElementInfo uei = (UDFElementInfo)(extentinfo.get((String)sec[i]));
		if(uei == null)
		    continue;

		udfnode.appendChild(uei.elem);
	    }

	}
	catch(Exception e){

	    e.printStackTrace();
	}
    }

    /**
       ドキュメントをソートする。

       各エレメントは、以下のグループ単位でソートされる。

パーティション外のデータ

各パーティションマップ内のデータ

       各グループ内のソートは、UDF_Extentの

 パーティション番号

 副番号

 secまたはlbn

       でソートされる。

       また、パーティション外のデータについては、secアトリビュート値が
       Partition 終了位置より後にある場合は最後尾に配置される。

       (ちなみに稀に Partition開始位置後に Volume情報がある場合がある
        ex: YUMERIA-VIDEO.IMG)

       (パーティションが2つある場合の処理は考慮されていない。)

       @param doc ソート対象となるXMLドキュメント。
       @param env UDF 環境。
    */
    static public void sortDocumentbyEnv(Document doc, UDF_Env env) throws UDF_XMLException{

	NodeList nlist   = doc.getElementsByTagName("udf");
	Node     udfnode = nlist.item(0);

	try{
	    // Prevailing Descriptor の1つ目を用いる。2つあった場合は考慮してない
	    UDF_ElementList desc5l = env.getPartDescList(env.VDS_AUTO);
	    com.udfv.ecma167.UDF_desc5 desc5 = (com.udfv.ecma167.UDF_desc5)desc5l.elementAt(0);
	    int partno = desc5.getPartNumber().getIntValue();

	    int partstart = env.getPartStartingLoc(partno);
	    int partend = partstart + (int)(env.getPartLen(partno) / env.LBS);
	    int partnum = env.getPartMapList().size();
	    TreeMap[] tm = null;
	    int i = 0;

	    /*
	    // 各グループのUDF_Extent情報を取得する
	    // tm[0]:パーティション外(-1)
	    // tm[1]〜tm[n-1]:各パーティションマップ(但しMirrorが無い場合は〜tm[n])
	    // tm[n]:(存在すれば)Mirror Partition
	    if(env.hasMetadataPartMap()){

		tm = new TreeMap[partnum + 1 + 1];  // -1とMirror の2つを追加
		for(i = 0; i < partnum + 1; i++)
		    tm[i] = getExtents(doc, i - 1, false);
		tm[i] = getExtents(doc, i - 2, true);
	    }
	    else{

		tm = new TreeMap[partnum + 1];  // -1を追加
		for(i = 0; i < tm.length; i++)
		    tm[i] = getExtents(doc, i - 1, false);
	    }
	    */
	    tm = new TreeMap[1];

	    tm[0] = getExtents(doc, partend/*, 0, false*/);

	    for(i = 0; i < tm.length; i++){

		Object[] sec = tm[i].keySet().toArray();
		for(int j = 0; j < sec.length; j++){

		    UDFElementInfo uei = (UDFElementInfo)(tm[i].get((String)sec[j]));
		    if(uei == null)
			continue;

		    /*
		    // Partition Lengthより後ろにあったらやらない
		    if(i == 0){

			Integer strsec = (Integer)sec[j];
			int intsec = strsec.intValue();

			if(partend <= intsec)
			    continue;
		    }
		    */
		    udfnode.appendChild(uei.elem);
		}
	    }

	    /*
	    // Partition Lengthより後ろのものを追加
	    Object[] sec = tm[0].keySet().toArray();
	    for(i = 0; i < sec.length; i++){

		UDFElementInfo uei = (UDFElementInfo)(tm[0].get((String)sec[i]));
		if(uei == null)
		    continue;

		Integer strsec = (Integer)sec[i];
		int intsec = strsec.intValue();

		if(intsec < partend)
		    continue;

		udfnode.appendChild(uei.elem);
	    }
	    */
	}
	catch(Exception e){

	    e.printStackTrace();
	}
    }

    /**
       ドキュメントからUDF_ExtentのTreeMapを取得する。

       @param doc XMLドキュメント。
       @param partstart partitionの開始位置

       TreeMapのキーは以下の文字列で構成される。

       "位置" + "." + "パーティション番号" + "." + "副番号" + "." + "LOC"

       位置はパーティションの前にあれば 0、
       位置はパーティションの中にあれば 1、
       位置はパーティションの後にあれば 2

       パーティション番号は4桁の数字。パーティション外にある場合は "----"となる

       副番号は4桁の数字。パーティション外にある場合は "0000"となる

       LBNは10桁の数字。

       以上をキーとして辞書順にソートする。
    */
    static private TreeMap getExtents(Document doc, int partstart/*, int partmapno, boolean mirror*/){

	TreeMap tm = new TreeMap();
	NodeList udflist = doc.getElementsByTagName("udf");
	NodeList nlist = udflist.item(0).getChildNodes();

	for(int i = 0; i < nlist.getLength(); i++){

	    if(nlist.item(i).getNodeType() != Node.ELEMENT_NODE)
		continue;

	    Element udfelem = (Element)nlist.item(i);
	    if(udfelem.getTagName().equals(UDF_XML.EXTENT_OF_PARTITION) ||
	       udfelem.getTagName().equals(UDF_XML.MIRROR_EXTENT_OF_PARTITION) ||
	       udfelem.getTagName().equals(UDF_XML.SYSTEM) ||
	       udfelem.getTagName().equals(UDF_XML.PARTITION) ||
	       udfelem.getTagName().equals("partition-info") ||
	       udfelem.getTagName().equals("partition-map-info"))
		continue;

	    // UDF_Extent 内にextents エレメントは1つしか存在しないので
	    // 1つ目のみのエクステントのみをソートの対象とする
	    NodeList extentlist = udfelem.getElementsByTagName(_ELEM_EXTENTS);
	    Element  firstextents = (Element)extentlist.item(0);
	    Element  extent = (Element)firstextents.getElementsByTagName(_ELEM_EXTENT).item(0);

	    if(extent == null){

		System.err.println("UDF_SortXML - Warning: This Element(" + udfelem + ") doesn't have " + _ELEM_EXTENT + " element.");
		continue;
	    }

	    String key;
	    String strsec = extent.getAttribute(_ATTR_SECTOR);
	    if(strsec.length() > 0){
		int sec_ = Integer.parseInt(strsec);
		String sec = UDF_Util.i2d10(sec_);
		if(sec_ < partstart)
		    key = "0" + "." + "----" + "." + "0000" + "." + sec;
		else
		    key = "2" + "." + "----" + "." + "0000" + "." + sec;
	    }
	    else{
		String strpartno = extent.getAttribute(_ATTR_PARTNO);
		String partno = UDF_Util.i2d4(Integer.parseInt(strpartno));

		String subno = "0000";
		if(udfelem.getAttribute(_ATTR_MIRROR).equals("yes")){
		    subno = "0001";
		}

		if(udfelem.getAttribute("subno").length() >= 1){
		    subno = UDF_Util.i2d4(Integer.parseInt(udfelem.getAttribute("subno")));
		}

		String strlbn = extent.getAttribute(_ATTR_LBN);
		String lbn = UDF_Util.i2d10(Integer.parseInt(strlbn));

		key = "1" + "." + partno + "." + subno + "." + lbn;
	    }

	    // TreeMapに追加
	    UDFElementInfo uei = new UDFElementInfo();
	    uei.elem = udfelem;
	    //uei.partno = partmapno;
	    tm.put(key, uei);
	}

	return tm;
    }

    /**
       XML の先頭で定義されているパーティション情報を取得する。
       @param doc       XML のドキュメントインスタンス。
       @param partelem  パーティション情報が格納されているエレメント名。

       @return
       正常に終了すると、パーティション番号をキーとした UDFPartInfo クラスのTreeMap を返す。
       partelem で指定されるエレメントが存在しないときは、null を返す。
    */
    static private TreeMap getPartInfo(Document doc, String partelem) throws UDF_XMLException{

	NodeList partlist = doc.getElementsByTagName(partelem);
	TreeMap  tm = new TreeMap();  // パーティション番号をキーとしたハッシュ

	if(partlist.getLength() == 0){

//	    System.err.println("UDF_SortXML - Warning: " + partelem + " element that indicates Partition infomation is not exist.");
	    return null;
	}

	// パーティションのリストを取得する
	for(int i = 0; i < partlist.getLength(); i++){

	    Element  partmaps   = (Element)partlist.item(i);
	    NodeList partitions = partmaps.getElementsByTagName(UDF_XML.PARTITION);

	    if(partitions.getLength() == 0)
		throw new UDF_XMLException(null, "Couldn't sort. This XML file doesn't have " + UDF_XML.EXTENT_OF_PARTITION + " element.");

	    // 1つのパーティションの "extents" のリストを取得する
	    for(int j = 0; j < partitions.getLength(); j++){

		Element  partition   = (Element)partitions.item(j);
		NodeList extentslist = partition.getElementsByTagName(_ELEM_EXTENTS);
		Element  extents    = (Element)extentslist.item(0);
		NodeList extentlist = partition.getElementsByTagName(_ELEM_EXTENT);
		Vector   extentinfo = new Vector();
		Integer  partno     = Integer.decode(partition.getAttribute(_ATTR_PARTNO));

		// 1つのパーティションのエクステントのデータを取得する
		for(int k = 0; k < extentlist.getLength(); k++){

		    Element elem_ext = (Element)extentlist.item(k);
		    long  sec = Long.parseLong(elem_ext.getAttribute(_ATTR_SECTOR));
		    long  len = Long.parseLong(elem_ext.getAttribute(_ATTR_LEN));
		    UDFPartInfo ei = new UDFPartInfo();

		    ei.sec    = sec;
		    ei.length = len;
		    extentinfo.add(ei);
		}

		tm.put(partno, extentinfo);
	    }
	}

	return tm;
    }
    /**
       XML の先頭で定義されているパーティション情報を取得する。
       @param doc       XML のドキュメントインスタンス。
       @param partelem  パーティション情報が格納されているエレメント名。

       @return
       正常に終了すると、パーティション番号をキーとした UDFPartInfo クラスのTreeMap を返す。
       partelem で指定されるエレメントが存在しないときは、null を返す。
    */
    static private TreeMap getPartInfo2(Document doc, String partelem, boolean mirror) throws UDF_XMLException{

	NodeList partlist = doc.getElementsByTagName(partelem);
	TreeMap  tm = new TreeMap();  // パーティション番号をキーとしたハッシュ

	if(partlist.getLength() == 0){

	    System.err.println("UDF_SortXML - Warning: " + partelem + " element that indicates Partition infomation is not exist.");
	    return null;
	}

	for(int i = 0; i < partlist.getLength(); i++){  // パーティションのリスト(<partition>)

	    if(partlist.item(i).getNodeType() != Node.ELEMENT_NODE)
		continue;

	    Element  partition = (Element)partlist.item(i);
	    NodeList partmaplist = partition.getElementsByTagName(_ELEM_PARTMAP);

	    for(int j = 0; j < partmaplist.getLength(); j++){  // パーティションマップのリスト(<partmap>)

		if(partmaplist.item(j).getNodeType() != Node.ELEMENT_NODE)
		    continue;

		Element  elem = (Element)(partmaplist.item(j));
		Integer  partno = Integer.decode(elem.getAttribute(_ATTR_PARTNO));

		getPartMapInfo(tm, elem, partno, mirror, "");
	    }
	}

	return tm;
    }

    /**
       XML の先頭で定義されているパーティションマップ情報を取得する。

       @param tm      UDFPartInfo クラスを格納するためのTreeMap。
       @param partmap パーティションマップを表すエレメント(<partmap>)。
       @param partno  パーティションマップ番号。
    */
    static private void getPartMapInfo(TreeMap tm, Element partmap, Integer partno, boolean mirror, String type){

	NodeList pmchild = partmap.getChildNodes();
	int partmaptype = -1;

	for(int i = 0; i < pmchild.getLength(); i++){

	    if(pmchild.item(i).getNodeType() != Node.ELEMENT_NODE)
		continue;

	    Element elem = (Element)(pmchild.item(i));
	    String nodename = elem.getNodeName();

	    if(nodename.equals("UDF_Extent") && !mirror){

		NodeList extentslist = elem.getChildNodes();
		Element  extents = (Element)extentslist.item(0);
		NodeList extentlist = extents.getChildNodes();
		Vector   extentinfo  = new Vector();

		// 既に追加されていればそれは最新のVAT なので、上書きしない
		if(type.equals("vat") && tm.containsKey(partno))
		    return;

		for(int j = 0; j < extentlist.getLength(); j++){

		    Element elem_ext = (Element)extentlist.item(j);
		    long  sec = Long.parseLong(elem_ext.getAttribute(_ATTR_SECTOR));
		    long  len = Long.parseLong(elem_ext.getAttribute(_ATTR_LEN));
		    UDFPartInfo2 ei = new UDFPartInfo2();

		    ei.sec      = sec;
		    ei.length   = len;
		    ei.parttype = type;
		    extentinfo.add(ei);
		}

		tm.put(partno, extentinfo);
	    }
	    else if(nodename.equals("vat")){

		getPartMapInfo(tm, elem, partno, mirror, "vat");
	    }
	    else if(nodename.equals("metadata")){

		// MetadataMain のみ
		if(!elem.getAttribute(_ATTR_MIRROR).equals("yes"))
		    getPartMapInfo(tm, elem, partno, mirror, "meta");
		else if(mirror)
		    getPartMapInfo(tm, elem, partno, false, "meta");
	    }
	}
    }

    /**
       各UDF Element の所属するパーティション番号と、開始セクタを取得する。
       extents Element 内に複数のextent Element が存在していた場合、先頭のextent Element のみを取得する。
       もしudfnode 内に同じ位置(sec)を指すUDF Element が複数あった場合は、そのUDF Element を削除する。
       また、partinfo またはmirrorinfo がnull の場合で、且つUDF Element がそれらの情報を必要とした場合
       (UDF Element がpartno XML Attribute を持っている場合)、単にsec/lbn XML Attribute の値でソートする。

       @param udfnode    <udf> Element を示すインスタンス。
       @param partinfo   パーティション情報が格納されたTreeMap インスタンス。この情報はgetPartInfo2() で取得できる。
       @param mirrorinfo ミラーパーティション情報が格納されたTreeMap インスタンス。この情報はgetPartInfo() で取得できる。
       @param mirrorloc  Metadata Mirror File の位置。Mirror が存在しない場合は-1 を指定する。
       @return 正常に終了すると、セクタをキーとしたUDFElementInfo クラスのTreeMap を返す。
    */
    static private TreeMap getUDFElementInfo(Node udfnode, TreeMap partinfo, TreeMap mirrorinfo, int mirrorloc)
	throws UDF_XMLException{

	TreeMap  tm = new TreeMap();  // sec 値をキーとしたハッシュ
	NodeList nl = udfnode.getChildNodes();

	for(int i = 0; i < nl.getLength(); i++){

	    if(nl.item(i).getNodeType() != Node.ELEMENT_NODE)
		continue;

	    Element  udfelem = (Element)nl.item(i);

	    if(udfelem.getTagName().equals(UDF_XML.EXTENT_OF_PARTITION) ||
	       udfelem.getTagName().equals(UDF_XML.MIRROR_EXTENT_OF_PARTITION) ||
	       udfelem.getTagName().equals(UDF_XML.SYSTEM) ||
	       udfelem.getTagName().equals(UDF_XML.PARTITION))
		continue;

	    // UDF_Extent 内にextents エレメントは1つしか存在しないので
	    // 1つ目のみのエクステントのみをソートの対象とする
	    NodeList extentlist   = udfelem.getElementsByTagName(_ELEM_EXTENTS);

	    if(extentlist == null){

		System.err.println("UDF_SortXML - Warning: This Element(" + udfelem + ") doesn't have " + _ELEM_EXTENTS + " element.");
		continue;
	    }

	    Element  firstextents = (Element)extentlist.item(0);
	    Element  extent = (Element)firstextents.getElementsByTagName(_ELEM_EXTENT).item(0);

	    if(extent == null){

		System.err.println("UDF_SortXML - Warning: This Element(" + udfelem + ") doesn't have " + _ELEM_EXTENT + " element.");
		continue;
	    }

	    String   strsec = extent.getAttribute(_ATTR_SECTOR);
	    Integer  partno = new Integer(-1);
	    Long     sec    = null;
	    String   keystr = new String();

	    if(strsec.equals("")){  // sec アトリビュートが存在しない

		// かわりにlbn アトリビュートを探す
		strsec = extent.getAttribute(_ATTR_LBN);
		if(strsec.equals("")){

		    System.err.println("elem = " + udfelem.getTagName());
		    throw new UDF_XMLException(null,
			 "Couldn't sort. This element of udf has neither " + _ATTR_SECTOR + " nor " + _ATTR_LBN + " attribute.");
		}

		// lbn のときは、partno アトリビュートも必須
		String strpartno = extent.getAttribute(_ATTR_PARTNO);
		partno = Integer.decode(strpartno);

		if(strpartno.equals(""))
		    throw new UDF_XMLException(null,
			"Couldn't sort. This element of udf has " + _ATTR_LBN + " attribute, but doesn't have " + _ATTR_PARTNO + " attribute.");

		boolean ismirror = extent.getAttribute(_ATTR_MIRROR).equals("yes");

		if(partinfo == null || (ismirror && mirrorinfo == null)){

		    sec = Long.decode(strsec);  // ソート効果はほとんどない
		}
		else{
		    // パーティションの情報をモトに、lbn をsec 値へと変換する
		    Vector partextents = (Vector)(ismirror ? mirrorinfo.get(partno) : partinfo.get(partno));

		    if(partextents == null){

			throw new UDF_XMLException(null,
			    "ismirror = " + ismirror + " Couldn't sort. Partition Number " + partno + " is not defined in "
			     + (ismirror ? UDF_XML.MIRROR_EXTENT_OF_PARTITION : UDF_XML.EXTENT_OF_PARTITION) + ".");
		    }

		    UDFPartInfo2 firstinfo  = (UDFPartInfo2)partextents.elementAt(0);
		    long  firstsec = firstinfo.sec;
		    long  lbn = (Long.parseLong(strsec));
		    long  offset = 0;

		    for(int k = 0; k < partextents.size(); k++){

			UDFPartInfo2 upi = (UDFPartInfo2)partextents.elementAt(k);

			if(upi.sec - firstsec < lbn && k != (partextents.size() - 1)){

			    offset += upi.length / 2048;
			    continue;
			}

			sec = new Long((lbn - offset) + upi.sec);

			if(udfelem.getAttribute(_ATTR_MIRROR).equals("yes"))
			    sec = new Long((lbn - offset) + upi.sec + mirrorloc);

			String tmpstr = new String();
			for(int l = String.valueOf(sec).length(); l < 25; l++)
			    tmpstr += '0';

			keystr += ("sec=" + tmpstr + sec + ":partno=" + partno);

			break;
		    }
		}
	    }
	    else{

		sec = Long.decode(strsec);  // ナマのセクタ値

		if(udfelem.getAttribute(_ATTR_MIRROR).equals("yes")){

		    long tmp = sec.longValue();
		    sec = new Long(tmp + mirrorloc);
		}

		String tmpstr = new String();
		for(int l = String.valueOf(sec).length(); l < 25; l++)
		    tmpstr += '0';
		keystr += ("sec=" + tmpstr + sec + ":partno=" + partno);
	    }

//	    System.err.println(keystr + " elem = " + udfelem);

	    // マップに追加する
	    UDFElementInfo uei = new UDFElementInfo();
	    uei.elem   = udfelem;
	    uei.partno = partno.intValue();

	}

	return tm;
    }

    public static void main(String args[]){

	if(args.length < 2){

	    System.err.println("Usage: java UDF_SortXML <Input_XML> <Output_XML>");
	    return;
	}

	new UDF_XML(args);
    }

    private int mirrorloc_;

    private static final String _ELEM_EXTENTS     = "extents";
    private static final String _ELEM_EXTENT      = "extent";
    private static final String _ELEM_PARTITION   = "partition";
    private static final String _ELEM_PMTYPE      = "pm-type";
    private static final String _ELEM_PARTMAP     = "partmap";
    private static final String _ELEM_VAT         = "vat";
    private static final String _ELEM_METADATA    = "metadata";

    private static final String _ATTR_PARTNO      = "partno";
    private static final String _ATTR_SECTOR      = "sec";
    private static final String _ATTR_LEN         = "len";
    private static final String _ATTR_LBN         = "lbn";
    private static final String _ATTR_MIRROR      = "mirror";

}


text:
package org.slc.sli.validation.schema;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import org.slc.sli.common.domain.ContainerDocumentHolder;
import org.slc.sli.common.domain.NaturalKeyDescriptor;
import org.slc.sli.common.util.tenantdb.TenantContext;
import org.slc.sli.domain.CalculatedData;
import org.slc.sli.domain.Entity;
import org.slc.sli.validation.NaturalKeyValidationException;
import org.slc.sli.validation.NoNaturalKeysDefinedException;
import org.slc.sli.validation.SchemaRepository;
import org.slc.sli.validation.schema.Annotation.AnnotationType;

/**
 *
 * TODO: add class javadoc
 *
 */
public class NaturalKeyExtractorTest {

    private static final String COLLECTION_TYPE = "StampCollection";

    @InjectMocks
    NaturalKeyExtractor naturalKeyExtractor = new NaturalKeyExtractor();

    @Mock
    SchemaRepository entitySchemaRegistry;

    @Mock
    private ContainerDocumentHolder mockHolder;

    NeutralSchema mockSchema;

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGetNaturalKeyFields() throws NoNaturalKeysDefinedException {

        Entity e = setup();

        Map<String, Boolean> naturalKeyFields = naturalKeyExtractor.getNaturalKeyFields(e);

        Assert.assertEquals(1, naturalKeyFields.size());
        Assert.assertEquals("someField", naturalKeyFields.entrySet().iterator().next().getKey());
        Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString());
    }

    @Test
    public void testGetNaturalKeyDescriptor() throws NoNaturalKeysDefinedException {

        Entity e = setup();

        TenantContext.setTenantId("someTenant");
        NaturalKeyDescriptor desc = naturalKeyExtractor.getNaturalKeyDescriptor(e);
        Map<String, String> naturalKeys = desc.getNaturalKeys();

        Assert.assertEquals(COLLECTION_TYPE, desc.getEntityType());
        Assert.assertEquals("someTenant", desc.getTenantId());
        Assert.assertEquals(1, naturalKeys.size());
        Assert.assertEquals("someValue", naturalKeys.get("someField"));
        Mockito.verify(entitySchemaRegistry, Mockito.times(2)).getSchema(Mockito.anyString());
    }

    @Test
    public void testGetNaturalKeys() throws NoNaturalKeysDefinedException {

        Entity e = setup();

        Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e);

        Assert.assertEquals(1, naturalKeys.size());
        Assert.assertEquals("someValue", naturalKeys.get("someField"));
        Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString());
    }

    @Test(expected = NaturalKeyValidationException.class)
    public void shouldThrowExceptionWhenMissingRequiredKeyField() throws NoNaturalKeysDefinedException {

        Entity e = setup();
        // remove field so that exception is thrown
        e.getBody().remove("someField");

        @SuppressWarnings("unused")
        Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e);
    }

    @Test
    public void shouldNotThrowExceptionWhenMissingOptionalKeyField() throws NoNaturalKeysDefinedException {

        Entity e = setup();

        // add another optional schema field that is not present
        AppInfo mockAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true);
        Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO);
        mockSchema.addAnnotation(mockAppInfo);

        NeutralSchema mockFieldSchema = Mockito.mock(NeutralSchema.class);
        mockSchema.addField("optionalField", mockFieldSchema);

        AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo);
        Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true);
        Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(false);

        Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e);

        Assert.assertEquals(2, naturalKeys.size());
        Assert.assertEquals("someValue", naturalKeys.get("someField"));
        Assert.assertEquals("", naturalKeys.get("optionalField"));
        Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString());
    }

    @Test
    public void shouldExtractNestedKeyField() throws NoNaturalKeysDefinedException {

        Entity e = setup();
        Map<String, String> parentValue = new HashMap<String, String>();
        parentValue.put("childField", "someNestedValue");
        e.getBody().put("parentField", parentValue);

        // add another optional schema field that is not present
        AppInfo mockAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true);
        Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO);
        mockSchema.addAnnotation(mockAppInfo);

        // create the parent field schema
        ComplexSchema parentFieldSchema = new ComplexSchema();
        mockSchema.addField("parentField", parentFieldSchema);
        AppInfo mockAppInfoForParent = Mockito.mock(AppInfo.class);
        Mockito.when(mockAppInfoForParent.isNaturalKey()).thenReturn(true);
        Mockito.when(mockAppInfoForParent.getType()).thenReturn(AnnotationType.APPINFO);
        parentFieldSchema.addAnnotation(mockAppInfoForParent);

        // create the child field schema
        NeutralSchema mockChildFieldSchema = Mockito.mock(NeutralSchema.class);
        AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockChildFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo);
        Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true);
        Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(false);

        // add the child schema to the parent
        parentFieldSchema.addField("childField", mockChildFieldSchema);

        Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e);

        Assert.assertEquals(2, naturalKeys.size());
        Assert.assertEquals("someValue", naturalKeys.get("someField"));
        Assert.assertEquals("someNestedValue", naturalKeys.get("parentField.childField"));
        Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString());
    }

    @Test
    public void shouldNotExtractNestedKeyFieldWhenParentFieldIsNotANaturalKey() throws NoNaturalKeysDefinedException {

        Entity e = setup();
        Map<String, String> parentValue = new HashMap<String, String>();
        parentValue.put("childField", "someNestedValue");
        e.getBody().put("parentField", parentValue);

        // add another optional schema field that is not present
        AppInfo mockAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true);
        Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO);
        mockSchema.addAnnotation(mockAppInfo);

        // create the parent field schema
        ComplexSchema parentFieldSchema = new ComplexSchema();
        mockSchema.addField("parentField", parentFieldSchema);
        AppInfo mockAppInfoForParent = Mockito.mock(AppInfo.class);
        Mockito.when(mockAppInfoForParent.isNaturalKey()).thenReturn(false);
        Mockito.when(mockAppInfoForParent.getType()).thenReturn(AnnotationType.APPINFO);
        parentFieldSchema.addAnnotation(mockAppInfoForParent);

        // create the child field schema
        NeutralSchema mockChildFieldSchema = Mockito.mock(NeutralSchema.class);
        AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockChildFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo);
        Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true);
        Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(false);

        // add the child schema to the parent
        parentFieldSchema.addField("childField", mockChildFieldSchema);

        Map<String, String> naturalKeys = naturalKeyExtractor.getNaturalKeys(e);

        Assert.assertEquals(1, naturalKeys.size());
        Assert.assertEquals("someValue", naturalKeys.get("someField"));
        Assert.assertNull("The nested field should not be extracted", naturalKeys.get("parentField.childField"));
        Mockito.verify(entitySchemaRegistry, Mockito.times(1)).getSchema(Mockito.anyString());
    }

    @Test
    public void shouldLookupEntityCollection() {

        Entity e = setup();

        // add another optional schema field that is not present
        AppInfo mockAppInfo = Mockito.mock(AppInfo.class);
        mockSchema.addAnnotation(mockAppInfo);

        String collectionName = naturalKeyExtractor.getCollectionName(e);

        Assert.assertEquals(COLLECTION_TYPE, collectionName);
    }

    private Entity setup() {
        String entityType = "entityType";
        Entity e = createEntity(entityType);
        e.getBody().put("someField", "someValue");

        mockSchema = new StringSchema(entityType);
        Mockito.when(entitySchemaRegistry.getSchema(entityType)).thenReturn(mockSchema);

        AppInfo mockAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockAppInfo.applyNaturalKeys()).thenReturn(true);
        Mockito.when(mockAppInfo.getType()).thenReturn(AnnotationType.APPINFO);
        Mockito.when(mockAppInfo.getCollectionType()).thenReturn(COLLECTION_TYPE);
        mockSchema.addAnnotation(mockAppInfo);

        NeutralSchema mockFieldSchema = Mockito.mock(NeutralSchema.class);
        mockSchema.addField("someField", mockFieldSchema);

        AppInfo mockFieldAppInfo = Mockito.mock(AppInfo.class);
        Mockito.when(mockFieldSchema.getAppInfo()).thenReturn(mockFieldAppInfo);
        Mockito.when(mockFieldAppInfo.isNaturalKey()).thenReturn(true);
        Mockito.when(mockFieldAppInfo.isRequired()).thenReturn(true);

        return e;

    }

    private Entity createEntity(final String type) {
        return new Entity() {
            private Map<String, Object> body = new HashMap<String, Object>();
            private Map<String, Object> metadata = new HashMap<String, Object>();

            @Override
            public String getType() {
                return type;
            }

            @Override
            public String getEntityId() {
                return null;
            }

            @Override
            public Map<String, Object> getBody() {
                return body;
            }

            @Override
            public Map<String, Object> getMetaData() {
                return metadata;
            }

            @Override
            public CalculatedData<String> getCalculatedValues() {
                return null;
            }

            @Override
            public CalculatedData<Map<String, Integer>> getAggregates() {
                return null;
            }

            @Override
            public Map<String, List<Entity>> getEmbeddedData() {
                return null;
            }

            @Override
            public Map<String, List<Map<String, Object>>> getDenormalizedData() {
                return null;
            }

            @Override
            public String getStagedEntityId() {
                return null;
            }

            @Override
            public Map<String, List<Entity>> getContainerData() {
                return null;
            }

            @Override
            public void hollowOut() {
                // override super implementation with empty implementation
            }
        };
    }
}


text:
layout: post
title: "the beginnings of going tech free"
description: "a more tech free lifestyle"
category: articles
tags: [amish, tech, addiction, habits, social, lifestyle, study, meditation]
comments: false
---

I am an avid tech user. I own several laptops, each installed with Gnu+Linux,
and quite often I'm tinkering away inside of my text editors, notetaking apps,
or other tools. I'm often searching through online articles, news stories, and
ebooks with the percieved purpose of feeding my desire to gain the hottest new
headlines and geeky must-know knowledge.  I'm also using social media quite
often, including Freenode irc, [Mastodon.social](https://mastodon.social), and
FaceBook.  This has definitely allowed me to keep up-to-date with the latest
happenings of my friends and distant aquaintances, and it has helped me to
learn of new academic resources, online libraries, and toves of information
venues that I wouldn't have otherwise found, but I have discovered a major
issue with all of this.

Overall, I am wasting my time.

The time that I'm spending on tech and social media is time that could be be
spent doing other more fulfilling activities, such as deep reading. Now, I am
far from the only person with this issue of wasting far too much time chatting
away on social media or tinkering with the latest trendy apps and gadgets.  We
all seem to do this. Take any given day, at any given public venue, and I find
most people zapped into the mesmerizing lure of their laptops and cell phones,
typing away the latest gossip to all of their friends or hypnotized into their
favorite apps and games.  We as a society and culture are sucked into this lure
of tech and social media, and it is totally wasting our time and distracting us
from deep reading and thinking.

That being said, I have made the decision to attempt to effectively eliminate
all of my social media and other distractions. I am beginning this process by
leaving my laptop at home and turning off my phone when I am out and about,
especially when I go to my college or university. I will be taking the bus
quite often, and being that it is a long commute to get to places, I won't be
able to easily go back for my gadgets. When I do need to use a computer during
the day I will utilize a time limited college or library computer lab.  I will
still be blogging and using email, but my idea with this is that by doing this
it will free up much of my time for my primary goal of deep reading. We will
see how this goes, and I will update this post as I make progress.

Now, to give proper credit where credit is due, my initial idea for going
tech-free is via a meetup friend who has actually done this. He has closed all
of his social media accounts, and all of that. He has been able to read three
to four full quality books per week, quality books being classical and deep
academic literature. His time was freed up considerably, and his secret was to
eliminate all of the social media distractions.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 16(no. 78): 54 (1887)

#### Original name
Teichospora pezizoides Sacc. & Speg.

### Remarks
null


text:
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PersistenciaDatos
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class BDlogisticaEntities : DbContext
    {
        public BDlogisticaEntities()
            : base("name=BDlogisticaEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<almacen> almacen { get; set; }
        public DbSet<catalogo> catalogo { get; set; }
        public DbSet<departamento> departamento { get; set; }
        public DbSet<entidad> entidad { get; set; }
        public DbSet<proyecto> proyecto { get; set; }
        public DbSet<requerimiento> requerimiento { get; set; }
        public DbSet<requerimiento_detalle> requerimiento_detalle { get; set; }
        public DbSet<unidad_medida> unidad_medida { get; set; }
        public DbSet<usuario> usuario { get; set; }
    }
}


text:
package com.sun.crypto.provider;

import java.security.InvalidKeyException;

/**
 * This class represents ciphers in Plaintext Cipher Block Chaining (PCBC)
 * mode.
 *
 *
This mode is implemented independently of a particular cipher.
 * Ciphers to which this mode should apply (e.g., DES) must be
 * plugged-in using the constructor.
 *
 *
NOTE: This class does not deal with buffering or padding.
 *
 * @author Gigi Ankeny
 */

final class PCBC extends FeedbackCipher {

    /*
     * output buffer
     */
    private final byte[] k;

    // variables for save/restore calls
    private byte[] kSave = null;

    PCBC(SymmetricCipher embeddedCipher) {
        super(embeddedCipher);
        k = new byte[blockSize];
    }

    /**
     * Gets the name of this feedback mode.
     *
     * @return the string PCBC
     */
    String getFeedback() {
        return "PCBC";
    }

    /**
     * Initializes the cipher in the specified mode with the given key
     * and iv.
     *
     * @param decrypting flag indicating encryption or decryption
     * @param algorithm the algorithm name
     * @param key the key
     * @param iv the iv
     *
     * @exception InvalidKeyException if the given key is inappropriate for
     * initializing this cipher
     */
    void init(boolean decrypting, String algorithm, byte[] key, byte[] iv)
            throws InvalidKeyException {
        if ((key == null) || (iv == null) || (iv.length != blockSize)) {
            throw new InvalidKeyException("Internal error");
        }
        this.iv = iv;
        reset();
        embeddedCipher.init(decrypting, algorithm, key);
    }

    /**
     * Resets the iv to its original value.
     * This is used when doFinal is called in the Cipher class, so that the
     * cipher can be reused (with its original iv).
     */
    void reset() {
        System.arraycopy(iv, 0, k, 0, blockSize);
    }

    /**
     * Save the current content of this cipher.
     */
    void save() {
        if (kSave == null) {
            kSave = new byte[blockSize];
        }
        System.arraycopy(k, 0, kSave, 0, blockSize);

    }

    /**
     * Restores the content of this cipher to the previous saved one.
     */
    void restore() {
        System.arraycopy(kSave, 0, k, 0, blockSize);
    }

    /**
     * Performs encryption operation.
     *
     *
The input plain text plain, starting at
     * plainOffset and ending at
     * (plainOffset + len - 1), is encrypted.
     * The result is stored in cipher, starting at
     * cipherOffset.
     *
     *
It is the application's responsibility to make sure that
     * plainLen is a multiple of the embedded cipher's block size,
     * as any excess bytes are ignored.
     *
     *
It is also the application's responsibility to make sure that
     * init has been called before this method is called.
     * (This check is omitted here, to avoid double checking.)
     *
     * @param plain the buffer with the input data to be encrypted
     * @param plainOffset the offset in plain
     * @param plainLen the length of the input data
     * @param cipher the buffer for the result
     * @param cipherOffset the offset in cipher
     */
    void encrypt(byte[] plain, int plainOffset, int plainLen,
                        byte[] cipher, int cipherOffset)
    {
        int i;
        int endIndex = plainOffset + plainLen;

        for (; plainOffset < endIndex;
             plainOffset += blockSize, cipherOffset += blockSize) {
            for (i=0; i<blockSize; i++) {
                k[i] ^= (byte)(plain[i+plainOffset]);
            }
            embeddedCipher.encryptBlock(k, 0, cipher, cipherOffset);
            for (i = 0; i < blockSize; i++) {
                k[i] = (byte)(plain[i+plainOffset] ^ cipher[i+cipherOffset]);
            }
        }
    }

    /**
     * Performs decryption operation.
     *
     *
The input cipher text cipher, starting at
     * cipherOffset and ending at
     * (cipherOffset + len - 1), is decrypted.
     * The result is stored in plain, starting at
     * plainOffset.
     *
     *
It is the application's responsibility to make sure that
     * cipherLen is a multiple of the embedded cipher's block
     * size, as any excess bytes are ignored.
     *
     *
It is also the application's responsibility to make sure that
     * init has been called before this method is called.
     * (This check is omitted here, to avoid double checking.)
     *
     * @param cipher the buffer with the input data to be decrypted
     * @param cipherOffset the offset in cipherOffset
     * @param cipherLen the length of the input data
     * @param plain the buffer for the result
     * @param plainOffset the offset in plain
     */
    void decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                        byte[] plain, int plainOffset)
    {
        int i;
        int endIndex = cipherOffset + cipherLen;

        for (; cipherOffset < endIndex;
             plainOffset += blockSize, cipherOffset += blockSize) {
            embeddedCipher.decryptBlock(cipher, cipherOffset,
                                   plain, plainOffset);
            for (i = 0; i < blockSize; i++) {
                plain[i+plainOffset] ^= k[i];
            }
            for (i = 0; i < blockSize; i++) {
                k[i] = (byte)(plain[i+plainOffset] ^ cipher[i+cipherOffset]);
            }
        }
    }
}


text:
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors.  All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package proto

/*
 * Routines for encoding data into the wire format for protocol buffers.
 */

import (
	"fmt"
	"log"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"sync"
)

const debug bool = false

// Constants that identify the encoding of a value on the wire.
const (
	WireVarint     = 0
	WireFixed64    = 1
	WireBytes      = 2
	WireStartGroup = 3
	WireEndGroup   = 4
	WireFixed32    = 5
)

// tagMap is an optimization over map[int]int for typical protocol buffer
// use-cases. Encoded protocol buffers are often in tag order with small tag
// numbers.
type tagMap struct {
	fastTags []int
	slowTags map[int]int
}

// tagMapFastLimit is the upper bound on the tag number that will be stored in
// the tagMap slice rather than its map.
const tagMapFastLimit = 1024

func (p *tagMap) get(t int) (int, bool) {
	if t > 0 && t < tagMapFastLimit {
		if t >= len(p.fastTags) {
			return 0, false
		}
		fi := p.fastTags[t]
		return fi, fi >= 0
	}
	fi, ok := p.slowTags[t]
	return fi, ok
}

func (p *tagMap) put(t int, fi int) {
	if t > 0 && t < tagMapFastLimit {
		for len(p.fastTags) < t+1 {
			p.fastTags = append(p.fastTags, -1)
		}
		p.fastTags[t] = fi
		return
	}
	if p.slowTags == nil {
		p.slowTags = make(map[int]int)
	}
	p.slowTags[t] = fi
}

// StructProperties represents properties for all the fields of a struct.
// decoderTags and decoderOrigNames should only be used by the decoder.
type StructProperties struct {
	Prop             []*Properties  // properties for each field
	reqCount         int            // required count
	decoderTags      tagMap         // map from proto tag to struct field number
	decoderOrigNames map[string]int // map from original name to struct field number
	order            []int          // list of struct field numbers in tag order

	// OneofTypes contains information about the oneof fields in this message.
	// It is keyed by the original name of a field.
	OneofTypes map[string]*OneofProperties
}

// OneofProperties represents information about a specific field in a oneof.
type OneofProperties struct {
	Type  reflect.Type // pointer to generated struct type for this oneof field
	Field int          // struct field number of the containing oneof in the message
	Prop  *Properties
}

// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
// See encode.go, (*Buffer).enc_struct.

func (sp *StructProperties) Len() int { return len(sp.order) }
func (sp *StructProperties) Less(i, j int) bool {
	return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
}
func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }

// Properties represents the protocol-specific behavior of a single struct field.
type Properties struct {
	Name     string // name of the field, for error messages
	OrigName string // original name before protocol compiler (always set)
	JSONName string // name to use for JSON; determined by protoc
	Wire     string
	WireType int
	Tag      int
	Required bool
	Optional bool
	Repeated bool
	Packed   bool   // relevant for repeated primitives only
	Enum     string // set for enum types only
	proto3   bool   // whether this is known to be a proto3 field
	oneof    bool   // whether this is a oneof field

	Default     string // default value
	HasDefault  bool   // whether an explicit default was provided
	CustomType  string
	CastType    string
	StdTime     bool
	StdDuration bool
	WktPointer  bool

	stype reflect.Type      // set for struct types only
	ctype reflect.Type      // set for custom types only
	sprop *StructProperties // set for struct types only

	mtype      reflect.Type // set for map types only
	MapKeyProp *Properties  // set for map types only
	MapValProp *Properties  // set for map types only
}

// String formats the properties in the protobuf struct field tag style.
func (p *Properties) String() string {
	s := p.Wire
	s += ","
	s += strconv.Itoa(p.Tag)
	if p.Required {
		s += ",req"
	}
	if p.Optional {
		s += ",opt"
	}
	if p.Repeated {
		s += ",rep"
	}
	if p.Packed {
		s += ",packed"
	}
	s += ",name=" + p.OrigName
	if p.JSONName != p.OrigName {
		s += ",json=" + p.JSONName
	}
	if p.proto3 {
		s += ",proto3"
	}
	if p.oneof {
		s += ",oneof"
	}
	if len(p.Enum) > 0 {
		s += ",enum=" + p.Enum
	}
	if p.HasDefault {
		s += ",def=" + p.Default
	}
	return s
}

// Parse populates p by parsing a string in the protobuf struct field tag style.
func (p *Properties) Parse(s string) {
	// "bytes,49,opt,name=foo,def=hello!"
	fields := strings.Split(s, ",") // breaks def=, but handled below.
	if len(fields) < 2 {
		log.Printf("proto: tag has too few fields: %q", s)
		return
	}

	p.Wire = fields[0]
	switch p.Wire {
	case "varint":
		p.WireType = WireVarint
	case "fixed32":
		p.WireType = WireFixed32
	case "fixed64":
		p.WireType = WireFixed64
	case "zigzag32":
		p.WireType = WireVarint
	case "zigzag64":
		p.WireType = WireVarint
	case "bytes", "group":
		p.WireType = WireBytes
		// no numeric converter for non-numeric types
	default:
		log.Printf("proto: tag has unknown wire type: %q", s)
		return
	}

	var err error
	p.Tag, err = strconv.Atoi(fields[1])
	if err != nil {
		return
	}

outer:
	for i := 2; i < len(fields); i++ {
		f := fields[i]
		switch {
		case f == "req":
			p.Required = true
		case f == "opt":
			p.Optional = true
		case f == "rep":
			p.Repeated = true
		case f == "packed":
			p.Packed = true
		case strings.HasPrefix(f, "name="):
			p.OrigName = f[5:]
		case strings.HasPrefix(f, "json="):
			p.JSONName = f[5:]
		case strings.HasPrefix(f, "enum="):
			p.Enum = f[5:]
		case f == "proto3":
			p.proto3 = true
		case f == "oneof":
			p.oneof = true
		case strings.HasPrefix(f, "def="):
			p.HasDefault = true
			p.Default = f[4:] // rest of string
			if i+1 < len(fields) {
				// Commas aren't escaped, and def is always last.
				p.Default += "," + strings.Join(fields[i+1:], ",")
				break outer
			}
		case strings.HasPrefix(f, "embedded="):
			p.OrigName = strings.Split(f, "=")[1]
		case strings.HasPrefix(f, "customtype="):
			p.CustomType = strings.Split(f, "=")[1]
		case strings.HasPrefix(f, "casttype="):
			p.CastType = strings.Split(f, "=")[1]
		case f == "stdtime":
			p.StdTime = true
		case f == "stdduration":
			p.StdDuration = true
		case f == "wktptr":
			p.WktPointer = true
		}
	}
}

var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()

// setFieldProps initializes the field properties for submessages and maps.
func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
	isMap := typ.Kind() == reflect.Map
	if len(p.CustomType) > 0 && !isMap {
		p.ctype = typ
		p.setTag(lockGetProp)
		return
	}
	if p.StdTime && !isMap {
		p.setTag(lockGetProp)
		return
	}
	if p.StdDuration && !isMap {
		p.setTag(lockGetProp)
		return
	}
	if p.WktPointer && !isMap {
		p.setTag(lockGetProp)
		return
	}
	switch t1 := typ; t1.Kind() {
	case reflect.Struct:
		p.stype = typ
	case reflect.Ptr:
		if t1.Elem().Kind() == reflect.Struct {
			p.stype = t1.Elem()
		}
	case reflect.Slice:
		switch t2 := t1.Elem(); t2.Kind() {
		case reflect.Ptr:
			switch t3 := t2.Elem(); t3.Kind() {
			case reflect.Struct:
				p.stype = t3
			}
		case reflect.Struct:
			p.stype = t2
		}

	case reflect.Map:

		p.mtype = t1
		p.MapKeyProp = &Properties{}
		p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
		p.MapValProp = &Properties{}
		vtype := p.mtype.Elem()
		if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
			// The value type is not a message (*T) or bytes ([]byte),
			// so we need encoders for the pointer to this type.
			vtype = reflect.PtrTo(vtype)
		}

		p.MapValProp.CustomType = p.CustomType
		p.MapValProp.StdDuration = p.StdDuration
		p.MapValProp.StdTime = p.StdTime
		p.MapValProp.WktPointer = p.WktPointer
		p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
	}
	p.setTag(lockGetProp)
}

func (p *Properties) setTag(lockGetProp bool) {
	if p.stype != nil {
		if lockGetProp {
			p.sprop = GetProperties(p.stype)
		} else {
			p.sprop = getPropertiesLocked(p.stype)
		}
	}
}

var (
	marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
)

// Init populates the properties from a protocol buffer struct tag.
func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
	p.init(typ, name, tag, f, true)
}

func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
	// "bytes,49,opt,def=hello!"
	p.Name = name
	p.OrigName = name
	if tag == "" {
		return
	}
	p.Parse(tag)
	p.setFieldProps(typ, f, lockGetProp)
}

var (
	propertiesMu  sync.RWMutex
	propertiesMap = make(map[reflect.Type]*StructProperties)
)

// GetProperties returns the list of properties for the type represented by t.
// t must represent a generated struct type of a protocol message.
func GetProperties(t reflect.Type) *StructProperties {
	if t.Kind() != reflect.Struct {
		panic("proto: type must have kind struct")
	}

	// Most calls to GetProperties in a long-running program will be
	// retrieving details for types we have seen before.
	propertiesMu.RLock()
	sprop, ok := propertiesMap[t]
	propertiesMu.RUnlock()
	if ok {
		return sprop
	}

	propertiesMu.Lock()
	sprop = getPropertiesLocked(t)
	propertiesMu.Unlock()
	return sprop
}

type (
	oneofFuncsIface interface {
		XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
	}
	oneofWrappersIface interface {
		XXX_OneofWrappers() []interface{}
	}
)

// getPropertiesLocked requires that propertiesMu is held.
func getPropertiesLocked(t reflect.Type) *StructProperties {
	if prop, ok := propertiesMap[t]; ok {
		return prop
	}

	prop := new(StructProperties)
	// in case of recursive protos, fill this in now.
	propertiesMap[t] = prop

	// build properties
	prop.Prop = make([]*Properties, t.NumField())
	prop.order = make([]int, t.NumField())

	isOneofMessage := false
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		p := new(Properties)
		name := f.Name
		p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)

		oneof := f.Tag.Get("protobuf_oneof") // special case
		if oneof != "" {
			isOneofMessage = true
			// Oneof fields don't use the traditional protobuf tag.
			p.OrigName = oneof
		}
		prop.Prop[i] = p
		prop.order[i] = i
		if debug {
			print(i, " ", f.Name, " ", t.String(), " ")
			if p.Tag > 0 {
				print(p.String())
			}
			print("\n")
		}
	}

	// Re-order prop.order.
	sort.Sort(prop)

	if isOneofMessage {
		var oots []interface{}
		switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
		case oneofFuncsIface:
			_, _, _, oots = m.XXX_OneofFuncs()
		case oneofWrappersIface:
			oots = m.XXX_OneofWrappers()
		}
		if len(oots) > 0 {
			// Interpret oneof metadata.
			prop.OneofTypes = make(map[string]*OneofProperties)
			for _, oot := range oots {
				oop := &OneofProperties{
					Type: reflect.ValueOf(oot).Type(), // *T
					Prop: new(Properties),
				}
				sft := oop.Type.Elem().Field(0)
				oop.Prop.Name = sft.Name
				oop.Prop.Parse(sft.Tag.Get("protobuf"))
				// There will be exactly one interface field that
				// this new value is assignable to.
				for i := 0; i < t.NumField(); i++ {
					f := t.Field(i)
					if f.Type.Kind() != reflect.Interface {
						continue
					}
					if !oop.Type.AssignableTo(f.Type) {
						continue
					}
					oop.Field = i
					break
				}
				prop.OneofTypes[oop.Prop.OrigName] = oop
			}
		}
	}

	// build required counts
	// build tags
	reqCount := 0
	prop.decoderOrigNames = make(map[string]int)
	for i, p := range prop.Prop {
		if strings.HasPrefix(p.Name, "XXX_") {
			// Internal fields should not appear in tags/origNames maps.
			// They are handled specially when encoding and decoding.
			continue
		}
		if p.Required {
			reqCount++
		}
		prop.decoderTags.put(p.Tag, i)
		prop.decoderOrigNames[p.OrigName] = i
	}
	prop.reqCount = reqCount

	return prop
}

// A global registry of enum types.
// The generated code will register the generated maps by calling RegisterEnum.

var enumValueMaps = make(map[string]map[string]int32)
var enumStringMaps = make(map[string]map[int32]string)

// RegisterEnum is called from the generated code to install the enum descriptor
// maps into the global table to aid parsing text format protocol buffers.
func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
	if _, ok := enumValueMaps[typeName]; ok {
		panic("proto: duplicate enum registered: " + typeName)
	}
	enumValueMaps[typeName] = valueMap
	if _, ok := enumStringMaps[typeName]; ok {
		panic("proto: duplicate enum registered: " + typeName)
	}
	enumStringMaps[typeName] = unusedNameMap
}

// EnumValueMap returns the mapping from names to integers of the
// enum type enumType, or a nil if not found.
func EnumValueMap(enumType string) map[string]int32 {
	return enumValueMaps[enumType]
}

// A registry of all linked message types.
// The string is a fully-qualified proto name ("pkg.Message").
var (
	protoTypedNils = make(map[string]Message)      // a map from proto names to typed nil pointers
	protoMapTypes  = make(map[string]reflect.Type) // a map from proto names to map types
	revProtoTypes  = make(map[reflect.Type]string)
)

// RegisterType is called from generated code and maps from the fully qualified
// proto name to the type (pointer to struct) of the protocol buffer.
func RegisterType(x Message, name string) {
	if _, ok := protoTypedNils[name]; ok {
		// TODO: Some day, make this a panic.
		log.Printf("proto: duplicate proto type registered: %s", name)
		return
	}
	t := reflect.TypeOf(x)
	if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
		// Generated code always calls RegisterType with nil x.
		// This check is just for extra safety.
		protoTypedNils[name] = x
	} else {
		protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
	}
	revProtoTypes[t] = name
}

// RegisterMapType is called from generated code and maps from the fully qualified
// proto name to the native map type of the proto map definition.
func RegisterMapType(x interface{}, name string) {
	if reflect.TypeOf(x).Kind() != reflect.Map {
		panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
	}
	if _, ok := protoMapTypes[name]; ok {
		log.Printf("proto: duplicate proto type registered: %s", name)
		return
	}
	t := reflect.TypeOf(x)
	protoMapTypes[name] = t
	revProtoTypes[t] = name
}

// MessageName returns the fully-qualified proto name for the given message type.
func MessageName(x Message) string {
	type xname interface {
		XXX_MessageName() string
	}
	if m, ok := x.(xname); ok {
		return m.XXX_MessageName()
	}
	return revProtoTypes[reflect.TypeOf(x)]
}

// MessageType returns the message type (pointer to struct) for a named message.
// The type is not guaranteed to implement proto.Message if the name refers to a
// map entry.
func MessageType(name string) reflect.Type {
	if t, ok := protoTypedNils[name]; ok {
		return reflect.TypeOf(t)
	}
	return protoMapTypes[name]
}

// A registry of all linked proto files.
var (
	protoFiles = make(map[string][]byte) // file name => fileDescriptor
)

// RegisterFile is called from generated code and maps from the
// full file name of a .proto file to its compressed FileDescriptorProto.
func RegisterFile(filename string, fileDescriptor []byte) {
	protoFiles[filename] = fileDescriptor
}

// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
func FileDescriptor(filename string) []byte { return protoFiles[filename] }


text:
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrestazure.azure_operation import AzureOperationPoller
import uuid

from .. import models

class DeploymentsOperations(object):
    """DeploymentsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An objec model deserializer.
    """

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer

        self.config = config

    def delete(
            self, resource_group_name, deployment_name, custom_headers=None, raw=False, **operation_config):
        """Deletes a deployment from the deployment history.

        A template deployment that is currently running cannot be deleted.
        Deleting a template deployment removes the associated deployment
        operations. Deleting a template deployment does not affect the state of
        the resource group. This is an asynchronous operation that returns a
        status of 202 until the template deployment is successfully deleted.
        The Location response header contains the URI that is used to obtain
        the status of the process. While the process is running, a call to the
        URI in the Location header returns a status of 202. When the process
        finishes, the URI in the Location header returns a status of 204 on
        success. If the asynchronous request failed, the URI in the Location
        header returns an error-level status code.

        :param resource_group_name: The name of the resource group with the
         deployment to delete. The name is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment to delete.
        :type deployment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :rtype:
         :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
         instance that returns None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        def long_running_send():

            request = self._client.delete(url, query_parameters)
            return self._client.send(request, header_parameters, **operation_config)

        def get_long_running_status(status_link, headers=None):

            request = self._client.get(status_link)
            if headers:
                request.headers.update(headers)
            return self._client.send(
                request, header_parameters, **operation_config)

        def get_long_running_output(response):

            if response.status_code not in [202, 204]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            if raw:
                client_raw_response = ClientRawResponse(None, response)
                return client_raw_response

        if raw:
            response = long_running_send()
            return get_long_running_output(response)

        long_running_operation_timeout = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        return AzureOperationPoller(
            long_running_send, get_long_running_output,
            get_long_running_status, long_running_operation_timeout)

    def check_existence(
            self, resource_group_name, deployment_name, custom_headers=None, raw=False, **operation_config):
        """Checks whether the deployment exists.

        :param resource_group_name: The name of the resource group with the
         deployment to check. The name is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment to check.
        :type deployment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: bool
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.head(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [204, 404]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = (response.status_code == 204)
        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response
        return deserialized

    def create_or_update(
            self, resource_group_name, deployment_name, properties=None, custom_headers=None, raw=False, **operation_config):
        """Deploys resources to a resource group.

        You can provide the template and parameters directly in the request or
        link to JSON files.

        :param resource_group_name: The name of the resource group to deploy
         the resources to. The name is case insensitive. The resource group
         must already exist.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment.
        :type deployment_name: str
        :param properties: The deployment properties.
        :type properties: :class:`DeploymentProperties
         <azure.mgmt.resource.resources.models.DeploymentProperties>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :rtype:
         :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
         instance that returns :class:`DeploymentExtended
         <azure.mgmt.resource.resources.models.DeploymentExtended>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        parameters = models.Deployment(properties=properties)

        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'Deployment')

        # Construct and send request
        def long_running_send():

            request = self._client.put(url, query_parameters)
            return self._client.send(
                request, header_parameters, body_content, **operation_config)

        def get_long_running_status(status_link, headers=None):

            request = self._client.get(status_link)
            if headers:
                request.headers.update(headers)
            return self._client.send(
                request, header_parameters, **operation_config)

        def get_long_running_output(response):

            if response.status_code not in [200, 201]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            deserialized = None

            if response.status_code == 200:
                deserialized = self._deserialize('DeploymentExtended', response)
            if response.status_code == 201:
                deserialized = self._deserialize('DeploymentExtended', response)

            if raw:
                client_raw_response = ClientRawResponse(deserialized, response)
                return client_raw_response

            return deserialized

        if raw:
            response = long_running_send()
            return get_long_running_output(response)

        long_running_operation_timeout = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        return AzureOperationPoller(
            long_running_send, get_long_running_output,
            get_long_running_status, long_running_operation_timeout)

    def get(
            self, resource_group_name, deployment_name, custom_headers=None, raw=False, **operation_config):
        """Gets a deployment.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment to get.
        :type deployment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`DeploymentExtended
         <azure.mgmt.resource.resources.models.DeploymentExtended>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('DeploymentExtended', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def cancel(
            self, resource_group_name, deployment_name, custom_headers=None, raw=False, **operation_config):
        """Cancels a currently running template deployment.

        You can cancel a deployment only if the provisioningState is Accepted
        or Running. After the deployment is canceled, the provisioningState is
        set to Canceled. Canceling a template deployment stops the currently
        running template deployment and leaves the resource group partially
        deployed.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment to cancel.
        :type deployment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/cancel'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [204]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def validate(
            self, resource_group_name, deployment_name, properties=None, custom_headers=None, raw=False, **operation_config):
        """Validates whether the specified template is syntactically correct and
        will be accepted by Azure Resource Manager..

        :param resource_group_name: The name of the resource group the
         template will be deployed to. The name is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment.
        :type deployment_name: str
        :param properties: The deployment properties.
        :type properties: :class:`DeploymentProperties
         <azure.mgmt.resource.resources.models.DeploymentProperties>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`DeploymentValidateResult
         <azure.mgmt.resource.resources.models.DeploymentValidateResult>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        parameters = models.Deployment(properties=properties)

        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/validate'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'Deployment')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, **operation_config)

        if response.status_code not in [200, 400]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('DeploymentValidateResult', response)
        if response.status_code == 400:
            deserialized = self._deserialize('DeploymentValidateResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def export_template(
            self, resource_group_name, deployment_name, custom_headers=None, raw=False, **operation_config):
        """Exports the template used for specified deployment.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment from which to get
         the template.
        :type deployment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`DeploymentExportResult
         <azure.mgmt.resource.resources.models.DeploymentExportResult>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/exportTemplate'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str', max_length=64, min_length=1, pattern='^[-\w\._\(\)]+$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('DeploymentExportResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def list(
            self, resource_group_name, filter=None, top=None, custom_headers=None, raw=False, **operation_config):
        """Get all the deployments for a resource group.

        :param resource_group_name: The name of the resource group with the
         deployments to get. The name is case insensitive.
        :type resource_group_name: str
        :param filter: The filter to apply on the operation. For example, you
         can use $filter=provisioningState eq '{state}'.
        :type filter: str
        :param top: The number of results to get. If null is passed, returns
         all deployments.
        :type top: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`DeploymentExtendedPaged
         <azure.mgmt.resource.resources.models.DeploymentExtendedPaged>`
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/'
                path_format_arguments = {
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\w\._\(\)]+$'),
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.DeploymentExtendedPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.DeploymentExtendedPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized


text:
This directory contains tests that run CMake to configure a project
but do not actually build anything.  To add a test:

1. Add a subdirectory named for the test, say ``<Test>/``.

2. In ``./CMakeLists.txt`` call ``add_RunCMake_test`` and pass the
   test directory name ``<Test>``.

3. Create script ``<Test>/RunCMakeTest.cmake`` in the directory containing::

    include(RunCMake)
    run_cmake(SubTest1)
    ...
    run_cmake(SubTestN)

   where ``SubTest1`` through ``SubTestN`` are sub-test names each
   corresponding to an independent CMake run and project configuration.

   One may also add calls of the form::

    run_cmake_command(SubTestI ${CMAKE_COMMAND} ...)

   to fully customize the test case command-line.

4. Create file ``<Test>/CMakeLists.txt`` in the directory containing::

    cmake_minimum_required(...)
    project(${RunCMake_TEST} NONE) # or languages needed
    include(${RunCMake_TEST}.cmake)

   where ``${RunCMake_TEST}`` is literal.  A value for ``RunCMake_TEST``
   will be passed to CMake by the ``run_cmake`` macro when running each
   sub-test.

5. Create a ``<Test>/<SubTest>.cmake`` file for each sub-test named
   above containing the actual test code.  Optionally create files
   containing expected test results:

   ``<SubTest>-result.txt``
    Process result expected if not "0"
   ``<SubTest>-stdout.txt``
    Regex matching expected stdout content
   ``<SubTest>-stderr.txt``
    Regex matching expected stderr content
   ``<SubTest>-check.cmake``
    Custom result check.

   Note that trailing newlines will be stripped from actual and expected
   test output before matching against the stdout and stderr expressions.
   The code in ``<SubTest>-check.cmake`` may use variables

   ``RunCMake_TEST_SOURCE_DIR``
    Top of test source tree
   ``RunCMake_TEST_BINARY_DIR``
    Top of test binary tree

   and an failure must store a message in ``RunCMake_TEST_FAILED``.