text:
//////////////////////////////////////////////////////////////
// <auto-generated>This code was generated by LLBLGen Pro 5.7.</auto-generated>
//////////////////////////////////////////////////////////////
// Code is generated on:
// Code is generated using templates: SD.TemplateBindings.SharedTemplates
// Templates vendor: Solutions Design.
//////////////////////////////////////////////////////////////
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using AdventureWorks.Dal.Adapter.HelperClasses;
using AdventureWorks.Dal.Adapter.FactoryClasses;
using AdventureWorks.Dal.Adapter.RelationClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;

namespace AdventureWorks.Dal.Adapter.EntityClasses
{
	// __LLBLGENPRO_USER_CODE_REGION_START AdditionalNamespaces
	// __LLBLGENPRO_USER_CODE_REGION_END
	/// Entity class which represents the entity 'Customer'.

	[Serializable]
	public partial class CustomerEntity : CommonEntityBase
		// __LLBLGENPRO_USER_CODE_REGION_START AdditionalInterfaces
		// __LLBLGENPRO_USER_CODE_REGION_END
	{
		private EntityCollection<SalesOrderHeaderEntity> _salesOrderHeaders;
		private PersonEntity _person;
		private SalesTerritoryEntity _salesTerritory;
		private StoreEntity _store;

		// __LLBLGENPRO_USER_CODE_REGION_START PrivateMembers
		// __LLBLGENPRO_USER_CODE_REGION_END
		private static CustomerEntityStaticMetaData _staticMetaData = new CustomerEntityStaticMetaData();
		private static CustomerRelations _relationsFactory = new CustomerRelations();

		/// All names of fields mapped onto a relation. Usable for in-memory filtering
		public static partial class MemberNames
		{
			/// Member name Person
			public static readonly string Person = "Person";
			/// Member name SalesTerritory
			public static readonly string SalesTerritory = "SalesTerritory";
			/// Member name Store
			public static readonly string Store = "Store";
			/// Member name SalesOrderHeaders
			public static readonly string SalesOrderHeaders = "SalesOrderHeaders";
		}

		/// Static meta-data storage for navigator related information
		protected class CustomerEntityStaticMetaData : EntityStaticMetaDataBase
		{
			public CustomerEntityStaticMetaData()
			{
				SetEntityCoreInfo("CustomerEntity", InheritanceHierarchyType.None, false, (int)AdventureWorks.Dal.Adapter.EntityType.CustomerEntity, typeof(CustomerEntity), typeof(CustomerEntityFactory), false);
				AddNavigatorMetaData<CustomerEntity, EntityCollection<SalesOrderHeaderEntity>>("SalesOrderHeaders", a => a._salesOrderHeaders, (a, b) => a._salesOrderHeaders = b, a => a.SalesOrderHeaders, () => new CustomerRelations().SalesOrderHeaderEntityUsingCustomerId, typeof(SalesOrderHeaderEntity), (int)AdventureWorks.Dal.Adapter.EntityType.SalesOrderHeaderEntity);
				AddNavigatorMetaData<CustomerEntity, PersonEntity>("Person", "Customers", (a, b) => a._person = b, a => a._person, (a, b) => a.Person = b, AdventureWorks.Dal.Adapter.RelationClasses.StaticCustomerRelations.PersonEntityUsingPersonIdStatic, ()=>new CustomerRelations().PersonEntityUsingPersonId, null, new int[] { (int)CustomerFieldIndex.PersonId }, null, true, (int)AdventureWorks.Dal.Adapter.EntityType.PersonEntity);
				AddNavigatorMetaData<CustomerEntity, SalesTerritoryEntity>("SalesTerritory", "Customers", (a, b) => a._salesTerritory = b, a => a._salesTerritory, (a, b) => a.SalesTerritory = b, AdventureWorks.Dal.Adapter.RelationClasses.StaticCustomerRelations.SalesTerritoryEntityUsingTerritoryIdStatic, ()=>new CustomerRelations().SalesTerritoryEntityUsingTerritoryId, null, new int[] { (int)CustomerFieldIndex.TerritoryId }, null, true, (int)AdventureWorks.Dal.Adapter.EntityType.SalesTerritoryEntity);
				AddNavigatorMetaData<CustomerEntity, StoreEntity>("Store", "Customers", (a, b) => a._store = b, a => a._store, (a, b) => a.Store = b, AdventureWorks.Dal.Adapter.RelationClasses.StaticCustomerRelations.StoreEntityUsingStoreIdStatic, ()=>new CustomerRelations().StoreEntityUsingStoreId, null, new int[] { (int)CustomerFieldIndex.StoreId }, null, true, (int)AdventureWorks.Dal.Adapter.EntityType.StoreEntity);
			}
		}

		/// Static ctor
		static CustomerEntity()
		{
		}

		///  CTor
		public CustomerEntity()
		{
			InitClassEmpty(null, null);
		}

		///  CTor
		/// <param name="fields">Fields object to set as the fields for this entity.</param>
		public CustomerEntity(IEntityFields2 fields)
		{
			InitClassEmpty(null, fields);
		}

		///  CTor
		/// <param name="validator">The custom validator object for this CustomerEntity</param>
		public CustomerEntity(IValidator validator)
		{
			InitClassEmpty(validator, null);
		}

		///  CTor
		/// <param name="customerId">PK value for Customer which data should be fetched into this Customer object</param>
		public CustomerEntity(System.Int32 customerId) : this(customerId, null)
		{
		}

		///  CTor
		/// <param name="customerId">PK value for Customer which data should be fetched into this Customer object</param>
		/// <param name="validator">The custom validator object for this CustomerEntity</param>
		public CustomerEntity(System.Int32 customerId, IValidator validator)
		{
			InitClassEmpty(validator, null);
			this.CustomerId = customerId;
		}

		/// Private CTor for deserialization
		/// <param name="info"></param>
		/// <param name="context"></param>
		protected CustomerEntity(SerializationInfo info, StreamingContext context) : base(info, context)
		{
			// __LLBLGENPRO_USER_CODE_REGION_START DeserializationConstructor
			// __LLBLGENPRO_USER_CODE_REGION_END
		}

		/// Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entities of type 'SalesOrderHeader' to this entity.
		/// <returns></returns>
		public virtual IRelationPredicateBucket GetRelationInfoSalesOrderHeaders() { return CreateRelationInfoForNavigator("SalesOrderHeaders"); }

		/// Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entity of type 'Person' to this entity.
		/// <returns></returns>
		public virtual IRelationPredicateBucket GetRelationInfoPerson() { return CreateRelationInfoForNavigator("Person"); }

		/// Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entity of type 'SalesTerritory' to this entity.
		/// <returns></returns>
		public virtual IRelationPredicateBucket GetRelationInfoSalesTerritory() { return CreateRelationInfoForNavigator("SalesTerritory"); }

		/// Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entity of type 'Store' to this entity.
		/// <returns></returns>
		public virtual IRelationPredicateBucket GetRelationInfoStore() { return CreateRelationInfoForNavigator("Store"); }

		/// <inheritdoc/>
		protected override EntityStaticMetaDataBase GetEntityStaticMetaData() {	return _staticMetaData; }

		/// Initializes the class members
		private void InitClassMembers()
		{
			PerformDependencyInjection();
			// __LLBLGENPRO_USER_CODE_REGION_START InitClassMembers
			// __LLBLGENPRO_USER_CODE_REGION_END
			OnInitClassMembersComplete();
		}

		/// Initializes the class with empty data, as if it is a new Entity.
		/// <param name="validator">The validator object for this CustomerEntity</param>
		/// <param name="fields">Fields of this entity</param>
		private void InitClassEmpty(IValidator validator, IEntityFields2 fields)
		{
			OnInitializing();
			this.Fields = fields ?? CreateFields();
			this.Validator = validator;
			InitClassMembers();
			// __LLBLGENPRO_USER_CODE_REGION_START InitClassEmpty
			// __LLBLGENPRO_USER_CODE_REGION_END

			OnInitialized();
		}

		/// The relations object holding all relations of this entity with other entity classes.
		public static CustomerRelations Relations { get { return _relationsFactory; } }

		/// Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'SalesOrderHeader' for this entity.
		/// <returns>Ready to use IPrefetchPathElement2 implementation.</returns>
		public static IPrefetchPathElement2 PrefetchPathSalesOrderHeaders { get { return _staticMetaData.GetPrefetchPathElement("SalesOrderHeaders", CommonEntityBase.CreateEntityCollection<SalesOrderHeaderEntity>()); } }

		/// Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'Person' for this entity.
		/// <returns>Ready to use IPrefetchPathElement2 implementation.</returns>
		public static IPrefetchPathElement2 PrefetchPathPerson { get { return _staticMetaData.GetPrefetchPathElement("Person", CommonEntityBase.CreateEntityCollection<PersonEntity>()); } }

		/// Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'SalesTerritory' for this entity.
		/// <returns>Ready to use IPrefetchPathElement2 implementation.</returns>
		public static IPrefetchPathElement2 PrefetchPathSalesTerritory { get { return _staticMetaData.GetPrefetchPathElement("SalesTerritory", CommonEntityBase.CreateEntityCollection<SalesTerritoryEntity>()); } }

		/// Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'Store' for this entity.
		/// <returns>Ready to use IPrefetchPathElement2 implementation.</returns>
		public static IPrefetchPathElement2 PrefetchPathStore { get { return _staticMetaData.GetPrefetchPathElement("Store", CommonEntityBase.CreateEntityCollection<StoreEntity>()); } }

		/// The AccountNumber property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."AccountNumber".
Table field type characteristics (type, precision, scale, length): VarChar, 0, 0, 10.
Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.String AccountNumber
		{
			get { return (System.String)GetValue((int)CustomerFieldIndex.AccountNumber, true); }
		}

		/// The CustomerId property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."CustomerID".
Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0.
Table field behavior characteristics (is nullable, is PK, is identity): false, true, true</remarks>
		public virtual System.Int32 CustomerId
		{
			get { return (System.Int32)GetValue((int)CustomerFieldIndex.CustomerId, true); }
			set { SetValue((int)CustomerFieldIndex.CustomerId, value); }		}

		/// The ModifiedDate property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."ModifiedDate".
Table field type characteristics (type, precision, scale, length): DateTime, 0, 0, 0.
Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.DateTime ModifiedDate
		{
			get { return (System.DateTime)GetValue((int)CustomerFieldIndex.ModifiedDate, true); }
			set	{ SetValue((int)CustomerFieldIndex.ModifiedDate, value); }
		}

		/// The PersonId property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."PersonID".
Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0.
Table field behavior characteristics (is nullable, is PK, is identity): true, false, false</remarks>
		public virtual Nullable<System.Int32> PersonId
		{
			get { return (Nullable<System.Int32>)GetValue((int)CustomerFieldIndex.PersonId, false); }
			set	{ SetValue((int)CustomerFieldIndex.PersonId, value); }
		}

		/// The Rowguid property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."rowguid".
Table field type characteristics (type, precision, scale, length): UniqueIdentifier, 0, 0, 0.
Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.Guid Rowguid
		{
			get { return (System.Guid)GetValue((int)CustomerFieldIndex.Rowguid, true); }
			set	{ SetValue((int)CustomerFieldIndex.Rowguid, value); }
		}

		/// The StoreId property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."StoreID".
Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0.
Table field behavior characteristics (is nullable, is PK, is identity): true, false, false</remarks>
		public virtual Nullable<System.Int32> StoreId
		{
			get { return (Nullable<System.Int32>)GetValue((int)CustomerFieldIndex.StoreId, false); }
			set	{ SetValue((int)CustomerFieldIndex.StoreId, value); }
		}

		/// The TerritoryId property of the Entity Customer

		/// <remarks>Mapped on  table field: "Customer"."TerritoryID".
Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0.
Table field behavior characteristics (is nullable, is PK, is identity): true, false, false</remarks>
		public virtual Nullable<System.Int32> TerritoryId
		{
			get { return (Nullable<System.Int32>)GetValue((int)CustomerFieldIndex.TerritoryId, false); }
			set	{ SetValue((int)CustomerFieldIndex.TerritoryId, value); }
		}

		/// Gets the EntityCollection with the related entities of type 'SalesOrderHeaderEntity' which are related to this entity via a relation of type '1:n'. If the EntityCollection hasn't been fetched yet, the collection returned will be empty.

		[TypeContainedAttribute(typeof(SalesOrderHeaderEntity))]
		public virtual EntityCollection<SalesOrderHeaderEntity> SalesOrderHeaders { get { return GetOrCreateEntityCollection<SalesOrderHeaderEntity, SalesOrderHeaderEntityFactory>("Customer", true, false, ref _salesOrderHeaders); } }

		/// Gets / sets related entity of type 'PersonEntity' which has to be set using a fetch action earlier. If no related entity is set for this property, null is returned..

		[Browsable(false)]
		public virtual PersonEntity Person
		{
			get { return _person; }
			set { SetSingleRelatedEntityNavigator(value, "Person"); }
		}

		/// Gets / sets related entity of type 'SalesTerritoryEntity' which has to be set using a fetch action earlier. If no related entity is set for this property, null is returned..

		[Browsable(false)]
		public virtual SalesTerritoryEntity SalesTerritory
		{
			get { return _salesTerritory; }
			set { SetSingleRelatedEntityNavigator(value, "SalesTerritory"); }
		}

		/// Gets / sets related entity of type 'StoreEntity' which has to be set using a fetch action earlier. If no related entity is set for this property, null is returned..

		[Browsable(false)]
		public virtual StoreEntity Store
		{
			get { return _store; }
			set { SetSingleRelatedEntityNavigator(value, "Store"); }
		}

		// __LLBLGENPRO_USER_CODE_REGION_START CustomEntityCode
		// __LLBLGENPRO_USER_CODE_REGION_END

	}
}

namespace AdventureWorks.Dal.Adapter
{
	public enum CustomerFieldIndex
	{
		///AccountNumber.
		AccountNumber,
		///CustomerId.
		CustomerId,
		///ModifiedDate.
		ModifiedDate,
		///PersonId.
		PersonId,
		///Rowguid.
		Rowguid,
		///StoreId.
		StoreId,
		///TerritoryId.
		TerritoryId,
		///
		AmountOfFields
	}
}

namespace AdventureWorks.Dal.Adapter.RelationClasses
{
	/// Implements the relations factory for the entity: Customer.
	public partial class CustomerRelations: RelationFactory
	{
		/// Returns a new IEntityRelation object, between CustomerEntity and SalesOrderHeaderEntity over the 1:n relation they have, using the relation between the fields: Customer.CustomerId - SalesOrderHeader.CustomerId
		public virtual IEntityRelation SalesOrderHeaderEntityUsingCustomerId
		{
			get { return ModelInfoProviderSingleton.GetInstance().CreateRelation(RelationType.OneToMany, "SalesOrderHeaders", true, new[] { CustomerFields.CustomerId, SalesOrderHeaderFields.CustomerId }); }
		}

		/// Returns a new IEntityRelation object, between CustomerEntity and PersonEntity over the m:1 relation they have, using the relation between the fields: Customer.PersonId - Person.BusinessEntityId
		public virtual IEntityRelation PersonEntityUsingPersonId
		{
			get	{ return ModelInfoProviderSingleton.GetInstance().CreateRelation(RelationType.ManyToOne, "Person", false, new[] { PersonFields.BusinessEntityId, CustomerFields.PersonId }); }
		}

		/// Returns a new IEntityRelation object, between CustomerEntity and SalesTerritoryEntity over the m:1 relation they have, using the relation between the fields: Customer.TerritoryId - SalesTerritory.TerritoryId
		public virtual IEntityRelation SalesTerritoryEntityUsingTerritoryId
		{
			get	{ return ModelInfoProviderSingleton.GetInstance().CreateRelation(RelationType.ManyToOne, "SalesTerritory", false, new[] { SalesTerritoryFields.TerritoryId, CustomerFields.TerritoryId }); }
		}

		/// Returns a new IEntityRelation object, between CustomerEntity and StoreEntity over the m:1 relation they have, using the relation between the fields: Customer.StoreId - Store.CustomerId
		public virtual IEntityRelation StoreEntityUsingStoreId
		{
			get	{ return ModelInfoProviderSingleton.GetInstance().CreateRelation(RelationType.ManyToOne, "Store", false, new[] { StoreFields.CustomerId, CustomerFields.StoreId }); }
		}

	}

	/// Static class which is used for providing relationship instances which are re-used internally for syncing
	internal static class StaticCustomerRelations
	{
		internal static readonly IEntityRelation SalesOrderHeaderEntityUsingCustomerIdStatic = new CustomerRelations().SalesOrderHeaderEntityUsingCustomerId;
		internal static readonly IEntityRelation PersonEntityUsingPersonIdStatic = new CustomerRelations().PersonEntityUsingPersonId;
		internal static readonly IEntityRelation SalesTerritoryEntityUsingTerritoryIdStatic = new CustomerRelations().SalesTerritoryEntityUsingTerritoryId;
		internal static readonly IEntityRelation StoreEntityUsingStoreIdStatic = new CustomerRelations().StoreEntityUsingStoreId;

		/// CTor
		static StaticCustomerRelations() { }
	}
}


text:
var parseParams = require('../lib/utils').parseParams;

var path = require('path'),
    assert = require('assert'),
    inspect = require('util').inspect;

var group = path.basename(__filename, '.js') + '/';

[
  { source: 'video/ogg',
    expected: ['video/ogg'],
    what: 'No parameters'
  },
  { source: 'video/ogg;',
    expected: ['video/ogg'],
    what: 'No parameters (with separator)'
  },
  { source: 'video/ogg; ',
    expected: ['video/ogg'],
    what: 'No parameters (with separator followed by whitespace)'
  },
  { source: ';video/ogg',
    expected: ['', 'video/ogg'],
    what: 'Empty parameter'
  },
  { source: 'video/*',
    expected: ['video/*'],
    what: 'Subtype with asterisk'
  },
  { source: 'text/plain; encoding=utf8',
    expected: ['text/plain', ['encoding', 'utf8']],
    what: 'Unquoted'
  },
  { source: 'text/plain; encoding=',
    expected: ['text/plain', ['encoding', '']],
    what: 'Unquoted empty string'
  },
  { source: 'text/plain; encoding="utf8"',
    expected: ['text/plain', ['encoding', 'utf8']],
    what: 'Quoted'
  },
  { source: 'text/plain; greeting="hello \\"world\\""',
    expected: ['text/plain', ['greeting', 'hello "world"']],
    what: 'Quotes within quoted'
  },
  { source: 'text/plain; encoding=""',
    expected: ['text/plain', ['encoding', '']],
    what: 'Quoted empty string'
  },
  { source: 'text/plain; encoding="utf8";\t   foo=bar;test',
    expected: ['text/plain', ['encoding', 'utf8'], ['foo', 'bar'], 'test'],
    what: 'Multiple params with various spacing'
  },
  { source: "text/plain; filename*=iso-8859-1'en'%A3%20rates",
    expected: ['text/plain', ['filename', '£ rates']],
    what: 'Extended parameter (RFC 5987) with language'
  },
  { source: "text/plain; filename*=utf-8''%c2%a3%20and%20%e2%82%ac%20rates",
    expected: ['text/plain', ['filename', '£ and € rates']],
    what: 'Extended parameter (RFC 5987) without language'
  },
  { source: "text/plain; filename*=utf-8''%E6%B5%8B%E8%AF%95%E6%96%87%E6%A1%A3",
    expected: ['text/plain', ['filename', '测试文档']],
    what: 'Extended parameter (RFC 5987) without language #2'
  },
  { source: "text/plain; filename*=iso-8859-1'en'%A3%20rates; altfilename*=utf-8''%c2%a3%20and%20%e2%82%ac%20rates",
    expected: ['text/plain', ['filename', '£ rates'], ['altfilename', '£ and € rates']],
    what: 'Multiple extended parameters (RFC 5987) with mixed charsets'
  },
  { source: "text/plain; filename*=iso-8859-1'en'%A3%20rates; altfilename=\"foobarbaz\"",
    expected: ['text/plain', ['filename', '£ rates'], ['altfilename', 'foobarbaz']],
    what: 'Mixed regular and extended parameters (RFC 5987)'
  },
  { source: "text/plain; filename=\"foobarbaz\"; altfilename*=iso-8859-1'en'%A3%20rates",
    expected: ['text/plain', ['filename', 'foobarbaz'], ['altfilename', '£ rates']],
    what: 'Mixed regular and extended parameters (RFC 5987) #2'
  },
  { source: 'text/plain; filename="C:\\folder\\test.png"',
    expected: ['text/plain', ['filename', 'C:\\folder\\test.png']],
    what: 'Unescaped backslashes should be considered backslashes'
  },
  { source: 'text/plain; filename="John \\"Magic\\" Smith.png"',
    expected: ['text/plain', ['filename', 'John "Magic" Smith.png']],
    what: 'Escaped double-quotes should be considered double-quotes'
  },
  { source: 'multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY',
    expected: ['multipart/form-data', ['charset', 'utf-8'], ['boundary', '0xKhTmLbOuNdArY']],
    what: 'Multiple non-quoted parameters'
  },
].forEach(function(v) {
  var result = parseParams(v.source),
      msg = '[' + group + v.what + ']: parsed parameters mismatch.\n'
            + 'Saw: ' + inspect(result) + '\n'
            + 'Expected: ' + inspect(v.expected);
  assert.deepEqual(result, v.expected, msg);
});

redpajama_set_name: RedPajamaGithub


text:
package uk.ac.ncl.openlab.intake24.services.fooddb.admin

import uk.ac.ncl.openlab.intake24.api.data.AssociatedFood
import uk.ac.ncl.openlab.intake24.api.data.admin.AssociatedFoodWithHeader
import uk.ac.ncl.openlab.intake24.errors.{LocalLookupError, LocaleOrParentError, UnexpectedDatabaseError}
import uk.ac.ncl.openlab.intake24.services.fooddb.user.AssociatedFoodsService

trait AssociatedFoodsAdminService extends AssociatedFoodsService {

  def getAssociatedFoodsWithHeaders(foodCode: String, locale: String): Either[LocalLookupError, Seq[AssociatedFoodWithHeader]]

  def updateAssociatedFoods(foodCode: String, associatedFoods: Seq[AssociatedFood], locale: String): Either[LocaleOrParentError, Unit]

  def deleteAllAssociatedFoods(locale: String): Either[UnexpectedDatabaseError, Unit]

  def createAssociatedFoods(assocFoods: Map[String, Seq[AssociatedFood]], locale: String): Either[LocaleOrParentError, Unit]
}


text: {{fieldName}}{{fieldType}}{{fieldDefault}}{{fieldNotNull}}COMMENT '{{fieldComment}}',


text:
package hudson.plugins.warnings.parser;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.common.collect.Lists;

import hudson.Extension;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.analysis.util.model.Priority;
import hudson.plugins.warnings.WarningsDescriptor;
import hudson.plugins.warnings.util.XmlElementUtil;

/**
 * A parser for IntelliJ IDEA inspections.
 *
 * @author Alex Lopashev, alexlopashev@gmail.com
 */
@Extension
public class IdeaInspectionParser extends AbstractWarningsParser {
    private static final long serialVersionUID = 3307389086106375473L;

    private static final String IDEA_SMALL_ICON = WarningsDescriptor.IMAGE_PREFIX + "idea-24x24.png";
    private static final String IDEA_LARGE_ICON = WarningsDescriptor.IMAGE_PREFIX + "idea-48x48.png";

    /**
     * Creates a new instance of {@link IdeaInspectionParser}.
     */
    public IdeaInspectionParser() {
        super(Messages._Warnings_IdeaInspection_ParserName(),
                Messages._Warnings_IdeaInspection_LinkName(),
                Messages._Warnings_IdeaInspection_TrendName());
    }

    @Override
    public Collection<FileAnnotation> parse(Reader reader) throws IOException {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(new InputSource(reader));

            Element rootElement = (Element) document.getElementsByTagName("problems").item(0);
            return parseProblems(XmlElementUtil.getNamedChildElements(rootElement, "problem"));
        }
        catch (ParserConfigurationException exception) {
            throw new IOException(exception);
        }
        catch (SAXException exception) {
            throw new IOException(exception);
        }
    }

    private List<FileAnnotation> parseProblems(List<Element> elements) {
        List<FileAnnotation> problems = Lists.newArrayList();
        for (Element element : elements) {
            String file = getChildValue(element, "file");
            int line = Integer.parseInt(getChildValue(element, "line"));
            Element problemClass = XmlElementUtil.getFirstElementByTagName(element, "problem_class");
            String severity = problemClass.getAttribute("severity");
            String category = StringEscapeUtils.unescapeXml(getValue(problemClass));
            String description = StringEscapeUtils.unescapeXml(getChildValue(element, "description"));
            problems.add(createWarning(file, line, category, description, getPriority(severity)));
        }
        return problems;
    }

    private Priority getPriority(String severity) {
        Priority priority = Priority.LOW;
        if (severity.equals("WARNING")) {
            priority = Priority.NORMAL;
        }
        else if (severity.equals("ERROR")) {
            priority = Priority.HIGH;
        }
        return priority;
    }

    private String getValue(Element element) {
        return element.getFirstChild().getNodeValue();
    }

    private String getChildValue(Element element, String childTag) {
        Element firstElement = XmlElementUtil.getFirstElementByTagName(element, childTag);
        if (firstElement != null) {
            Node child = firstElement.getFirstChild();
            if (child != null) {
                return child.getNodeValue();
            }
        }
        return "-";
    }

    @Override
    protected String getId() {
        return "IntelliJ IDEA Inspections";
    }

    @Override
    public String getSmallImage() {
        return IDEA_SMALL_ICON;
    }

    @Override
    public String getLargeImage() {
        return IDEA_LARGE_ICON;
    }
}


text:
package com.ai.st.at;

public class DemoProvidercClientApplication {

	public static void main(String[] args) {
	}
}


text:
import fn from '../../isSaturday/index'
import convertToFP from '../_lib/convertToFP/index'

export default convertToFP(fn, 1)


text: User ID. A user should be registered in Jenkins.


text:
package org.hswebframework.web.authorization.oauth2.client.simple.request;

import org.hswebframework.expands.request.http.HttpRequest;
import org.hswebframework.expands.request.http.Response;
import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
import org.hswebframework.web.authorization.oauth2.client.request.ResponseConvertHandler;
import org.hswebframework.web.authorization.oauth2.client.request.ResponseJudge;
import org.hswebframework.web.authorization.oauth2.client.request.TokenExpiredCallBack;
import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
import org.hswebframework.web.oauth2.core.ErrorType;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author zhouhao
 */
public class SimpleOAuth2Request implements OAuth2Request {

    private HttpRequest request;

    private ResponseConvertHandler convertHandler;

    private ResponseJudge responseJudge;

    private TokenExpiredCallBack expiredCallBack;

    private TokenExpiredCallBack refreshTokenExpiredCallBack;

    public SimpleOAuth2Request(HttpRequest request) {
        this.request = request;
    }

    public void setConvertHandler(ResponseConvertHandler convertHandler) {
        this.convertHandler = convertHandler;
    }

    public void setResponseJudge(ResponseJudge responseJudge) {
        this.responseJudge = responseJudge;
    }

    @Override
    public OAuth2Request onRefreshTokenExpired(TokenExpiredCallBack refreshTokenExpiredCallBack) {
        this.refreshTokenExpiredCallBack = refreshTokenExpiredCallBack;
        return this;
    }

    @Override
    public OAuth2Request onTokenExpired(TokenExpiredCallBack callback) {
        this.expiredCallBack = callback;
        return this;
    }

    @Override
    public OAuth2Response upload(String name, InputStream inputStream) {
        return createUnCheckResponse(() -> request.upload(name, inputStream));
    }

    @Override
    public OAuth2Response upload(String name, InputStream inputStream, String fileName) {
        return createUnCheckResponse(() -> request.upload(name, inputStream, fileName));
    }

    @Override
    public OAuth2Request params(Map<String, String> params) {
        request.params(params);
        return this;
    }

    @Override
    public OAuth2Request param(String name, Object value) {
        request.param(name, String.valueOf(value));
        return this;
    }

    @Override
    public OAuth2Request requestBody(String value) {
        request.requestBody(value);
        return this;
    }

    @Override
    public OAuth2Request header(String name, String value) {
        request.header(name, value);
        return this;
    }

    @Override
    public OAuth2Request cookie(String cookie) {
        request.cookie(cookie);
        return this;
    }

    @Override
    public OAuth2Request contentType(String contentType) {
        request.contentType(contentType);
        return this;
    }

    @Override
    public OAuth2Request accept(String accept) {
        header("Accept", accept);
        return this;
    }

    @Override
    public OAuth2Request timeout(long millisecond, Consumer<OAuth2Request> timeoutCallBack) {
        return this;
    }

    private volatile SimpleOAuth2Response auth2Response;

    protected SimpleOAuth2Response createNativeResponse(Supplier<Response> responseSupplier) {
        SimpleOAuth2Response response = new SimpleOAuth2Response(responseSupplier.get(), convertHandler, responseJudge);

        return auth2Response = response;
    }

    protected OAuth2Response createResponse(Supplier<Response> responseSupplier) {
        createNativeResponse(responseSupplier);
        if (null != expiredCallBack) {
            //判定token是否过期,过期后先执行回调进行操作如更新token,并尝试重新请求
            auth2Response.judgeError(ErrorType.EXPIRED_TOKEN, () -> {

                //调用回调,并指定重试的操作(重新请求)
                expiredCallBack.call(() -> createNativeResponse(responseSupplier));

                //返回重试后的response
                return auth2Response;
            });
        }
        if (null != refreshTokenExpiredCallBack) {
            //判定token是否有效,无效的token将重新申请token
            auth2Response.judgeError(ErrorType.INVALID_TOKEN, () -> {
                //调用回调,并指定重试的操作(重新请求)
                refreshTokenExpiredCallBack.call(() -> createNativeResponse(responseSupplier));
                //返回重试后的response
                return auth2Response;
            });
            //判定refresh_token是否过期,过期后先执行回调进行操作如更新token,并尝试重新请求
            auth2Response.judgeError(ErrorType.EXPIRED_REFRESH_TOKEN, () -> {
                //调用回调,并指定重试的操作(重新请求)
                refreshTokenExpiredCallBack.call(() -> createNativeResponse(responseSupplier));
                //返回重试后的response
                return auth2Response;
            });

            //如果是invalid token 也将重新生成token
            auth2Response.judgeError(ErrorType.INVALID_TOKEN, () -> {
                //调用回调,并指定重试的操作(重新请求)
                refreshTokenExpiredCallBack.call(() -> createNativeResponse(responseSupplier));
                //返回重试后的response
                return auth2Response;
            });
        }
        return auth2Response;
    }

    protected OAuth2Response createUnCheckResponse(UnCheck<Response> unCheck) {
        return createResponse(() -> UnCheck.unCheck(unCheck));
    }

    @Override
    public OAuth2Response get() {
        return createUnCheckResponse(request::get);
    }

    @Override
    public OAuth2Response put() {
        return createUnCheckResponse(request::put);
    }

    @Override
    public OAuth2Response post() {
        return createUnCheckResponse(request::post);
    }

    @Override
    public OAuth2Response delete() {
        return createUnCheckResponse(request::delete);
    }

    @Override
    public OAuth2Response patch() {
        return createUnCheckResponse(request::patch);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Nove</logradouro><bairro>Santa Maria</bairro><cidade>Aracaju</cidade><uf>SE</uf><cep>49043715</cep></feed>


text:
GOC=go build
GOFLAGS=-a -ldflags '-s'
CGOR=CGO_ENABLED=0
OS_PERMS=sudo
CWD=$(shell pwd)
GIT_HASH=$(shell git rev-parse HEAD | head -c 10)
NGINX_BIN_LOC=https://cryo.unixvoid.com/bin/nginx/nginx-1.11.10-linux-amd64
REDIS_BIN_LOC=https://cryo.unixvoid.com/bin/redis/3.2.6/redis-server
FULL_DOCKER_NAME=bitnuke:full

all: bitnuke

dependencies:
	go get github.com/gorilla/mux
	go get github.com/unixvoid/glogger
	go get gopkg.in/gcfg.v1
	go get gopkg.in/redis.v5
	go get golang.org/x/crypto/sha3

daemon:
	bin/bitnuke &

bitnuke:
	$(GOC) bitnuke.go

run:
	go run \
		bitnuke/bitnuke.go \
		bitnuke/dynamic_handler.go \
		bitnuke/link_compressor.go \
		bitnuke/remove.go \
		bitnuke/token_generator.go \
		bitnuke/upload.go

prep_aci: stat
	mkdir -p stage.tmp/bitnuke-layout/rootfs/
	cp bin/bitnuke* stage.tmp/bitnuke-layout/rootfs/bitnuke
	cp config.gcfg stage.tmp/bitnuke-layout/rootfs/
	cp deps/manifest.json stage.tmp/bitnuke-layout/manifest

build_aci: prep_aci
	# build image
	cd stage.tmp/ && \
		actool build bitnuke-layout bitnuke-api.aci && \
		mv bitnuke-api.aci ../
	@echo "bitnuke-api.aci built"

build_travis_aci: prep_aci
	wget https://github.com/appc/spec/releases/download/v0.8.7/appc-v0.8.7.tar.gz
	tar -zxf appc-v0.8.7.tar.gz
	# build image
	cd stage.tmp/ && \
		../appc-v0.8.7/actool build bitnuke-layout bitnuke-api.aci && \
		mv bitnuke-api.aci ../
	rm -rf appc-v0.8.7*
	@echo "bitnuke-api.aci built"

test: clean build_aci
	mkdir -p /tmp/redis
	mkdir -p /tmp/nginx/log
	$(OS_PERMS) rkt run \
		--port=web-http:8080 \
		--volume redis-data,kind=host,source=/tmp/redis \
		--volume nginx-data,kind=host,source=$(CWD)/deps/data/ \
		--volume nginx-conf,kind=host,source=$(CWD)/deps/conf/nginx.conf \
		--volume nginx-log,kind=host,source=/tmp/nginx/log \
		--volume nginx-mime,kind=host,source=$(CWD)/deps/conf/mime.types \
		unixvoid.com/redis \
			--mount volume=redis-data,target=/redisbak \
		unixvoid.com/nginx-1.13.11 \
			--mount volume=nginx-data,target=/data \
			--mount volume=nginx-conf,target=/nginx/nginx.conf \
			--mount volume=nginx-mime,target=/conf/mime.types \
			--mount volume=nginx-log,target=/nginx/log/ \
		./bitnuke-api.aci \
			--insecure-options=image

build-full: clean stat
	rm -rf stage.tmp/
	mkdir -p stage.tmp/
	cp deps/Dockerfile.full stage.tmp/Dockerfile
	cp bin/bitnuke* stage.tmp/bitnuke
	cp config.gcfg stage.tmp/
	cp deps/redis.conf stage.tmp/
	cp deps/run_all.sh stage.tmp/
	cd stage.tmp/ && \
		wget -O nginx $(NGINX_BIN_LOC) && \
		chmod +x nginx && \
		wget -O redis-server $(REDIS_BIN_LOC) && \
		chmod +x redis-server && \
		$(OS_PERMS) docker build -t $(FULL_DOCKER_NAME) .

run-full:
	$(OS_PERMS) docker run \
		-it \
		--name bitnuke-full \
		-v $(CWD)/deps/conf/nginx.conf:/nginx/nginx.conf \
		-v $(CWD)/deps/conf/mime.types:/conf/mime.types \
		-v $(CWD)/deps/data/:/data \
		-p 8080:80 \
		$(FULL_DOCKER_NAME)

stat:
	mkdir -p bin/
	$(CGOR) $(GOC) $(GOFLAGS) -o bin/bitnuke-$(GIT_HASH)-linux-amd64 bitnuke/*.go

install: stat
	cp bitnuke /usr/bin

clean:
	rm -rf bin/
	rm -rf stage.tmp/
	rm -f bitnuke-api.aci


text:
{% extends "core/base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}

Create an account

  {% if user.is_authenticated %}

Please logout before making a new account

  {% else %}
  <form action="{% url core.views.register %}" method="POST">
        {{ form.as_ul }}
        <input type="submit" value="Create the account">
        {% csrf_token %}
  </form>
  {% endif %}
{% endblock %}


text:
package chapter16;

import java.awt.event.*;
import javax.swing.JFrame;

public class AdapterDemo extends JFrame {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) {
		AdapterDemo frame = new AdapterDemo();
		frame.setLocationRelativeTo(null); // Center the frame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setTitle("AdapterDemo");
		frame.setSize(220, 80);
		frame.setVisible(true);
	}

	public AdapterDemo() {
		addWindowListener(new WindowAdapter() {
			public void windowActivated(WindowEvent event) {
				System.out.println("Window activated");
			}
		});
	}
}


text:
from urlparse import urlunparse

from devstack import component as comp
from devstack import date
from devstack import exceptions
from devstack import libvirt as virsh
from devstack import log as logging
from devstack import shell as sh
from devstack import utils

from devstack.components import db
from devstack.components import keystone
from devstack.components import rabbit

LOG = logging.getLogger('devstack.components.nova')

# Special generated conf
API_CONF = 'nova.conf'

# How we reference some config files (in applications)
CFG_FILE_OPT = '--config-file'

# Normal conf
PASTE_CONF = 'nova-api-paste.ini'
PASTE_SOURCE_FN = 'api-paste.ini'
POLICY_CONF = 'policy.json'
LOGGING_SOURCE_FN = 'logging_sample.conf'
LOGGING_CONF = "logging.conf"
CONFIGS = [PASTE_CONF, POLICY_CONF, LOGGING_CONF]
ADJUST_CONFIGS = [PASTE_CONF]

# This is a special conf
NET_INIT_CONF = 'nova-network-init.sh'
NET_INIT_CMD_ROOT = [sh.joinpths("/", "bin", 'bash')]

# This db will be dropped then created
DB_NAME = 'nova'

# This makes the database be in sync with nova
DB_SYNC_CMD = [
    {'cmd': ['%BIN_DIR%/nova-manage', CFG_FILE_OPT, '%CFGFILE%', 'db', 'sync']},
]

# These are used for nova volumes
VG_CHECK_CMD = [
    {'cmd': ['vgs', '%VOLUME_GROUP%'],
     'run_as_root': True}
]
VG_DEV_CMD = [
    {'cmd': ['losetup', '-f', '--show', '%VOLUME_BACKING_FILE%'],
     'run_as_root': True}
]
VG_CREATE_CMD = [
    {'cmd': ['vgcreate', '%VOLUME_GROUP%', '%DEV%'],
     'run_as_root': True}
]
VG_LVS_CMD = [
    {'cmd': ['lvs', '--noheadings', '-o', 'lv_name', '%VOLUME_GROUP%'],
     'run_as_root': True}
]
VG_LVREMOVE_CMD = [
    {'cmd': ['lvremove', '-f', '%VOLUME_GROUP%/%LV%'],
     'run_as_root': True}
]

# NCPU, NVOL, NAPI ... are here as possible subsystems of nova
NCPU = "cpu"
NVOL = "vol"
NAPI = "api"
NOBJ = "obj"
NNET = "net"
NCERT = "cert"
NSCHED = "sched"
NCAUTH = "cauth"
NXVNC = "xvnc"
SUBSYSTEMS = [NCPU, NVOL, NAPI,
    NOBJ, NNET, NCERT, NSCHED, NCAUTH, NXVNC]

# What to start
APP_OPTIONS = {
    #these are currently the core components/applications
    'nova-api': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-compute': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-volume': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-network': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-scheduler': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-cert': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-objectstore': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-consoleauth': [CFG_FILE_OPT, '%CFGFILE%'],
    'nova-xvpvncproxy': [CFG_FILE_OPT, '%CFGFILE%'],
}

# Sub component names to actual app names (matching previous dict)
SUB_COMPONENT_NAME_MAP = {
    NCPU: 'nova-compute',
    NVOL: 'nova-volume',
    NAPI: 'nova-api',
    NOBJ: 'nova-objectstore',
    NNET: 'nova-network',
    NCERT: 'nova-cert',
    NSCHED: 'nova-scheduler',
    NCAUTH: 'nova-consoleauth',
    NXVNC: 'nova-xvpvncproxy',
}

# Subdirs of the checkout/download
BIN_DIR = 'bin'
CONFIG_DIR = "etc"

# Network class/driver/manager templs
QUANTUM_MANAGER = 'nova.network.quantum.manager.QuantumManager'
QUANTUM_IPAM_LIB = 'nova.network.quantum.melange_ipam_lib'
NET_MANAGER_TEMPLATE = 'nova.network.manager.%s'
FIRE_MANAGER_TEMPLATE = 'nova.virt.libvirt.firewall.%s'

# Sensible defaults
DEF_IMAGE_SERVICE = 'nova.image.glance.GlanceImageService'
DEF_SCHEDULER = 'nova.scheduler.simple.SimpleScheduler'
DEF_GLANCE_PORT = 9292
DEF_GLANCE_SERVER = "%s" + ":%s" % (DEF_GLANCE_PORT)
DEF_INSTANCE_PREFIX = 'instance-'
DEF_INSTANCE_TEMPL = DEF_INSTANCE_PREFIX + '%08x'
DEF_FIREWALL_DRIVER = 'IptablesFirewallDriver'
DEF_FLAT_VIRT_BRIDGE = 'br100'
DEF_NET_MANAGER = 'FlatDHCPManager'
DEF_VOL_PREFIX = 'volume-'
DEF_VOL_TEMPL = DEF_VOL_PREFIX + '%08x'

# Default virt types
DEF_VIRT_DRIVER = 'libvirt'
DEF_VIRT_TYPE = 'qemu'

# Virt drivers map -> to there connection name
VIRT_DRIVER_CON_MAP = {
    'libvirt': 'libvirt',
    'xenserver': 'xenapi',
    'vmware': 'vmwareapi',
    'baremetal': 'baremetal',
}

# Only turned on if openvswitch enabled
QUANTUM_OPENSWITCH_OPS = {
    'libvirt_vif_type': 'ethernet',
    'libvirt_vif_driver': 'nova.virt.libvirt.vif.LibvirtOpenVswitchDriver',
    'linuxnet_interface_driver': 'nova.network.linux_net.LinuxOVSInterfaceDriver',
    'quantum_use_dhcp': True,
}

# This is a special conf
CLEANER_DATA_CONF = 'nova-clean.sh'
CLEANER_CMD_ROOT = [sh.joinpths("/", "bin", 'bash')]

# FIXME:
#rhel6/fedora libvirt policy
#http://wiki.libvirt.org/page/SSHPolicyKitSetup
#LIBVIRT_POLICY_FN = "/etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla"
#LIBVIRT_POLICY_CONTENTS = """
#[libvirt Management Access]
#Identity=unix-group:libvirtd
#Action=org.libvirt.unix.manage
#ResultAny=yes
#ResultInactive=yes
#ResultActive=yes
#"""

# Xenserver specific defaults
XS_DEF_INTERFACE = 'eth1'
XA_CONNECTION_ADDR = '169.254.0.1'
XS_VNC_ADDR = XA_CONNECTION_ADDR
XS_DEF_BRIDGE = 'xapi1'
XA_CONNECTION_PORT = 80
XA_DEF_USER = 'root'
XA_DEF_CONNECTION_URL = urlunparse(('http', "%s:%s" % (XA_CONNECTION_ADDR, XA_CONNECTION_PORT), "", '', '', ''))

# Vnc specific defaults
VNC_DEF_ADDR = '127.0.0.1'

# Nova std compute extensions
STD_COMPUTE_EXTS = 'nova.api.openstack.compute.contrib.standard_extensions'

# Config keys we warm up so u won't be prompted later
WARMUP_PWS = [('rabbit', rabbit.PW_USER_PROMPT)]

# Nova conf default section
NV_CONF_DEF_SECTION = "[DEFAULT]"

def _canon_virt_driver(virt_driver):
    if not virt_driver:
        return DEF_VIRT_DRIVER
    virt_driver = virt_driver.strip().lower()
    if not (virt_driver in VIRT_DRIVER_CON_MAP):
        return DEF_VIRT_DRIVER
    return virt_driver

def _canon_libvirt_type(virt_type):
    if not virt_type:
        return DEF_VIRT_TYPE
    virt_type = virt_type.lower().strip()
    if not (virt_type in virsh.LIBVIRT_PROTOCOL_MAP):
        return DEF_VIRT_TYPE
    else:
        return virt_type

class NovaUninstaller(comp.PythonUninstallComponent):
    def __init__(self, *args, **kargs):
        comp.PythonUninstallComponent.__init__(self, *args, **kargs)
        self.bin_dir = sh.joinpths(self.app_dir, BIN_DIR)
        self.cfg_dir = sh.joinpths(self.app_dir, CONFIG_DIR)

    def known_subsystems(self):
        return SUBSYSTEMS

    def pre_uninstall(self):
        self._clear_libvirt_domains()
        self._clean_it()

    def _clean_it(self):
        # These environment additions are important
        # in that they eventually affect how this script runs
        env = dict()
        env['ENABLED_SERVICES'] = ",".join(self.desired_subsystems)
        env['BIN_DIR'] = self.bin_dir
        env['VOLUME_NAME_PREFIX'] = self.cfg.getdefaulted('nova', 'volume_name_prefix', DEF_VOL_PREFIX)
        cleaner_fn = sh.joinpths(self.bin_dir, CLEANER_DATA_CONF)
        if sh.isfile(cleaner_fn):
            LOG.info("Cleaning up your system by running nova cleaner script [%s]." % (cleaner_fn))
            cmd = CLEANER_CMD_ROOT + [cleaner_fn]
            sh.execute(*cmd, run_as_root=True, env_overrides=env)

    def _clear_libvirt_domains(self):
        virt_driver = _canon_virt_driver(self.cfg.get('nova', 'virt_driver'))
        if virt_driver == 'libvirt':
            inst_prefix = self.cfg.getdefaulted('nova', 'instance_name_prefix', DEF_INSTANCE_PREFIX)
            libvirt_type = _canon_libvirt_type(self.cfg.get('nova', 'libvirt_type'))
            virsh.clear_libvirt_domains(self.distro, libvirt_type, inst_prefix)

class NovaInstaller(comp.PythonInstallComponent):
    def __init__(self, *args, **kargs):
        comp.PythonInstallComponent.__init__(self, *args, **kargs)
        self.bin_dir = sh.joinpths(self.app_dir, BIN_DIR)
        self.cfg_dir = sh.joinpths(self.app_dir, CONFIG_DIR)
        self.paste_conf_fn = self._get_target_config_name(PASTE_CONF)
        self.volumes_enabled = False
        if NVOL in self.desired_subsystems:
            self.volumes_enabled = True
        self.xvnc_enabled = False
        if NXVNC in self.desired_subsystems:
            self.xvnc_enabled = True

    def known_options(self):
        return set(['no-vnc', 'quantum', 'melange'])

    def known_subsystems(self):
        return SUBSYSTEMS

    def _get_symlinks(self):
        links = comp.PythonInstallComponent._get_symlinks(self)
        source_fn = sh.joinpths(self.cfg_dir, API_CONF)
        links[source_fn] = sh.joinpths(self._get_link_dir(), API_CONF)
        return links

    def _get_download_locations(self):
        places = list()
        places.append({
            'uri': ("git", "nova_repo"),
            'branch': ("git", "nova_branch"),
        })
        return places

    def warm_configs(self):
        warm_pws = list(WARMUP_PWS)
        driver_canon = _canon_virt_driver(self.cfg.get('nova', 'virt_driver'))
        if driver_canon == 'xenserver':
            warm_pws.append(('xenapi_connection', 'the Xen API connection'))
        for pw_key, pw_prompt in warm_pws:
            self.pw_gen.get_password(pw_key, pw_prompt)

    def _get_config_files(self):
        return list(CONFIGS)

    def _setup_network_initer(self):
        LOG.info("Configuring nova network initializer template %s.", NET_INIT_CONF)
        (_, contents) = utils.load_template(self.component_name, NET_INIT_CONF)
        params = self._get_param_map(NET_INIT_CONF)
        contents = utils.param_replace(contents, params, True)
        tgt_fn = sh.joinpths(self.bin_dir, NET_INIT_CONF)
        sh.write_file(tgt_fn, contents)
        sh.chmod(tgt_fn, 0755)
        self.tracewriter.file_touched(tgt_fn)

    def _sync_db(self):
        LOG.info("Syncing the database with nova.")
        mp = dict()
        mp['BIN_DIR'] = self.bin_dir
        mp['CFGFILE'] = sh.joinpths(self.cfg_dir, API_CONF)
        utils.execute_template(*DB_SYNC_CMD, params=mp)

    def post_install(self):
        comp.PythonInstallComponent.post_install(self)
        # Extra actions to do nova setup
        self._setup_db()
        self._sync_db()
        self._setup_cleaner()
        self._setup_network_initer()
        # Check if we need to do the vol subsystem
        if self.volumes_enabled:
            vol_maker = NovaVolumeConfigurator(self)
            vol_maker.setup_volumes()

    def _setup_cleaner(self):
        LOG.info("Configuring cleaner template %s.", CLEANER_DATA_CONF)
        (_, contents) = utils.load_template(self.component_name, CLEANER_DATA_CONF)
        tgt_fn = sh.joinpths(self.bin_dir, CLEANER_DATA_CONF)
        sh.write_file(tgt_fn, contents)
        sh.chmod(tgt_fn, 0755)
        self.tracewriter.file_touched(tgt_fn)

    def _setup_db(self):
        LOG.info("Fixing up database named %s.", DB_NAME)
        db.drop_db(self.cfg, self.pw_gen, self.distro, DB_NAME)
        db.create_db(self.cfg, self.pw_gen, self.distro, DB_NAME)

    def _generate_nova_conf(self):
        LOG.info("Generating dynamic content for nova configuration (%s)." % (API_CONF))
        conf_gen = NovaConfConfigurator(self)
        nova_conf_contents = conf_gen.configure()
        conf_fn = self._get_target_config_name(API_CONF)
        LOG.info("Writing nova configuration to %s" % (conf_fn))
        LOG.debug(nova_conf_contents)
        self.tracewriter.dirs_made(*sh.mkdirslist(sh.dirname(conf_fn)))
        self.tracewriter.cfg_file_written(sh.write_file(conf_fn, nova_conf_contents))

    def _get_source_config(self, config_fn):
        name = config_fn
        if config_fn == PASTE_CONF:
            # Return the paste api template
            return comp.PythonInstallComponent._get_source_config(self, PASTE_SOURCE_FN)
        elif config_fn == LOGGING_CONF:
            name = LOGGING_SOURCE_FN
        srcfn = sh.joinpths(self.cfg_dir, "nova", name)
        contents = sh.load_file(srcfn)
        return (srcfn, contents)

    def _get_param_map(self, config_fn):
        mp = dict()
        if config_fn == NET_INIT_CONF:
            mp['NOVA_DIR'] = self.app_dir
            mp['CFG_FILE'] = sh.joinpths(self.cfg_dir, API_CONF)
            mp['FLOATING_RANGE'] = self.cfg.getdefaulted('nova', 'floating_range', '172.24.4.224/28')
            mp['TEST_FLOATING_RANGE'] = self.cfg.getdefaulted('nova', 'test_floating_range', '192.168.253.0/29')
            mp['TEST_FLOATING_POOL'] = self.cfg.getdefaulted('nova', 'test_floating_pool', 'test')
            mp['FIXED_NETWORK_SIZE'] = self.cfg.getdefaulted('nova', 'fixed_network_size', '256')
            mp['FIXED_RANGE'] = self.cfg.getdefaulted('nova', 'fixed_range', '10.0.0.0/24')
        else:
            mp.update(keystone.get_shared_params(self.cfg, self.pw_gen, 'nova'))
        return mp

    def configure(self):
        configs_made = comp.PythonInstallComponent.configure(self)
        self._generate_nova_conf()
        configs_made += 1
        driver_canon = _canon_virt_driver(self.cfg.get('nova', 'virt_driver'))
        # TODO maybe move this??
        if  driver_canon == 'libvirt' and self.distro.get_command('virt-policy', quiet=True):
            (fn, contents) = self.distro.get_command('virt-policy')
            dirs_made = list()
            with sh.Rooted(True):
                dirs_made = sh.mkdirslist(sh.dirname(fn))
                sh.write_file(fn, contents)
            self.tracewriter.dirs_made(*dirs_made)
            self.tracewriter.cfg_file_written(fn)
            configs_made += 1
        return configs_made

class NovaRuntime(comp.PythonRuntime):
    def __init__(self, *args, **kargs):
        comp.PythonRuntime.__init__(self, *args, **kargs)
        self.cfg_dir = sh.joinpths(self.app_dir, CONFIG_DIR)
        self.bin_dir = sh.joinpths(self.app_dir, BIN_DIR)
        self.wait_time = max(self.cfg.getint('default', 'service_wait_seconds'), 1)

    def _setup_network_init(self):
        tgt_fn = sh.joinpths(self.bin_dir, NET_INIT_CONF)
        if sh.isfile(tgt_fn):
            LOG.info("Creating your nova network to be used with instances.")
            # If still there, run it
            # these environment additions are important
            # in that they eventually affect how this script runs
            if 'quantum' in self.options:
                LOG.info("Waiting %s seconds so that quantum can start up before running first time init." % (self.wait_time))
                sh.sleep(self.wait_time)
            env = dict()
            env['ENABLED_SERVICES'] = ",".join(self.instances.keys())
            setup_cmd = NET_INIT_CMD_ROOT + [tgt_fn]
            LOG.info("Running (%s) command to initialize nova's network." % (" ".join(setup_cmd)))
            sh.execute(*setup_cmd, env_overrides=env, run_as_root=False)
            LOG.debug("Removing (%s) file since we successfully initialized nova's network." % (tgt_fn))
            sh.unlink(tgt_fn)

    def post_start(self):
        self._setup_network_init()

    def known_options(self):
        return set(['quantum'])

    def known_subsystems(self):
        return SUBSYSTEMS

    def _get_apps_to_start(self):
        apps = list()
        for subsys in self.desired_subsystems:
            app = dict()
            app['name'] = SUB_COMPONENT_NAME_MAP[subsys]
            app['path'] = sh.joinpths(self.bin_dir, app['name'])
            apps.append(app)
        return apps

    def pre_start(self):
        # Let the parent class do its thing
        comp.PythonRuntime.pre_start(self)
        virt_driver = _canon_virt_driver(self.cfg.get('nova', 'virt_driver'))
        if virt_driver == 'libvirt':
            # FIXME: The configuration for the virtualization-type
            # should come from the persona.
            virt_type = _canon_libvirt_type(self.cfg.get('nova', 'libvirt_type'))
            LOG.info("Checking that your selected libvirt virtualization type [%s] is working and running." % (virt_type))
            if not virsh.virt_ok(virt_type, self.distro):
                msg = ("Libvirt type %s does not seem to be active or configured correctly, "
                       "perhaps you should be using %s instead." % (virt_type, DEF_VIRT_TYPE))
                raise exceptions.StartException(msg)
            virsh.restart(self.distro)

    def _get_param_map(self, app_name):
        params = comp.PythonRuntime._get_param_map(self, app_name)
        params['CFGFILE'] = sh.joinpths(self.cfg_dir, API_CONF)
        return params

    def _get_app_options(self, app):
        return APP_OPTIONS.get(app)

# This will configure nova volumes which in a developer box
# is a volume group (lvm) that are backed by a loopback file
class NovaVolumeConfigurator(object):
    def __init__(self, ni):
        self.cfg = ni.cfg
        self.app_dir = ni.app_dir
        self.distro = ni.distro

    def setup_volumes(self):
        self._setup_vol_groups()

    def _setup_vol_groups(self):
        LOG.info("Attempting to setup volume groups for nova volume management.")
        mp = dict()
        backing_file = self.cfg.getdefaulted('nova', 'volume_backing_file', sh.joinpths(self.app_dir, 'nova-volumes-backing-file'))
        vol_group = self.cfg.getdefaulted('nova', 'volume_group', 'nova-volumes')
        backing_file_size = utils.to_bytes(self.cfg.getdefaulted('nova', 'volume_backing_file_size', '2052M'))
        mp['VOLUME_GROUP'] = vol_group
        mp['VOLUME_BACKING_FILE'] = backing_file
        mp['VOLUME_BACKING_FILE_SIZE'] = backing_file_size
        try:
            utils.execute_template(*VG_CHECK_CMD, params=mp)
            LOG.warn("Volume group already exists: %s" % (vol_group))
        except exceptions.ProcessExecutionError as err:
            # Check that the error from VG_CHECK is an expected error
            if err.exit_code != 5:
                raise
            LOG.info("Need to create volume group: %s" % (vol_group))
            sh.touch_file(backing_file, die_if_there=False, file_size=backing_file_size)
            vg_dev_result = utils.execute_template(*VG_DEV_CMD, params=mp)
            if vg_dev_result and vg_dev_result[0]:
                LOG.debug("VG dev result: %s" % (vg_dev_result))
                # Strip the newlines out of the stdout (which is in the first
                # element of the first (and only) tuple in the response
                (sysout, _) = vg_dev_result[0]
                mp['DEV'] = sysout.replace('\n', '')
                utils.execute_template(*VG_CREATE_CMD, params=mp)
        # One way or another, we should have the volume group, Now check the
        # logical volumes
        self._process_lvs(mp)
        # Finish off by restarting tgt, and ignore any errors
        cmdrestart = self.distro.get_command('iscsi', 'restart', quiet=True)
        if cmdrestart:
            sh.execute(*cmdrestart, run_as_root=True, check_exit_code=False)

    def _process_lvs(self, mp):
        LOG.info("Attempting to setup logical volumes for nova volume management.")
        lvs_result = utils.execute_template(*VG_LVS_CMD, params=mp)
        if lvs_result and lvs_result[0]:
            LOG.debug("LVS result: %s" % (lvs_result))
            vol_name_prefix = self.cfg.getdefaulted('nova', 'volume_name_prefix', DEF_VOL_PREFIX)
            LOG.debug("Using volume name prefix: %s" % (vol_name_prefix))
            (sysout, _) = lvs_result[0]
            for stdout_line in sysout.split('\n'):
                stdout_line = stdout_line.strip()
                if stdout_line:
                    # Ignore blank lines
                    LOG.debug("Processing LVS output line: %s" % (stdout_line))
                    if stdout_line.startswith(vol_name_prefix):
                        # TODO still need to implement the following:
                        # tid=`egrep "^tid.+$lv" /proc/net/iet/volume | cut -f1 -d' ' | tr ':' '='`
                        # if [[ -n "$tid" ]]; then
                        #   lun=`egrep "lun.+$lv" /proc/net/iet/volume | cut -f1 -d' ' | tr ':' '=' | tr -d '\t'`
                        #   sudo ietadm --op delete --$tid --$lun
                        # fi
                        # sudo lvremove -f $VOLUME_GROUP/$lv
                        raise NotImplementedError("LVS magic not yet implemented!")
                    mp['LV'] = stdout_line
                    utils.execute_template(*VG_LVREMOVE_CMD, params=mp)

# This class has the smarts to build the configuration file based on
# various runtime values. A useful reference for figuring out this
# is at http://docs.openstack.org/diablo/openstack-compute/admin/content/ch_configuring-openstack-compute.html
class NovaConfConfigurator(object):
    def __init__(self, ni):
        self.cfg = ni.cfg
        self.pw_gen = ni.pw_gen
        self.instances = ni.instances
        self.component_dir = ni.component_dir
        self.app_dir = ni.app_dir
        self.tracewriter = ni.tracewriter
        self.paste_conf_fn = ni.paste_conf_fn
        self.distro = ni.distro
        self.cfg_dir = ni.cfg_dir
        self.xvnc_enabled = ni.xvnc_enabled
        self.volumes_enabled = ni.volumes_enabled
        self.options = ni.options
        self.novnc_enabled = 'no-vnc' in self.options

    def _getbool(self, name):
        return self.cfg.getboolean('nova', name)

    def _getstr(self, name, default=''):
        return self.cfg.getdefaulted('nova', name, default)

    def configure(self):
        # Everything built goes in here
        nova_conf = NovaConf()

        # Used more than once so we calculate it ahead of time
        hostip = self.cfg.get('host', 'ip')

        if self._getbool('verbose'):
            nova_conf.add('verbose', True)

        # Check if we have a logdir specified. If we do, we'll make
        # sure that it exists. We will *not* use tracewrite because we
        # don't want to lose the logs when we uninstall
        logdir = self._getstr('logdir')
        if logdir:
            full_logdir = sh.abspth(logdir)
            nova_conf.add('logdir', full_logdir)
            # Will need to be root to create it since it may be in /var/log
            if not sh.isdir(full_logdir):
                LOG.debug("Making sure that nova logdir exists at: %s" % full_logdir)
                with sh.Rooted(True):
                    sh.mkdir(full_logdir)
                    sh.chmod(full_logdir, 0777)

        # Allow the admin api?
        if self._getbool('allow_admin_api'):
            nova_conf.add('allow_admin_api', True)

        # FIXME: ??
        nova_conf.add('allow_resize_to_same_host', True)

        # Which scheduler do u want?
        nova_conf.add('compute_scheduler_driver', self._getstr('scheduler', DEF_SCHEDULER))

        # Setup any network settings
        self._configure_network_settings(nova_conf)

        # Setup nova volume settings
        if self.volumes_enabled:
            self._configure_vols(nova_conf)

        # The ip of where we are running
        nova_conf.add('my_ip', hostip)

        # Setup your sql connection
        db_dsn = db.fetch_dbdsn(self.cfg, self.pw_gen, DB_NAME)
        nova_conf.add('sql_connection', db_dsn)

        # Configure anything libvirt related?
        virt_driver = _canon_virt_driver(self._getstr('virt_driver'))
        if virt_driver == 'libvirt':
            libvirt_type = _canon_libvirt_type(self._getstr('libvirt_type'))
            self._configure_libvirt(libvirt_type, nova_conf)

        # How instances will be presented
        instance_template = self._getstr('instance_name_prefix') + self._getstr('instance_name_postfix')
        if not instance_template:
            instance_template = DEF_INSTANCE_TEMPL
        nova_conf.add('instance_name_template', instance_template)

        # Enable the standard extensions
        nova_conf.add('osapi_compute_extension', STD_COMPUTE_EXTS)

        # Auth will be using keystone
        nova_conf.add('auth_strategy', 'keystone')

        # Vnc settings setup
        self._configure_vnc(nova_conf)

        # Where our paste config is
        nova_conf.add('api_paste_config', self.paste_conf_fn)

        # What our imaging service will be
        self._configure_image_service(nova_conf, hostip)

        # Configs for ec2 / s3 stuff
        nova_conf.add('ec2_dmz_host', self._getstr('ec2_dmz_host', hostip))
        nova_conf.add('s3_host', hostip)

        # How is your rabbit setup?
        nova_conf.add('rabbit_host', self.cfg.getdefaulted('default', 'rabbit_host', hostip))
        nova_conf.add('rabbit_password', self.cfg.get("passwords", "rabbit"))

        # Where instances will be stored
        instances_path = self._getstr('instances_path', sh.joinpths(self.component_dir, 'instances'))
        self._configure_instances_path(instances_path, nova_conf)

        # Is this a multihost setup?
        self._configure_multihost(nova_conf)

        # Enable syslog??
        self._configure_syslog(nova_conf)

        # Handle any virt driver specifics
        self._configure_virt_driver(nova_conf)

        # Annnnnd extract to finish
        return self._get_content(nova_conf)

    def _get_extra(self, key):
        extras = self._getstr(key)
        cleaned_lines = list()
        extra_lines = extras.splitlines()
        for line in extra_lines:
            cleaned_line = line.strip()
            if len(cleaned_line):
                cleaned_lines.append(cleaned_line)
        return cleaned_lines

    def _convert_extra_flags(self, extra_flags):
        converted_flags = list()
        for f in extra_flags:
            cleaned_opt = f.lstrip("-")
            if len(cleaned_opt) == 0:
                continue
            if cleaned_opt.find("=") == -1:
                cleaned_opt += "=%s" % (True)
            converted_flags.append(cleaned_opt)
        return converted_flags

    def _get_content(self, nova_conf):
        generated_content = nova_conf.generate()
        extra_flags = self._get_extra('extra_flags')
        if extra_flags:
            LOG.warning("EXTRA_FLAGS is defined and may need to be converted to EXTRA_OPTS!")
            extra_flags = self._convert_extra_flags(extra_flags)
        extra_opts = self._get_extra('extra_opts')
        if extra_flags or extra_opts:
            new_contents = list()
            new_contents.append(generated_content)
            new_contents.append("")
            new_contents.append("# Extra flags")
            new_contents.append("")
            new_contents.extend(extra_flags)
            new_contents.append("")
            new_contents.append("# Extra options")
            new_contents.append("")
            new_contents.extend(extra_opts)
            new_contents.append("")
            generated_content = utils.joinlinesep(*new_contents)
        return generated_content

    def _configure_image_service(self, nova_conf, hostip):
        # What image service we will u be using sir?
        img_service = self._getstr('img_service', DEF_IMAGE_SERVICE)
        nova_conf.add('image_service', img_service)

        # If glance then where is it?
        if img_service.lower().find("glance") != -1:
            glance_api_server = self._getstr('glance_server', (DEF_GLANCE_SERVER % (hostip)))
            nova_conf.add('glance_api_servers', glance_api_server)

    def _configure_vnc(self, nova_conf):
        if self.novnc_enabled:
            nova_conf.add('novncproxy_base_url', self._getstr('vncproxy_url'))

        if self.xvnc_enabled:
            nova_conf.add('xvpvncproxy_base_url', self._getstr('xvpvncproxy_url'))

        nova_conf.add('vncserver_listen', self._getstr('vncserver_listen', VNC_DEF_ADDR))

        # If no vnc proxy address was specified,
        # pick a default based on which
        # driver we're using.
        vncserver_proxyclient_address = self._getstr('vncserver_proxyclient_address')
        if not vncserver_proxyclient_address:
            drive_canon = _canon_virt_driver(self._getstr('virt_driver'))
            if drive_canon == 'xenserver':
                vncserver_proxyclient_address = XS_VNC_ADDR
            else:
                vncserver_proxyclient_address = VNC_DEF_ADDR

        nova_conf.add('vncserver_proxyclient_address', vncserver_proxyclient_address)

    def _configure_vols(self, nova_conf):
        nova_conf.add('volume_group', self._getstr('volume_group'))
        vol_name_tpl = self._getstr('volume_name_prefix') + self._getstr('volume_name_postfix')
        if not vol_name_tpl:
            vol_name_tpl = DEF_VOL_TEMPL
        nova_conf.add('volume_name_template', vol_name_tpl)
        nova_conf.add('iscsi_helper', 'tgtadm')

    def _configure_network_settings(self, nova_conf):
        # TODO this might not be right....
        if 'quantum' in self.options:
            nova_conf.add('network_manager', QUANTUM_MANAGER)
            hostip = self.cfg.get('host', 'ip')
            nova_conf.add('quantum_connection_host', self.cfg.getdefaulted('quantum', 'q_host', hostip))
            nova_conf.add('quantum_connection_port', self.cfg.getdefaulted('quantum', 'q_port', '9696'))
            if self.cfg.get('quantum', 'q_plugin') == 'openvswitch':
                for (key, value) in QUANTUM_OPENSWITCH_OPS.items():
                    nova_conf.add(key, value)
            if 'melange' in self.options:
                nova_conf.add('quantum_ipam_lib', QUANTUM_IPAM_LIB)
                nova_conf.add('use_melange_mac_generation', True)
                nova_conf.add('melange_host', self.cfg.getdefaulted('melange', 'm_host', hostip))
                nova_conf.add('melange_port', self.cfg.getdefaulted('melange', 'm_port', '9898'))
        else:
            nova_conf.add('network_manager', NET_MANAGER_TEMPLATE % (self._getstr('network_manager', DEF_NET_MANAGER)))

        # Configs dhcp bridge stuff???
        # TODO: why is this the same as the nova.conf?
        nova_conf.add('dhcpbridge_flagfile', sh.joinpths(self.cfg_dir, API_CONF))

        # Network prefix for the IP network that all the projects for future VM guests reside on. Example: 192.168.0.0/12
        nova_conf.add('fixed_range', self._getstr('fixed_range'))

        # The value for vlan_interface may default to the the current value
        # of public_interface. We'll grab the value and keep it handy.
        public_interface = self._getstr('public_interface')
        vlan_interface = self._getstr('vlan_interface', public_interface)

        # Do a little check to make sure actually have that interface/s
        if not utils.is_interface(public_interface):
            msg = "Public interface %s is not a known interface" % (public_interface)
            raise exceptions.ConfigException(msg)

        if not utils.is_interface(vlan_interface):
            msg = "VLAN interface %s is not a known interface" % (vlan_interface)
            raise exceptions.ConfigException(msg)

        nova_conf.add('public_interface', public_interface)
        nova_conf.add('vlan_interface', vlan_interface)

        # This forces dnsmasq to update its leases table when an instance is terminated.
        nova_conf.add('force_dhcp_release', True)

    def _configure_syslog(self, nova_conf):
        if self.cfg.getboolean('default', 'syslog'):
            nova_conf.add('use_syslog', True)

    def _configure_multihost(self, nova_conf):
        if self._getbool('multi_host'):
            nova_conf.add('multi_host', True)
            nova_conf.add('send_arp_for_ha', True)

    def _configure_instances_path(self, instances_path, nova_conf):
        nova_conf.add('instances_path', instances_path)
        LOG.debug("Attempting to create instance directory: %s" % (instances_path))
        self.tracewriter.dirs_made(*sh.mkdirslist(instances_path))
        LOG.debug("Adjusting permissions of instance directory: %s" % (instances_path))
        sh.chmod(instances_path, 0777)

    def _configure_libvirt(self, virt_type, nova_conf):
        if virt_type == 'lxc':
            #TODO need to add some goodies here
            pass
        nova_conf.add('libvirt_type', virt_type)

    # Configures any virt driver settings
    def _configure_virt_driver(self, nova_conf):
        drive_canon = _canon_virt_driver(self._getstr('virt_driver'))
        nova_conf.add('connection_type', VIRT_DRIVER_CON_MAP.get(drive_canon, drive_canon))
        # Special driver settings
        if drive_canon == 'xenserver':
            nova_conf.add('xenapi_connection_url', self._getstr('xa_connection_url', XA_DEF_CONNECTION_URL))
            nova_conf.add('xenapi_connection_username', self._getstr('xa_connection_username', XA_DEF_USER))
            nova_conf.add('xenapi_connection_password', self.cfg.get("passwords", "xenapi_connection"))
            nova_conf.add('noflat_injected', True)
            xs_flat_ifc = self._getstr('xs_flat_interface', XS_DEF_INTERFACE)
            if not utils.is_interface(xs_flat_ifc):
                msg = "Xenserver flat interface %s is not a known interface" % (xs_flat_ifc)
                raise exceptions.ConfigException(msg)
            nova_conf.add('flat_interface', xs_flat_ifc)
            nova_conf.add('firewall_driver', FIRE_MANAGER_TEMPLATE % (self._getstr('xs_firewall_driver', DEF_FIREWALL_DRIVER)))
            nova_conf.add('flat_network_bridge', self._getstr('xs_flat_network_bridge', XS_DEF_BRIDGE))
        elif drive_canon == 'libvirt':
            nova_conf.add('firewall_driver', FIRE_MANAGER_TEMPLATE % (self._getstr('libvirt_firewall_driver', DEF_FIREWALL_DRIVER)))
            nova_conf.add('flat_network_bridge', self._getstr('flat_network_bridge', DEF_FLAT_VIRT_BRIDGE))
            flat_interface = self._getstr('flat_interface')
            if flat_interface:
                if not utils.is_interface(flat_interface):
                    msg = "Libvirt flat interface %s is not a known interface" % (flat_interface)
                    raise exceptions.ConfigException(msg)
                nova_conf.add('flat_interface', flat_interface)

# This class represents the data/format of the nova config file
class NovaConf(object):
    def __init__(self):
        self.lines = list()

    def add(self, key, value, *values):
        if not key:
            raise exceptions.BadParamException("Can not add a empty/none/false key")
        real_key = str(key)
        real_value = ""
        if len(values):
            str_values = [str(value)] + [str(v) for v in values]
            real_value = ",".join(str_values)
        else:
            real_value = str(value)
        self.lines.append({'key': real_key, 'value': real_value})
        LOG.debug("Added nova conf key %s with value [%s]" % (real_key, real_value))

    def _form_entry(self, key, value, params=None):
        real_value = utils.param_replace(str(value), params)
        entry = "%s=%s" % (key, real_value)
        return entry

    def _generate_header(self):
        lines = list()
        lines.append("# Generated on %s by (%s)" % (date.rcf8222date(), sh.getuser()))
        lines.append("")
        lines.append(NV_CONF_DEF_SECTION)
        lines.append("")
        return lines

    def _generate_footer(self):
        return list()

    def generate(self, param_dict=None):
        lines = list()
        lines.extend(self._generate_header())
        lines.extend(sorted(self._generate_lines(param_dict)))
        lines.extend(self._generate_footer())
        return utils.joinlinesep(*lines)

    def _generate_lines(self, params=None):
        lines = list()
        for line_entry in self.lines:
            key = line_entry.get('key')
            value = line_entry.get('value')
            lines.append(self._form_entry(key, value, params))
        return lines


text:
module.exports.getCurrentTimestampMs = function() {
	return (new Date().getTime());
}

module.exports.getCurrentTimestamp = function() {
	return module.exports.getCurrentTimestampMs() / 1000;
}

module.exports.stringToTimestampMs = function(str) {
	return (new Date(str).getTime())
}
module.exports.stringToTimestamp = function(str) {
	return module.exports.stringToTimestampMs(str) / 1000
}
module.exports.randomInt = function(min, max) {
	return Math.floor(Math.random() * (max - min)) + min
}

// Comparison functions for arrays and objects.

Array.prototype.equals = function (array) {
	// If the other array is a falsy value, return.
	if (!array) {
		return false
	}

	// Compare lengths - can save a lot of time.
	if (this.length != array.length) {
		return false
	}

	for (var i = 0, l=this.length; i < l; i++) {
		// Check if we have nested arrays.
		if (this[i] instanceof Array && array[i] instanceof Array) {
			// Recurse into the nested arrays.
			if (!this[i].equals(array[i])) {
				return false
			}
		} else if (this[i] != array[i]) {
			// Warning - two different object instances will never be equal: {x:20} != {x:20}.
			return false
		}
	}
	return true
}

Object.prototype.equals = function(object2) {
	// For the first loop, we only check for types.
	for (propName in this) {
		// Check for inherited methods and properties - like .equals itself
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
		// Return false if the return value is different.
		if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
			return false
		}
		// Check instance type
		else if (typeof this[propName] != typeof object2[propName]) {
			// Different types => not equal.
			return false
		}
	}
	// Now a deeper check using other objects property names.
	for (propName in object2) {
		// We must check instances anyway, there may be a property that only exists in object2.
		// I wonder, if remembering the checked values from the first loop would be faster or not.
		if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
			return false
		} else if (typeof this[propName] != typeof object2[propName]) {
			return false
		}
		// If the property is inherited, do not check any more (it must be equa if both objects inherit it).
		if (!this.hasOwnProperty(propName)) {
			continue;
		}

		// Now the detail check and recursion.

		// This returns the script back to the array comparing.
		/** REQUIRES Array.equals **/
		if (this[propName] instanceof Array && object2[propName] instanceof Array) {
			// Recurse into the nested arrays
			if (!this[propName].equals(object2[propName])) {
				return false;
			}
		} else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
			// Recurse into another objects.
			// console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
			if (!this[propName].equals(object2[propName])) {
				return false;
			}
		}
		//Normal value comparison for strings and numbers.
		else if(this[propName] != object2[propName]) {
			return false
		}
	}
	// If everything passed, let's say YES.
	return true
}


text:
package unquietcode.tools.closures;

import unquietcode.tools.closures.view.Closure1View;

/**
 * @author Benjamin Fagin
 * @version 01-23-2011
 */
public interface Closure1<Z, A> extends ClosureInterfaceBase<Z> {
	Z run(A p1);
	Closure1View<Z, A> getView();
	Class[] getArgumentTypes();
}


text:
<?xml version="1.0" encoding="UTF-8"?>

	<list key="installedFeatures">
	</list>

		<item value="172" key="DIALOG_Y_ORIGIN"/>
		<item value="200" key="DIALOG_X_ORIGIN"/>

		<item value="false" key="WizardProjectsImportPage.STORE_ARCHIVE_SELECTED"/>
		<item value="false" key="WizardProjectsImportPage.STORE_COPY_PROJECT_ID"/>
		<item value="false" key="WizardProjectsImportPage.STORE_NESTED_PROJECTS"/>
		<list key="WizardProjectsImportPage.STORE_DIRECTORIES">
			<item value="/home/training/Desktop/sarah-development/map-reduce/sample"/>
		</list>
		<list key="WizardProjectsImportPage.STORE_ARCHIVES">
			<item value=""/>
		</list>

		<list key="ENABLED_TRANSFERS">
		</list>


text:
var app = angular.module('MyTutorialApp',[]);

app.service('dataService', function($http) {
    this.getData = function(callbackFunc) {
        return $http({
            method: 'GET',
            url: '/',
        })
    }
}).controller("MainController", function($scope, dataService){

}).directive('nameGoesHere', function() {
    return {
    };
});/**
 * Created by Ravioli on 1/13/2017.
 */


text:
"""
next dashboard.py
author: Lalit Jain, lalitkumarj@gmail.com
last updated: 9/16/15

Flask controller for dashboards.
"""
import os
import json
import yaml
from flask import Blueprint, render_template, url_for, request, jsonify
from jinja2 import Environment, PackageLoader, ChoiceLoader
import requests

import next.broker.broker
import next.constants as constants
import next.database_client.PermStore as PermStore
from next.api.resource_manager import ResourceManager
import next.api.api_util as api_util

# Declare this as the dashboard blueprint
dashboard = Blueprint('dashboard',
                      __name__,
                      template_folder='templates',
                      static_folder='static')

rm = ResourceManager()
db = PermStore.PermStore()
broker = next.broker.broker.JobBroker()

import next.apps.Butler as Butler
Butler = Butler.Butler

# add database commands
dashboard_interface = api_util.NextBackendApi(dashboard)
from next.dashboard.database import DatabaseBackup, DatabaseRestore
dashboard_interface.add_resource(DatabaseBackup,'/database/databasebackup', endpoint='databasebackup')
dashboard_interface.add_resource(DatabaseRestore,'/database/databaserestore', endpoint='databaserestore')

@dashboard.route('/experiment_list')
def experiment_list():
    """
    Endpoint that renders a page with a simple list of all experiments.
    """
    # Experiments set
    experiments = []
    for app_id in rm.get_app_ids():
        for exp_uid in rm.get_app_exp_uids(app_id):
            start_date = rm.get_app_exp_uid_start_date(exp_uid)
            try:
                experiments.append({'exp_uid': exp_uid,
                                    'app_id': app_id,
                                    'start_date': start_date,
                                    'num_participants':len(rm.get_participant_uids(exp_uid)),
                                    })
            except IndexError as e:
                print e
                pass

    host_url = 'http://{}:{}'.format(constants.NEXT_BACKEND_GLOBAL_HOST,
                                     constants.NEXT_BACKEND_GLOBAL_PORT)
    if constants.SITE_KEY:
        dashboard_url='{}/dashboard/{}'.format(host_url, constants.SITE_KEY)
    else:
        dashboard_url='{}/dashboard'.format(host_url)

    return render_template('experiment_list.html',
                           dashboard_url=dashboard_url,
                           experiments = reversed(experiments))

@dashboard.route('/get_stats', methods=['POST'])
def get_stats():
    args_dict = request.json
    exp_uid = args_dict['exp_uid']
    app_id = rm.get_app_id(exp_uid)

    response_json,didSucceed,message = broker.dashboardAsync(app_id,exp_uid,args_dict)
    response_dict = json.loads(response_json,parse_float=lambda o:round(float(o),4))
    response_json = json.dumps(response_dict)
    return response_json

@dashboard.route('/system_monitor')
def system_monitor():
    """
    Endpoint that renders a page with a simple list of all monitoring.
    """
    host_url = 'http://{}:{}'.format(constants.NEXT_BACKEND_GLOBAL_HOST,
                                     constants.NEXT_BACKEND_GLOBAL_PORT)
    if constants.SITE_KEY:
        dashboard_url='{}/dashboard/{}'.format(host_url, constants.SITE_KEY)
    else:
        dashboard_url='{}/dashboard'.format(host_url)

    rabbit_url = 'http://{}:{}'.format(constants.NEXT_BACKEND_GLOBAL_HOST,
                                       15672)
    cadvisor_url = 'http://{}:{}'.format(constants.NEXT_BACKEND_GLOBAL_HOST,
                                         8888)
    mongodb_url = 'http://{}:{}'.format(constants.NEXT_BACKEND_GLOBAL_HOST,
                                        28017)
    return render_template('system_monitor.html',
                           dashboard_url=dashboard_url,
                           rabbit_url=rabbit_url,
                           cadvisor_url=cadvisor_url,
                           mongodb_url=mongodb_url)

@dashboard.route('/experiment_dashboard/<exp_uid>/<app_id>')
def experiment_dashboard(exp_uid, app_id):
    """
    Endpoint that renders the experiment dashboard.

    Inputs: ::\n
    	(string) exp_uid, exp_uid for a current experiment.
    """
    simple_flag = int(request.args.get('simple',0))
    force_recompute = int(request.args.get('force_recompute',1))

    # Not a particularly good way to do this.
    alg_label_list = rm.get_algs_for_exp_uid(exp_uid)
    alg_list = [{'alg_label':alg['alg_label'],
                 'alg_label_clean':'_'.join(alg['alg_label'].split())}
                for alg in alg_label_list]

    host_url = 'http://{}:{}'.format(constants.NEXT_BACKEND_GLOBAL_HOST,
                                     constants.NEXT_BACKEND_GLOBAL_PORT)
    if constants.SITE_KEY:
        dashboard_url='{}/dashboard/{}'.format(host_url, constants.SITE_KEY)
    else:
        dashboard_url='{}/dashboard'.format(host_url)

    env = Environment(loader=ChoiceLoader([PackageLoader('apps.{}'.format(app_id),
                                                         'dashboard'),
                                           PackageLoader('next.dashboard',
                                                         'templates')]))
    template = env.get_template('{}.html'.format(app_id)) # looks for /next/apps/{{ app_id }}/dashboard/{{ app_id }}.html
    return template.render(app_id=app_id,
                           exp_uid=exp_uid,
                           alg_list=alg_list,
                           host_url=host_url,
                           dashboard_url=dashboard_url,
                           exceptions_present=exceptions_present(exp_uid, host_url),
                           url_for=url_for,
                           simple_flag=int(simple_flag),
                           force_recompute=int(force_recompute))

def exceptions_present(exp_uid, host_url):
    url = '{}/api/experiment/{}/logs/APP-EXCEPTION'.format(host_url, exp_uid)
    r = requests.get(url)
    logs = yaml.load(r.content)['log_data']
    return True if len(logs) > 0 else False


text:
angular.module('starter.services', [])

.factory('Chats', function ($http) {
    function getData(callback) {
        $http.get('https://flashpay.herokuapp.com/getPayments')
            .success(callback);
    }

    return {
        all: getData,
        remove: function (chat) {
            chats.splice(chats.indexOf(chat), 1);
        },
        get: function (chatId) {
            for (var i = 0; i < chats.length; i++) {
                if (chats[i].id === parseInt(chatId)) {
                    return chats[i];
                }
            }
            return null;
        }
    };
});


text:
require 'spec_helper'

require 'httpadapter/adapters/mock'
require 'addressable/uri'
require 'addressable/template'

require 'xrd'

describe XRD::ResourceDescriptor do
  describe 'with an initialized resource descriptor' do
    before do
      @xrd = XRD::ResourceDescriptor.new
    end

    it 'should allow expiration dates to be set to Time objects' do
      now = Time.now
      @xrd.expires = now
      @xrd.expires.should == now
    end

    it 'should allow expiration dates to be set to String objects' do
      now = Time.now
      @xrd.expires = now.to_s
      @xrd.expires.to_s.should == now.to_s
    end

    it 'should allow subject values to be set to URI objects' do
      @xrd.subject = Addressable::URI.parse('http://example.com/subject')
      @xrd.subject.should == Addressable::URI.parse(
        'http://example.com/subject'
      )
    end

    it 'should allow subject values to be set to String objects' do
      @xrd.subject = 'http://example.com/subject'
      @xrd.subject.should == Addressable::URI.parse(
        'http://example.com/subject'
      )
    end

    it 'should not allow direct access to the property_keys' do
      (lambda do
        @xrd.property_keys
      end).should raise_error(NoMethodError)
      (lambda do
        @xrd.property_keys = []
      end).should raise_error(NoMethodError)
    end

    it 'should not allow direct access to the property_values' do
      (lambda do
        @xrd.property_values
      end).should raise_error(NoMethodError)
      (lambda do
        @xrd.property_values = []
      end).should raise_error(NoMethodError)
    end

    it 'should be inspectable' do
      @xrd.inspect.should be_kind_of(String)
    end
  end

  describe 'when attempting to parse an empty XRD document' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
</XRD>
      XML
      @xrd = XRD::ResourceDescriptor.parse(@xml)
    end

    it 'should return a blank resource descriptor' do
      @xrd.xml_id.should == nil
      @xrd.expires.should == nil
      @xrd.subject.should == nil
      @xrd.aliases.should == []
      @xrd.properties.should == []
      @xrd.links.should == []
    end
  end

  describe 'when attempting to parse an XRD document with an id' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0" xml:id="identifier">
</XRD>
      XML
      @xrd = XRD::ResourceDescriptor.parse(@xml)
    end

    it 'should return the correct id' do
      @xrd.xml_id.should == "identifier"
    end
  end

  describe 'when attempting to parse an XRD document with an Expires value' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
  <Expires>1970-01-01T00:00:00Z</Expires>
</XRD>
      XML
      @xrd = XRD::ResourceDescriptor.parse(@xml)
    end

    it 'should return the correct expiration date' do
      @xrd.expires.should == Time.gm(1970)
    end
  end

  describe 'when attempting to parse an XRD document with a Subject value' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
  <Subject>http://example.com/subject</Expires>
</XRD>
      XML
      @xrd = XRD::ResourceDescriptor.parse(@xml)
    end

    it 'should return the correct subject' do
      @xrd.subject.to_str.should == 'http://example.com/subject'
    end

    it 'should return a parsed subject URI' do
      @xrd.subject.should be_kind_of(Addressable::URI)
    end

    it 'should be inspectable' do
      @xrd.inspect.should be_kind_of(String)
      @xrd.inspect.should include('http://example.com/subject')
    end
  end

  describe 'when attempting to parse an XRD document with Alias values' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
  <Alias>http://people.example.com/subject</Alias>
  <Alias>acct:subject@example.com</Alias>
</XRD>
      XML
      @xrd = XRD::ResourceDescriptor.parse(@xml)
    end

    it 'should return the correct aliases' do
      (@xrd.aliases.map { |a| a.to_str }).should include(
        'http://people.example.com/subject'
      )
      (@xrd.aliases.map { |a| a.to_str }).should include(
        'acct:subject@example.com'
      )
    end

    it 'should return parsed alias URIs' do
      @xrd.aliases.each do |a|
        a.should be_kind_of(Addressable::URI)
      end
    end
  end

  describe 'when attempting to parse an XRD document with Property values' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
  <Property type="http://spec.example.net/version">1.0</Property>
  <Property type="http://spec.example.net/version">2.0</Property>
</XRD>
      XML
      @xrd = XRD::ResourceDescriptor.parse(@xml)
    end

    it 'should return the correct properties' do
      (@xrd.properties.map { |k, v| [k.to_str, v] }).should include(
        ['http://spec.example.net/version', '1.0']
      )
      (@xrd.properties.map { |k, v| [k.to_str, v] }).should include(
        ['http://spec.example.net/version', '2.0']
      )
    end

    it 'should return parsed property key URIs' do
      @xrd.properties.each do |k, v|
        k.should be_kind_of(Addressable::URI)
        v.should be_kind_of(String)
      end
    end
  end

  shared_examples_for 'simple XRD example' do
    it 'should return the correct expiration date' do
      @xrd.expires.should == Time.gm(1970)
    end

    it 'should return the correct subject' do
      @xrd.subject.to_str.should == 'http://example.com/subject'
    end

    it 'should return a parsed subject URI' do
      @xrd.subject.should be_kind_of(Addressable::URI)
    end

    it 'should return the correct properties' do
      (@xrd.properties.map { |k, v| [k.to_str, v] }).should include(
        ['http://spec.example.net/type/person', nil]
      )
    end

    it 'should return parsed property key URIs' do
      @xrd.properties.each do |k, v|
        k.should be_kind_of(Addressable::URI)
        v.should be_kind_of(NilClass)
      end
    end

    it 'should return the correct links' do
      @xrd.links[0].rel.should == 'http://spec.example.net/auth/1.0'
      @xrd.links[0].href.should == 'http://services.example.com/auth'
      @xrd.links[1].rel.should == 'http://spec.example.net/photo/1.0'
      @xrd.links[1].media_type.should == 'image/jpeg'
      @xrd.links[1].href.should == 'http://photos.example.com/gpburdell.jpg'
    end

    it 'should return the correct link titles' do
      @xrd.links[1].title.should == 'User Photo'
      @xrd.links[1].title('en').should == 'User Photo'
      @xrd.links[1].title('de').should == 'Benutzerfoto'

      @xrd.links[1].title.lang.should == 'en'
      @xrd.links[1].title('en').lang.should == 'en'
      @xrd.links[1].title('de').lang.should == 'de'
    end

    it 'should return the correct link properties' do
      @xrd.links[1].properties[0][0].should ===
        'http://spec.example.net/created/1.0'
      @xrd.links[1].properties[0][1].should == '1970-01-01'
    end

    it 'should allow links to be queried by rel value' do
      links = @xrd.links(:rel => 'http://spec.example.net/auth/1.0')
      links.length.should == 1
      links[0].rel.should == 'http://spec.example.net/auth/1.0'
    end

    it 'should allow links to be queried by rel value' do
      links = @xrd.links(:rel => 'alternate')
      links.length.should == 0
    end

    it 'should allow links to be queried by media type' do
      links = @xrd.links(:media_type => 'image/jpeg')
      links.length.should == 1
      links[0].media_type.should == 'image/jpeg'
    end

    it 'should allow links to be queried by media type' do
      links = @xrd.links(:media_type => 'text/html')
      links.length.should == 0
    end

    it 'should allow links to be queried by media type' do
      links = @xrd.links(:media_type => 'image')
      links.length.should == 1
      links[0].media_type.should == 'image/jpeg'
    end

    it 'should allow links to be queried by media type' do
      links = @xrd.links(:media_type => 'text')
      links.length.should == 0
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(:href => 'http://services.example.com/auth')
      links.length.should == 1
      links[0].href.should == 'http://services.example.com/auth'
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(:href => 'http://www.example.org/')
      links.length.should == 0
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(
        :href => Addressable::URI.parse('http://services.example.com/auth')
      )
      links.length.should == 1
      links[0].href.should == 'http://services.example.com/auth'
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(
        :href => Addressable::URI.parse('http://www.example.org/')
      )
      links.length.should == 0
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(:href => /services\.example\.com/)
      links.length.should == 1
      links[0].href.should == 'http://services.example.com/auth'
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(:href => /www\.example\.org/)
      links.length.should == 0
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(
        :href => Addressable::Template.new('http://{sub}.example.com/{path}')
      )
      links.length.should == 2
      links[0].href.should == 'http://services.example.com/auth'
      links[1].href.should == 'http://photos.example.com/gpburdell.jpg'
    end

    it 'should allow links to be queried by href' do
      links = @xrd.links(
        :href => Addressable::Template.new('http://www.example.org/{path}')
      )
      links.length.should == 0
    end
  end

  describe 'when attempting to fetch and parse an XRD document' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Expires>1970-01-01T00:00:00Z</Expires>
  <Subject>http://example.com/subject</Subject>
  <Property type="http://spec.example.net/type/person" xsi:nil="true" />
  <Link rel="http://spec.example.net/auth/1.0"
    href="http://services.example.com/auth" />
  <Link rel="http://spec.example.net/photo/1.0" type="image/jpeg"
    href="http://photos.example.com/gpburdell.jpg">
    <Title xml:lang="en">User Photo</Title>
    <Title xml:lang="de">Benutzerfoto</Title>
    <Property type="http://spec.example.net/created/1.0">1970-01-01</Property>
  </Link>
</XRD>
      XML
      @adapter = HTTPAdapter::MockAdapter.request_adapter do |request, conn|
        [
          200,
          [['Content-Type', 'application/xrd+xml']],
          [@xml],
        ]
      end
      @xrd = XRD::ResourceDescriptor.fetch_and_parse(
        'http://example.com/xrd', @adapter
      )
    end

    it_should_behave_like 'simple XRD example'
  end

  describe 'when attempting to fetch and parse an XRD document' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Expires>1970-01-01T00:00:00Z</Expires>
  <Subject>http://example.com/subject</Subject>
  <Property type="http://spec.example.net/type/person" xsi:nil="true" />
  <Link rel="http://spec.example.net/auth/1.0"
    href="http://services.example.com/auth" />
  <Link rel="http://spec.example.net/photo/1.0" type="image/jpeg"
    href="http://photos.example.com/gpburdell.jpg">
    <Title xml:lang="en">User Photo</Title>
    <Title xml:lang="de">Benutzerfoto</Title>
    <Property type="http://spec.example.net/created/1.0">1970-01-01</Property>
  </Link>
</XRD>
      XML
      @adapter = HTTPAdapter::MockAdapter.request_adapter do |request, conn|
        [
          200,
          [['Content-Type', 'application/xrd+xml']],
          [@xml],
        ]
      end
      @xrd = XRD.fetch_and_parse('http://example.com/xrd', @adapter)
    end

    it_should_behave_like 'simple XRD example'
  end

  describe 'when attempting to parse an XRD document with no title lang' do
    before do
      @xml = <<-XML
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Link rel="http://spec.example.net/photo/1.0" type="image/jpeg"
    href="http://photos.example.com/gpburdell.jpg">
    <Title>User Photo</Title>
    <Title xml:lang="de">Benutzerfoto</Title>
  </Link>
</XRD>
      XML
      @xrd = XRD.parse(@xml)
    end

    it 'should return the correct link titles' do
      @xrd.links[0].title.should == 'User Photo'
      @xrd.links[0].title('en').should == 'User Photo'
      @xrd.links[0].title('de').should == 'Benutzerfoto'

      @xrd.links[0].title.lang.should == nil
      @xrd.links[0].title('en').lang.should == nil
      @xrd.links[0].title('de').lang.should == 'de'
    end
  end
end