text:
///////////////////////////////////////////////////////////////
// This is generated code.
//////////////////////////////////////////////////////////////
// Code is generated using LLBLGen Pro version: 4.1
// Code is generated on:
// Code is generated using templates: SD.TemplateBindings.SharedTemplates
// Templates vendor: Solutions Design.
// Templates version:
//////////////////////////////////////////////////////////////
using System;
using System.ComponentModel;
using System.Collections.Generic;
#if !CF
using System.Runtime.Serialization;
#endif
using System.Xml.Serialization;
using AdventureWorks.Dal.Adapter.v41;
using AdventureWorks.Dal.Adapter.v41.HelperClasses;
using AdventureWorks.Dal.Adapter.v41.FactoryClasses;
using AdventureWorks.Dal.Adapter.v41.RelationClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;

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

	[Serializable]
	public partial class CreditCardEntity : CommonEntityBase
		// __LLBLGENPRO_USER_CODE_REGION_START AdditionalInterfaces
		// __LLBLGENPRO_USER_CODE_REGION_END
	{
		#region Class Member Declarations
		private EntityCollection<ContactCreditCardEntity> _contactCreditCards;
		private EntityCollection<SalesOrderHeaderEntity> _salesOrderHeaders;

		// __LLBLGENPRO_USER_CODE_REGION_START PrivateMembers
		// __LLBLGENPRO_USER_CODE_REGION_END
		#endregion

		#region Statics
		private static Dictionary<string, string>	_customProperties;
		private static Dictionary<string, Dictionary<string, string>>	_fieldsCustomProperties;

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

		///  Static CTor for setting up custom property hashtables. Is executed before the first instance of this entity class or derived classes is constructed.
		static CreditCardEntity()
		{
			SetupCustomPropertyHashtables();
		}

		///  CTor
		public CreditCardEntity():base("CreditCardEntity")
		{
			InitClassEmpty(null, null);
		}

		///  CTor
		/// <remarks>For framework usage.</remarks>
		/// <param name="fields">Fields object to set as the fields for this entity.</param>
		public CreditCardEntity(IEntityFields2 fields):base("CreditCardEntity")
		{
			InitClassEmpty(null, fields);
		}

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

		///  CTor
		/// <param name="creditCardId">PK value for CreditCard which data should be fetched into this CreditCard object</param>
		/// <remarks>The entity is not fetched by this constructor. Use a DataAccessAdapter for that.</remarks>
		public CreditCardEntity(System.Int32 creditCardId):base("CreditCardEntity")
		{
			InitClassEmpty(null, null);
			this.CreditCardId = creditCardId;
		}

		///  CTor
		/// <param name="creditCardId">PK value for CreditCard which data should be fetched into this CreditCard object</param>
		/// <param name="validator">The custom validator object for this CreditCardEntity</param>
		/// <remarks>The entity is not fetched by this constructor. Use a DataAccessAdapter for that.</remarks>
		public CreditCardEntity(System.Int32 creditCardId, IValidator validator):base("CreditCardEntity")
		{
			InitClassEmpty(validator, null);
			this.CreditCardId = creditCardId;
		}

		///  Protected CTor for deserialization
		/// <param name="info"></param>
		/// <param name="context"></param>
		[EditorBrowsable(EditorBrowsableState.Never)]
		protected CreditCardEntity(SerializationInfo info, StreamingContext context) : base(info, context)
		{
			if(SerializationHelper.Optimization != SerializationOptimization.Fast)
			{
				_contactCreditCards = (EntityCollection<ContactCreditCardEntity>)info.GetValue("_contactCreditCards", typeof(EntityCollection<ContactCreditCardEntity>));
				_salesOrderHeaders = (EntityCollection<SalesOrderHeaderEntity>)info.GetValue("_salesOrderHeaders", typeof(EntityCollection<SalesOrderHeaderEntity>));
				this.FixupDeserialization(FieldInfoProviderSingleton.GetInstance());
			}
			// __LLBLGENPRO_USER_CODE_REGION_START DeserializationConstructor
			// __LLBLGENPRO_USER_CODE_REGION_END
		}

		///  Sets the related entity property to the entity specified. If the property is a collection, it will add the entity specified to that collection.
		/// <param name="propertyName">Name of the property.</param>
		/// <param name="entity">Entity to set as an related entity</param>
		/// <remarks>Used by prefetch path logic.</remarks>
		protected override void SetRelatedEntityProperty(string propertyName, IEntityCore entity)
		{
			switch(propertyName)
			{
				case "ContactCreditCards":
					this.ContactCreditCards.Add((ContactCreditCardEntity)entity);
					break;
				case "SalesOrderHeaders":
					this.SalesOrderHeaders.Add((SalesOrderHeaderEntity)entity);
					break;
				default:
					this.OnSetRelatedEntityProperty(propertyName, entity);
					break;
			}
		}

		/// Gets the relation objects which represent the relation the fieldName specified is mapped on.
		/// <param name="fieldName">Name of the field mapped onto the relation of which the relation objects have to be obtained.</param>
		/// <returns>RelationCollection with relation object(s) which represent the relation the field is maped on</returns>
		protected override RelationCollection GetRelationsForFieldOfType(string fieldName)
		{
			return GetRelationsForField(fieldName);
		}

		/// Gets the relation objects which represent the relation the fieldName specified is mapped on.
		/// <param name="fieldName">Name of the field mapped onto the relation of which the relation objects have to be obtained.</param>
		/// <returns>RelationCollection with relation object(s) which represent the relation the field is maped on</returns>
		internal static RelationCollection GetRelationsForField(string fieldName)
		{
			RelationCollection toReturn = new RelationCollection();
			switch(fieldName)
			{
				case "ContactCreditCards":
					toReturn.Add(Relations.ContactCreditCardEntityUsingCreditCardId);
					break;
				case "SalesOrderHeaders":
					toReturn.Add(Relations.SalesOrderHeaderEntityUsingCreditCardId);
					break;
				default:
					break;
			}
			return toReturn;
		}
#if !CF
		/// Checks if the relation mapped by the property with the name specified is a one way / single sided relation. If the passed in name is null, it/ will return true if the entity has any single-sided relation
		/// <param name="propertyName">Name of the property which is mapped onto the relation to check, or null to check if the entity has any relation/ which is single sided</param>
		/// <returns>true if the relation is single sided / one way (so the opposite relation isn't present), false otherwise</returns>
		protected override bool CheckOneWayRelations(string propertyName)
		{
			int numberOfOneWayRelations = 0;
			switch(propertyName)
			{
				case null:
					return ((numberOfOneWayRelations > 0) || base.CheckOneWayRelations(null));
				default:
					return base.CheckOneWayRelations(propertyName);
			}
		}
#endif
		///  Sets the internal parameter related to the fieldname passed to the instance relatedEntity.
		/// <param name="relatedEntity">Instance to set as the related entity of type entityType</param>
		/// <param name="fieldName">Name of field mapped onto the relation which resolves in the instance relatedEntity</param>
		protected override void SetRelatedEntity(IEntityCore relatedEntity, string fieldName)
		{
			switch(fieldName)
			{
				case "ContactCreditCards":
					this.ContactCreditCards.Add((ContactCreditCardEntity)relatedEntity);
					break;
				case "SalesOrderHeaders":
					this.SalesOrderHeaders.Add((SalesOrderHeaderEntity)relatedEntity);
					break;
				default:
					break;
			}
		}

		///  Unsets the internal parameter related to the fieldname passed to the instance relatedEntity. Reverses the actions taken by SetRelatedEntity()
		/// <param name="relatedEntity">Instance to unset as the related entity of type entityType</param>
		/// <param name="fieldName">Name of field mapped onto the relation which resolves in the instance relatedEntity</param>
		/// <param name="signalRelatedEntityManyToOne">if set to true it will notify the manytoone side, if applicable.</param>
		protected override void UnsetRelatedEntity(IEntityCore relatedEntity, string fieldName, bool signalRelatedEntityManyToOne)
		{
			switch(fieldName)
			{
				case "ContactCreditCards":
					this.PerformRelatedEntityRemoval(this.ContactCreditCards, relatedEntity, signalRelatedEntityManyToOne);
					break;
				case "SalesOrderHeaders":
					this.PerformRelatedEntityRemoval(this.SalesOrderHeaders, relatedEntity, signalRelatedEntityManyToOne);
					break;
				default:
					break;
			}
		}

		///  Gets a collection of related entities referenced by this entity which depend on this entity (this entity is the PK side of their FK fields). These entities will have to be persisted after this entity during a recursive save.
		/// <returns>Collection with 0 or more IEntity2 objects, referenced by this entity</returns>
		protected override List<IEntity2> GetDependingRelatedEntities()
		{
			List<IEntity2> toReturn = new List<IEntity2>();
			return toReturn;
		}

		///  Gets a collection of related entities referenced by this entity which this entity depends on (this entity is the FK side of their PK fields). These
		/// entities will have to be persisted before this entity during a recursive save.
		/// <returns>Collection with 0 or more IEntity2 objects, referenced by this entity</returns>
		protected override List<IEntity2> GetDependentRelatedEntities()
		{
			List<IEntity2> toReturn = new List<IEntity2>();
			return toReturn;
		}

		/// Gets a list of all entity collections stored as member variables in this entity. Only 1:n related collections are returned.
		/// <returns>Collection with 0 or more IEntityCollection2 objects, referenced by this entity</returns>
		protected override List<IEntityCollection2> GetMemberEntityCollections()
		{
			List<IEntityCollection2> toReturn = new List<IEntityCollection2>();
			toReturn.Add(this.ContactCreditCards);
			toReturn.Add(this.SalesOrderHeaders);
			return toReturn;
		}

		/// ISerializable member. Does custom serialization so event handlers do not get serialized. Serializes members of this entity class and uses the base class' implementation to serialize the rest.
		/// <param name="info"></param>
		/// <param name="context"></param>
		[EditorBrowsable(EditorBrowsableState.Never)]
		protected override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (SerializationHelper.Optimization != SerializationOptimization.Fast)
			{
				info.AddValue("_contactCreditCards", ((_contactCreditCards!=null) && (_contactCreditCards.Count>0) && !this.MarkedForDeletion)?_contactCreditCards:null);
				info.AddValue("_salesOrderHeaders", ((_salesOrderHeaders!=null) && (_salesOrderHeaders.Count>0) && !this.MarkedForDeletion)?_salesOrderHeaders:null);
			}
			// __LLBLGENPRO_USER_CODE_REGION_START GetObjectInfo
			// __LLBLGENPRO_USER_CODE_REGION_END
			base.GetObjectData(info, context);
		}

		/// Gets a list of all the EntityRelation objects the type of this instance has.
		/// <returns>A list of all the EntityRelation objects the type of this instance has. Hierarchy relations are excluded.</returns>
		protected override List<IEntityRelation> GetAllRelations()
		{
			return new CreditCardRelations().GetAllRelations();
		}

		///  Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entities of type 'ContactCreditCard' to this entity.
		/// <returns></returns>
		public virtual IRelationPredicateBucket GetRelationInfoContactCreditCards()
		{
			IRelationPredicateBucket bucket = new RelationPredicateBucket();
			bucket.PredicateExpression.Add(new FieldCompareValuePredicate(ContactCreditCardFields.CreditCardId, null, ComparisonOperator.Equal, this.CreditCardId));
			return bucket;
		}

		///  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()
		{
			IRelationPredicateBucket bucket = new RelationPredicateBucket();
			bucket.PredicateExpression.Add(new FieldCompareValuePredicate(SalesOrderHeaderFields.CreditCardId, null, ComparisonOperator.Equal, this.CreditCardId));
			return bucket;
		}

		/// Creates a new instance of the factory related to this entity
		protected override IEntityFactory2 CreateEntityFactory()
		{
			return EntityFactoryCache2.GetEntityFactory(typeof(CreditCardEntityFactory));
		}
#if !CF
		/// Adds the member collections to the collections queue (base first)
		/// <param name="collectionsQueue">The collections queue.</param>
		protected override void AddToMemberEntityCollectionsQueue(Queue<IEntityCollection2> collectionsQueue)
		{
			base.AddToMemberEntityCollectionsQueue(collectionsQueue);
			collectionsQueue.Enqueue(this._contactCreditCards);
			collectionsQueue.Enqueue(this._salesOrderHeaders);
		}

		/// Gets the member collections queue from the queue (base first)
		/// <param name="collectionsQueue">The collections queue.</param>
		protected override void GetFromMemberEntityCollectionsQueue(Queue<IEntityCollection2> collectionsQueue)
		{
			base.GetFromMemberEntityCollectionsQueue(collectionsQueue);
			this._contactCreditCards = (EntityCollection<ContactCreditCardEntity>) collectionsQueue.Dequeue();
			this._salesOrderHeaders = (EntityCollection<SalesOrderHeaderEntity>) collectionsQueue.Dequeue();

		}

		/// Determines whether the entity has populated member collections
		/// <returns>true if the entity has populated member collections.</returns>
		protected override bool HasPopulatedMemberEntityCollections()
		{
			bool toReturn = false;
			toReturn |=(this._contactCreditCards != null);
			toReturn |=(this._salesOrderHeaders != null);
			return toReturn ? true : base.HasPopulatedMemberEntityCollections();
		}

		/// Creates the member entity collections queue.
		/// <param name="collectionsQueue">The collections queue.</param>
		/// <param name="requiredQueue">The required queue.</param>
		protected override void CreateMemberEntityCollectionsQueue(Queue<IEntityCollection2> collectionsQueue, Queue<bool> requiredQueue)
		{
			base.CreateMemberEntityCollectionsQueue(collectionsQueue, requiredQueue);
			collectionsQueue.Enqueue(requiredQueue.Dequeue() ? new EntityCollection<ContactCreditCardEntity>(EntityFactoryCache2.GetEntityFactory(typeof(ContactCreditCardEntityFactory))) : null);
			collectionsQueue.Enqueue(requiredQueue.Dequeue() ? new EntityCollection<SalesOrderHeaderEntity>(EntityFactoryCache2.GetEntityFactory(typeof(SalesOrderHeaderEntityFactory))) : null);
		}
#endif
		/// Gets all related data objects, stored by name. The name is the field name mapped onto the relation for that particular data element.
		/// <returns>Dictionary with per name the related referenced data element, which can be an entity collection or an entity or null</returns>
		protected override Dictionary<string, object> GetRelatedData()
		{
			Dictionary<string, object> toReturn = new Dictionary<string, object>();
			toReturn.Add("ContactCreditCards", _contactCreditCards);
			toReturn.Add("SalesOrderHeaders", _salesOrderHeaders);
			return toReturn;
		}

		///  Initializes the class members
		private void InitClassMembers()
		{
			PerformDependencyInjection();

			// __LLBLGENPRO_USER_CODE_REGION_START InitClassMembers
			// __LLBLGENPRO_USER_CODE_REGION_END
			OnInitClassMembersComplete();
		}

		#region Custom Property Hashtable Setup
		///  Initializes the hashtables for the entity type and entity field custom properties.
		private static void SetupCustomPropertyHashtables()
		{
			_customProperties = new Dictionary<string, string>();
			_fieldsCustomProperties = new Dictionary<string, Dictionary<string, string>>();
			Dictionary<string, string> fieldHashtable;
			fieldHashtable = new Dictionary<string, string>();
			_fieldsCustomProperties.Add("CardNumber", fieldHashtable);
			fieldHashtable = new Dictionary<string, string>();
			_fieldsCustomProperties.Add("CardType", fieldHashtable);
			fieldHashtable = new Dictionary<string, string>();
			_fieldsCustomProperties.Add("CreditCardId", fieldHashtable);
			fieldHashtable = new Dictionary<string, string>();
			_fieldsCustomProperties.Add("ExpMonth", fieldHashtable);
			fieldHashtable = new Dictionary<string, string>();
			_fieldsCustomProperties.Add("ExpYear", fieldHashtable);
			fieldHashtable = new Dictionary<string, string>();
			_fieldsCustomProperties.Add("ModifiedDate", fieldHashtable);
		}
		#endregion

		///  Initializes the class with empty data, as if it is a new Entity.
		/// <param name="validator">The validator object for this CreditCardEntity</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();

		}

		#region Class Property Declarations
		///  The relations object holding all relations of this entity with other entity classes.
		public  static CreditCardRelations Relations
		{
			get	{ return new CreditCardRelations(); }
		}

		///  The custom properties for this entity type.
		/// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks>
		public  static Dictionary<string, string> CustomProperties
		{
			get { return _customProperties;}
		}

		///  Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'ContactCreditCard' for this entity.
		/// <returns>Ready to use IPrefetchPathElement2 implementation.</returns>
		public static IPrefetchPathElement2 PrefetchPathContactCreditCards
		{
			get	{ return new PrefetchPathElement2( new EntityCollection<ContactCreditCardEntity>(EntityFactoryCache2.GetEntityFactory(typeof(ContactCreditCardEntityFactory))), (IEntityRelation)GetRelationsForField("ContactCreditCards")[0], (int)AdventureWorks.Dal.Adapter.v41.EntityType.CreditCardEntity, (int)AdventureWorks.Dal.Adapter.v41.EntityType.ContactCreditCardEntity, 0, null, null, null, null, "ContactCreditCards", SD.LLBLGen.Pro.ORMSupportClasses.RelationType.OneToMany);	}
		}

		///  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 new PrefetchPathElement2( new EntityCollection<SalesOrderHeaderEntity>(EntityFactoryCache2.GetEntityFactory(typeof(SalesOrderHeaderEntityFactory))), (IEntityRelation)GetRelationsForField("SalesOrderHeaders")[0], (int)AdventureWorks.Dal.Adapter.v41.EntityType.CreditCardEntity, (int)AdventureWorks.Dal.Adapter.v41.EntityType.SalesOrderHeaderEntity, 0, null, null, null, null, "SalesOrderHeaders", SD.LLBLGen.Pro.ORMSupportClasses.RelationType.OneToMany);	}
		}

		///  The custom properties for the type of this entity instance.
		/// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks>
		[Browsable(false), XmlIgnore]
		protected override Dictionary<string, string> CustomPropertiesOfType
		{
			get { return CustomProperties;}
		}

		///  The custom properties for the fields of this entity type. The returned Hashtable contains per fieldname a hashtable of name-value pairs.
		/// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks>
		public  static Dictionary<string, Dictionary<string, string>> FieldsCustomProperties
		{
			get { return _fieldsCustomProperties;}
		}

		///  The custom properties for the fields of the type of this entity instance. The returned Hashtable contains per fieldname a hashtable of name-value pairs.
		/// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks>
		[Browsable(false), XmlIgnore]
		protected override Dictionary<string, Dictionary<string, string>> FieldsCustomPropertiesOfType
		{
			get { return FieldsCustomProperties;}
		}

		///  The CardNumber property of the Entity CreditCard

		/// <remarks>Mapped on  table field: "CreditCard"."CardNumber"

		/// Table field type characteristics (type, precision, scale, length): NVarChar, 0, 0, 25

		/// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.String CardNumber
		{
			get { return (System.String)GetValue((int)CreditCardFieldIndex.CardNumber, true); }
			set	{ SetValue((int)CreditCardFieldIndex.CardNumber, value); }
		}

		///  The CardType property of the Entity CreditCard

		/// <remarks>Mapped on  table field: "CreditCard"."CardType"

		/// Table field type characteristics (type, precision, scale, length): NVarChar, 0, 0, 50

		/// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.String CardType
		{
			get { return (System.String)GetValue((int)CreditCardFieldIndex.CardType, true); }
			set	{ SetValue((int)CreditCardFieldIndex.CardType, value); }
		}

		///  The CreditCardId property of the Entity CreditCard

		/// <remarks>Mapped on  table field: "CreditCard"."CreditCardID"

		/// 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 CreditCardId
		{
			get { return (System.Int32)GetValue((int)CreditCardFieldIndex.CreditCardId, true); }
			set	{ SetValue((int)CreditCardFieldIndex.CreditCardId, value); }
		}

		///  The ExpMonth property of the Entity CreditCard

		/// <remarks>Mapped on  table field: "CreditCard"."ExpMonth"

		/// Table field type characteristics (type, precision, scale, length): TinyInt, 3, 0, 0

		/// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.Byte ExpMonth
		{
			get { return (System.Byte)GetValue((int)CreditCardFieldIndex.ExpMonth, true); }
			set	{ SetValue((int)CreditCardFieldIndex.ExpMonth, value); }
		}

		///  The ExpYear property of the Entity CreditCard

		/// <remarks>Mapped on  table field: "CreditCard"."ExpYear"

		/// Table field type characteristics (type, precision, scale, length): SmallInt, 5, 0, 0

		/// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks>
		public virtual System.Int16 ExpYear
		{
			get { return (System.Int16)GetValue((int)CreditCardFieldIndex.ExpYear, true); }
			set	{ SetValue((int)CreditCardFieldIndex.ExpYear, value); }
		}

		///  The ModifiedDate property of the Entity CreditCard

		/// <remarks>Mapped on  table field: "CreditCard"."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)CreditCardFieldIndex.ModifiedDate, true); }
			set	{ SetValue((int)CreditCardFieldIndex.ModifiedDate, value); }
		}

		///  Gets the EntityCollection with the related entities of type 'ContactCreditCardEntity' 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(ContactCreditCardEntity))]
		public virtual EntityCollection<ContactCreditCardEntity> ContactCreditCards
		{
			get { return GetOrCreateEntityCollection<ContactCreditCardEntity, ContactCreditCardEntityFactory>("CreditCard", true, false, ref _contactCreditCards);	}
		}

		///  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>("CreditCard", true, false, ref _salesOrderHeaders);	}
		}

		///  Gets the type of the hierarchy this entity is in.
		protected override InheritanceHierarchyType LLBLGenProIsInHierarchyOfType
		{
			get { return InheritanceHierarchyType.None;}
		}

		///  Gets or sets a value indicating whether this entity is a subtype
		protected override bool LLBLGenProIsSubType
		{
			get { return false;}
		}

		/// Returns the AdventureWorks.Dal.Adapter.v41.EntityType enum value for this entity.
		[Browsable(false), XmlIgnore]
		protected override int LLBLGenProEntityTypeValue
		{
			get { return (int)AdventureWorks.Dal.Adapter.v41.EntityType.CreditCardEntity; }
		}

		#endregion

		#region Custom Entity code

		// __LLBLGENPRO_USER_CODE_REGION_START CustomEntityCode
		// __LLBLGENPRO_USER_CODE_REGION_END
		#endregion

		#region Included code

		#endregion
	}
}


text:
package org.cfr.capsicum.spring.support;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.cayenne.BaseContext;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.configuration.CayenneRuntime;
import org.apache.cayenne.configuration.ObjectContextFactory;
import org.apache.cayenne.di.Injector;
import org.cfr.commons.util.Assert;
import org.springframework.beans.factory.DisposableBean;

/**
 * This class allows creating {@link ObjectContext} for the the current thread.
 * @author devacfr<christophefriederich@mac.com>
 * @since 1.0
 * @see MethodInterceptor
 */
public class CayenneInterceptor implements MethodInterceptor, DisposableBean {

    /**
     * cayenne runtime instance.
     */
    protected final CayenneRuntime cayenneRuntime;

    /**
     * Creates CayenneInterceptor for CayenneRuntime.
     * @param cayenneRuntime cayenne runtime instance
     */
    public CayenneInterceptor(final CayenneRuntime cayenneRuntime) {
        this.cayenneRuntime = Assert.notNull(cayenneRuntime, "Cayenne Runtime is required");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        ObjectContext objectContext = BaseContext.getThreadObjectContext();
        if (objectContext == null) {
            Injector injector = cayenneRuntime.getInjector();
            objectContext = injector.getInstance(ObjectContextFactory.class).createContext();
            BaseContext.bindThreadObjectContext(objectContext);
        }
        Object retVal = null;
        // This is an around advice: Invoke the next interceptor in the chain.
        // This will normally result in a target object being invoked.
        retVal = invocation.proceed();

        return retVal;
    }

    @Override
    public void destroy() throws Exception {
        CayenneRuntime.bindThreadInjector(null);
        BaseContext.bindThreadObjectContext(null);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.example.ruby.mygetgps.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.example.ruby.mygetgps.models.Trip;
import com.example.ruby.mygetgps.utils.Constants;
import com.example.ruby.mygetgps.utils.TripHelper;

import timber.log.Timber;

public class StopTripReceiver extends BroadcastReceiver {
    public StopTripReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            Timber.d("method=onReceive intent.action='%s'", intent.getAction());

            switch (intent.getAction()) {
                /*case UploadService.ACTION:
                    Trip trip = (Trip) intent.getSerializableExtra(Constants.TRIP_OBJECT_EXTRA);
                    TripHelper.addRecentlyPostedTrip(trip, context);
                    break;*/
            }
        }
    }
}


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

<title>Overview</title>
<meta name="date" content="2015-02-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.openhc.ohc.ui.view_pages

Class Overview

java.lang.Object

io.openhc.ohc.ui.view_pages.Page

io.openhc.ohc.ui.view_pages.Overview

public class Overview
extends Page

Device overview page. Shows a ListView containing all devices attached to the connected
 basestation

Author:

Tobias Schramm

Field Summary

Fields

Modifier and Type
Field and Description

private EditText
et_header_name

private ImageView
iv_header_icon

private ImageView
iv_header_settings

private ListView
lv_devices

Fields inherited from class io.openhc.ohc.ui.view_pages.Page

ctx, ohc

Constructor Summary

Constructors

Constructor and Description

Overview(OHC_ui ctx,
        OHC ohc)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
get_layout_id()

Returns the id of the layout corresponding to this page

ListView
get_lv_devices()

void
init()

Initialization method, called when the page should show up

void
onClick(View v)

void
onItemClick(AdapterView parent,
           View view,
           int position,
           long id)

Methods inherited from class io.openhc.ohc.ui.view_pages.Page

restore_state, store_state

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

lv_devices

private ListView lv_devices

iv_header_icon

private ImageView iv_header_icon

et_header_name

private EditText et_header_name

iv_header_settings

private ImageView iv_header_settings

Constructor Detail

Overview

public Overview(OHC_ui ctx,
                OHC ohc)

Method Detail

init

public void init()

Description copied from class: Page

Initialization method, called when the page should show up

Specified by:

init in class Page

onClick

public void onClick(View v)

onItemClick

public void onItemClick(AdapterView parent,
                        View view,
                        int position,
                        long id)

get_lv_devices

public ListView get_lv_devices()

get_layout_id

public int get_layout_id()

Description copied from class: Page

Returns the id of the layout corresponding to this page

Specified by:

get_layout_id in class Page

Returns:

Id of corresponding layout

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Merulius brassicaefolius Schwein.

### Remarks
null


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

<title>Uses of Class com.cyberfront.crdt.sample.simlation.MessageRouter</title>
<meta name="date" content="2017-10-29">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.cyberfront.crdt.sample.simlation.MessageRouter

Packages that use MessageRouter

Package
Description

com.cyberfront.crdt.sample.simlation

The com.cyberfront.crdt.sample.simulation contains a collection of classes which are intended to perform stress testing on the
  functionality of the commutative CRDT implementation specified elsewhere in the class library.

Uses of MessageRouter in com.cyberfront.crdt.sample.simlation

Fields in com.cyberfront.crdt.sample.simlation declared as MessageRouter

Modifier and Type
Field and Description

private MessageRouter
Executive.router

A queue which manages messages awaiting delivery

Methods in com.cyberfront.crdt.sample.simlation that return MessageRouter

Modifier and Type
Method and Description

MessageRouter
Executive.getRouter()

Retrieve the message router associated with this Executive instance

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
'use strict'
const sha1 = require('sha1')
const Promise = require('bluebird')
const request = Promise.promisify(require('request'))

const prefix = 'https://api.weixin.qq.com/cgi-bin/'
const api = {
    accessToken: prefix + 'token?grant_type=client_credential'
}

/*!
 * weixin auth
 * this middleware is used to authorize from weixin
 * the opts should have token
 */
function Wechat(opts) {
    let that = this
    this.appID = opts.appID
    this.appSecret = opts.appSecret
    this.getAccessToken = opts.getAccessToken
    this.saveAccessToken = opts.saveAccessToken

    this.getAccessToken()
        .then(function(data) {
            try {
                data = JSON.parse(data)
            } catch (e) {
                return that.updateAccessToken()
            }

            if (that.isValidAccessToken(data)) {
                Promise.resolve(data)
            } else {
                return that.updateAccessToken()
            }
        })
        .then(function(data) {
            that.access_token = data.access_token
            that.expires_in = data.expires_in

            that.saveAccessToken(data)
        })
}

/*!
 * exist, expire
 * lib: request, which provide higher level api based on http.request and promise
 */

Wechat.prototype.isValidAccessToken = function (data) {
    if (!data || !data.access_token || !data.expires_in) {
        return false
    }

    let access_token = data.access_token
    let expires_in = data.expires_in
    let now = (new Date().getTime())

    if (now < expires_in) {
        return true
    } else {
        return false
    }
    // return new Date().getTime() < data.expires_in ? true : false
}

Wechat.prototype.updateAccessToken = function () {
    let url = api.accessToken + '&appid=' + this.appID + '&secret=' + this.appSecret

    return new Promise(function(resolve, reject) {
        request({ url: url, json:true })
            .then(function (response) {
                let data = response[1]
                let now = (new Date().getTime())
                let expires_in = now + (data.expires_in - 60) * 1000
                data.expires_in = expires_in
                resolve(data)
            })
    })

    return new Promise(function (resolve, reject) {
        request({
            url: url,
            json: true
        }).then(function (response) {
            let data = response[1]
            data.expires_in += new Date().getTime() - (60 * 1000)

            console.log('----------------from update')
            console.dir(data)

            resolve(data)
        })
    })
}

module.exports = function(opts) {
    let wechat = new Wechat(opts)

    return function* (next) {
        console.dir(this.query)
        // get info for sha1 -> use es6 destructure assign to simplify this boilerplate
        let signature = this.query.signature
        let nonce = this.query.nonce
        let timestamp = this.query.timestamp
        let echostr = this.query.echostr
        let token = opts.token

        let str = [token, timestamp, nonce].sort().join('')
        let sha = sha1(str)

        if(sha === signature) {
            this.body = echostr + ''
        } else {
            this.body = 'it is not ok to hack me'
            console.log('some other requested our server')
            console.dir(this.query)
        }
        yield next
    }
}


text:
package com.googlecode.jmxtrans.model.output;

import com.fasterxml.jackson.core.JsonFactory;
import com.google.common.collect.ImmutableList;
import com.googlecode.jmxtrans.model.QueryFixtures;
import com.googlecode.jmxtrans.model.ResultFixtures;
import com.googlecode.jmxtrans.model.ServerFixtures;
import org.junit.Test;

import java.io.IOException;
import java.io.StringWriter;

import static org.assertj.core.api.Assertions.assertThat;

public class SensuWriter2Test {

	@Test
	public void metricsAreFormattedCorrectly() throws IOException {
		StringWriter writer = new StringWriter();
		SensuWriter2 sensuWriter = new SensuWriter2(new GraphiteWriter2(ImmutableList.<String>of(), null), new JsonFactory());

		sensuWriter.write(writer, ServerFixtures.dummyServer(), QueryFixtures.dummyQuery(), ResultFixtures.dummyResults());
		String lineSep = System.lineSeparator();
		assertThat(writer.toString()).isEqualTo(
				"{" + lineSep +
				"  \"name\" : \"jmxtrans\"," + lineSep +
				"  \"type\" : \"metric\"," + lineSep +
				"  \"handler\" : \"graphite\"," + lineSep +
				"  \"output\" : \"host_example_net_4321.MemoryAlias.ObjectPendingFinalizationCount 10 0\\n\"" + lineSep +
				"}");
	}

}


text:
'use strict';

const fs = require('fs');
const myRestifyApi = require('my-restify-api');
const oauth = myRestifyApi.plugin.oauth;
const vehicleHistoryV1Controller = require('./controller/vehicleHistoryV1');
const logger = require('./logger/logger').logger;

const startServer = function startServer(callback) {
  fs.readFile('config/public.key', (err, data) => {
    if (err) {
      logger.debug('config/public.key read error: ', err);
      throw err;
    }

    const options = {
      appName: 'API',
      swagger: {
        enabled: true,
        apiDocsDir: `${__dirname}/../public/`
      },
      authorization: {
        authHeaderPrefix: 'x-auth-',
        key: data,
        noVerify: false
      },
      bodyParser: {
        enabled: true,
        options: {
          maxBodySize: 1e6,
          mapParams: true,
          overrideParams: false
        }
      },
      acceptable: [
        'application/vnd.vehicle-history.v1+json',
        'application/vnd.vehicle-history.v1+xml'
      ]
    };

    const errorHandlers = {
      VehicleNotFound: {
        className: 'NotFoundError'
      },
      ServiceUnavailable: {
        className: 'ServiceUnavailableError'
      },
      InvalidVehiclePlate: {
        className: 'BadRequestError'
      },
      '': {
        className: 'ServiceUnavailableError'
      }
    };

    const publicCacheHandler = function publicCacheHandler(req, res, next) {
      res.cache('public', {maxAge: 600});
      res.header('Vary', 'Accept-Language, Accept-Encoding, Accept, Content-Type');
      //res.charSet('utf-8');
      return next();
    };

    const noPreconditionHandler = function noPreconditionHandler(req, res, next) {
      return next();
    };

    const getHistoryDeprecatedAuthHandler = function getHistoryDeprecatedAuthHandler(req, res, next) {
      return oauth(req, next)
        .scope('openid')
        .client('vehiclehistory')
        .next();
    };

    const getHistoryAuthHandler = function getHistoryAuthHandler(req, res, next) {
      return oauth(req, next)
        .scope('vehicle:report:get')
        .user()
        .next();
    };
    const getBusAuthHandler = function getBusAuthHandler(req, res, next) {
      return oauth(req, next)
        .scope('bus:report:get')
        .user()
        .next();
    };

    const routes = {
      get: [],
      post: [],
      put: [],
      del: []
    };

    routes.get.push({
      options: {
        path: '/api/vehicle-history', version: '1.0.0'
      },
      authMethod: getHistoryDeprecatedAuthHandler,
      cache: publicCacheHandler,
      precondition: noPreconditionHandler,
      controllerMethod: vehicleHistoryV1Controller.checkVehicleHistoryV1
    });

    routes.get.push({
      options: {
        path: '/api/vehicle-reports', version: '1.0.0'
      },
      authMethod: getHistoryAuthHandler,
      cache: publicCacheHandler,
      precondition: noPreconditionHandler,
      controllerMethod: vehicleHistoryV1Controller.getVehicleReportsV1
    });

    routes.get.push({
      options: {
        path: '/api/bus-reports/:plate', version: '1.0.0'
      },
      authMethod: getBusAuthHandler,
      cache: publicCacheHandler,
      precondition: noPreconditionHandler,
      controllerMethod: vehicleHistoryV1Controller.getBusReportV1
    });

    const server = myRestifyApi.createServer(routes, errorHandlers, options);

    server.opts(/.*/, (req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', req.header('Access-Control-Request-Method'));
      res.header('Access-Control-Allow-Headers', req.header('Access-Control-Request-Headers'));
      res.send(200);
      return next();
    });

    myRestifyApi.runServer(server, options, (serverErr, port) => {
      logger.debug('myRestifyApi running on port: %d', port);
      return callback(serverErr, port);
    });

  });
};

module.exports = {
  startServer: startServer
};


text:
iwconfig | grep "(\w).*IEEE" -oP > interface.config
ACTIVE_INTERFACE=$(tail -n1 interface.config | cut -f1 -d" ")
echo $ACTIVE_INTERFACE > interface.config

#Disconnect, get new mac address, reconnect
killall NetworkManager
ifconfig $ACTIVE_INTERFACE down
macchanger -r $ACTIVE_INTERFACE
MAC_ADDRESS=$(ifconfig $ACTIVE_INTERFACE | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')

echo "
auto lo
iface lo inet loopback

auto $ACTIVE_INTERFACE
iface $ACTIVE_INTERFACE inet dhcp
wireless-mode Managed
wpa-ssid ELTE
wpa-ap-scan 1
wpa-proto RSN WPA
wpa-pairwise CCMP TKIP
wpa-group CCMP TKIP
wpa-key-mgmt WPA-EAP
wpa-eap PEAP
wpa-identity $1
wpa-password $2
wpa-phase1 fast_provisioning=1
wpa-pac-file " `pwd` "/cert.crt
" > /etc/network/interfaces

ifconfig $ACTIVE_INTERFACE up

dhclient $ACTIVE_INTERFACE -v

service NetworkManager start


text:
package tlf

import (
	"testing"

	"github.com/keybase/client/go/protocol/keybase1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestMakeHandle(t *testing.T) {
	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
	}

	r := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(5).AsUserOrTeam(),
		keybase1.MakeTestUID(1).AsUserOrTeam(),
	}

	uw := []keybase1.SocialAssertion{
		{
			User:    "user2",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service1",
		},
	}

	ur := []keybase1.SocialAssertion{
		{
			User:    "user5",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service2",
		},
	}

	h, err := MakeHandle(w, r, uw, ur, nil)
	require.NoError(t, err)
	require.Equal(t, []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(3).AsUserOrTeam(),
		keybase1.MakeTestUID(4).AsUserOrTeam(),
	}, h.Writers)
	require.Equal(t, []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(1).AsUserOrTeam(),
		keybase1.MakeTestUID(5).AsUserOrTeam(),
	}, h.Readers)
	require.Equal(t, []keybase1.SocialAssertion{
		{
			User:    "user1",
			Service: "service1",
		},
		{
			User:    "user2",
			Service: "service3",
		},
	}, h.UnresolvedWriters)
	require.Equal(t, []keybase1.SocialAssertion{
		{
			User:    "user1",
			Service: "service2",
		},
		{
			User:    "user5",
			Service: "service3",
		},
	}, h.UnresolvedReaders)
}

func TestMakeHandleFailures(t *testing.T) {
	_, err := MakeHandle(nil, nil, nil, nil, nil)
	assert.Equal(t, errNoWriters, err)

	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
	}

	r := []keybase1.UserOrTeamID{
		keybase1.UserOrTeamID(keybase1.PUBLIC_UID),
		keybase1.MakeTestUID(2).AsUserOrTeam(),
	}

	_, err = MakeHandle(r, nil, nil, nil, nil)
	assert.Equal(t, errInvalidWriter, err)

	_, err = MakeHandle(w, r, nil, nil, nil)
	assert.Equal(t, errInvalidReader, err)

	ur := []keybase1.SocialAssertion{
		{
			User:    "user5",
			Service: "service3",
		},
	}

	_, err = MakeHandle(w, r[:1], nil, ur, nil)
	assert.Equal(t, errInvalidReader, err)

	// Any handle with a team must be a single-team handle.
	w = []keybase1.UserOrTeamID{
		keybase1.MakeTestTeamID(3, false).AsUserOrTeam(),
		keybase1.MakeTestTeamID(4, false).AsUserOrTeam(),
	}
	r = []keybase1.UserOrTeamID{}
	_, err = MakeHandle(w, r, nil, nil, nil)
	assert.Equal(t, errInvalidWriter, err)

	w = []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestTeamID(3, false).AsUserOrTeam(),
	}
	r = []keybase1.UserOrTeamID{}
	_, err = MakeHandle(w, r, nil, nil, nil)
	assert.Equal(t, errInvalidWriter, err)

	w = []keybase1.UserOrTeamID{
		keybase1.MakeTestTeamID(3, false).AsUserOrTeam(),
		keybase1.MakeTestUID(4).AsUserOrTeam(),
	}
	r = []keybase1.UserOrTeamID{}
	_, err = MakeHandle(w, r, nil, nil, nil)
	assert.Equal(t, errInvalidWriter, err)

	w = []keybase1.UserOrTeamID{
		keybase1.MakeTestTeamID(3, false).AsUserOrTeam(),
	}
	r = []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
	}
	_, err = MakeHandle(w, r, nil, nil, nil)
	assert.Equal(t, errInvalidReader, err)

	w = []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(5).AsUserOrTeam(),
	}
	r = []keybase1.UserOrTeamID{
		keybase1.MakeTestTeamID(3, false).AsUserOrTeam(),
	}
	_, err = MakeHandle(w, r, nil, nil, nil)
	assert.Equal(t, errInvalidReader, err)
}

func TestHandleAccessorsPrivate(t *testing.T) {
	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
	}

	r := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(5).AsUserOrTeam(),
		keybase1.MakeTestUID(1).AsUserOrTeam(),
	}

	uw := []keybase1.SocialAssertion{
		{
			User:    "user2",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service1",
		},
	}

	ur := []keybase1.SocialAssertion{
		{
			User:    "user5",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service2",
		},
	}

	h, err := MakeHandle(w, r, uw, ur, nil)
	require.NoError(t, err)

	require.Equal(t, Private, h.Type())

	for _, u := range w {
		require.True(t, h.IsWriter(u))
		require.True(t, h.IsReader(u))
	}

	for _, u := range r {
		require.False(t, h.IsWriter(u))
		require.True(t, h.IsReader(u))
	}

	for i := 6; i < 10; i++ {
		u := keybase1.MakeTestUID(uint32(i)).AsUserOrTeam()
		require.False(t, h.IsWriter(u))
		require.False(t, h.IsReader(u))
	}

	require.Equal(t, h.ResolvedUsers(),
		[]keybase1.UserOrTeamID{
			keybase1.MakeTestUID(3).AsUserOrTeam(),
			keybase1.MakeTestUID(4).AsUserOrTeam(),
			keybase1.MakeTestUID(1).AsUserOrTeam(),
			keybase1.MakeTestUID(5).AsUserOrTeam(),
		})
	require.True(t, h.HasUnresolvedUsers())
	require.Equal(t, h.UnresolvedUsers(),
		[]keybase1.SocialAssertion{
			{
				User:    "user1",
				Service: "service1",
			},
			{
				User:    "user2",
				Service: "service3",
			},
			{
				User:    "user1",
				Service: "service2",
			},
			{
				User:    "user5",
				Service: "service3",
			},
		})
}

func TestHandleAccessorsPublic(t *testing.T) {
	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
	}

	uw := []keybase1.SocialAssertion{
		{
			User:    "user2",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service1",
		},
	}

	h, err := MakeHandle(
		w, []keybase1.UserOrTeamID{keybase1.UserOrTeamID(keybase1.PUBLIC_UID)},
		uw, nil, nil)
	require.NoError(t, err)

	require.Equal(t, Public, h.Type())

	for _, u := range w {
		require.True(t, h.IsWriter(u))
		require.True(t, h.IsReader(u))
	}

	for i := 6; i < 10; i++ {
		u := keybase1.MakeTestUID(uint32(i)).AsUserOrTeam()
		require.False(t, h.IsWriter(u))
		require.True(t, h.IsReader(u))
	}

	require.Equal(t, h.ResolvedUsers(),
		[]keybase1.UserOrTeamID{
			keybase1.MakeTestUID(3).AsUserOrTeam(),
			keybase1.MakeTestUID(4).AsUserOrTeam(),
		})
	require.True(t, h.HasUnresolvedUsers())
	require.Equal(t, h.UnresolvedUsers(),
		[]keybase1.SocialAssertion{
			{
				User:    "user1",
				Service: "service1",
			},
			{
				User:    "user2",
				Service: "service3",
			},
		})
}

func TestHandleAccessorsSingleTeam(t *testing.T) {
	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestTeamID(4, false).AsUserOrTeam(),
	}

	h, err := MakeHandle(
		w, nil, nil, nil, nil)
	require.NoError(t, err)

	require.Equal(t, SingleTeam, h.Type())

	// All types of IsWriter/IsReader calls should panic for team TLFs.
	for _, u := range w {
		require.Panics(t, func() { h.IsWriter(u) })
		require.Panics(t, func() { h.IsReader(u) })
	}

	u := keybase1.MakeTestUID(uint32(6)).AsUserOrTeam()
	require.Panics(t, func() { h.IsWriter(u) })
	require.Panics(t, func() { h.IsReader(u) })

	require.False(t, h.HasUnresolvedUsers())
}

func TestHandleHasUnresolvedUsers(t *testing.T) {
	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
	}

	uw := []keybase1.SocialAssertion{
		{
			User:    "user2",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service1",
		},
	}

	ur := []keybase1.SocialAssertion{
		{
			User:    "user5",
			Service: "service3",
		},
		{
			User:    "user1",
			Service: "service2",
		},
	}

	h, err := MakeHandle(w, nil, uw, ur, nil)
	require.NoError(t, err)
	require.True(t, h.HasUnresolvedUsers())

	uw = h.UnresolvedWriters
	h.UnresolvedWriters = nil
	require.True(t, h.HasUnresolvedUsers())

	h.UnresolvedReaders = nil
	require.False(t, h.HasUnresolvedUsers())

	h.UnresolvedWriters = uw
	require.True(t, h.HasUnresolvedUsers())
}

func TestHandleResolveAssertions(t *testing.T) {
	w := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(4).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
	}

	r := []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(5).AsUserOrTeam(),
		keybase1.MakeTestUID(1).AsUserOrTeam(),
	}

	uw := []keybase1.SocialAssertion{
		{
			User:    "user2",
			Service: "service3",
		},
		{
			User:    "user7",
			Service: "service2",
		},
		{
			User:    "user1",
			Service: "service1",
		},
	}

	ur := []keybase1.SocialAssertion{
		{
			User:    "user6",
			Service: "service3",
		},
		{
			User:    "user8",
			Service: "service1",
		},
		{
			User:    "user5",
			Service: "service1",
		},
		{
			User:    "user1",
			Service: "service2",
		},
		{
			User:    "user9",
			Service: "service1",
		},
		{
			User:    "user9",
			Service: "service3",
		},
	}

	h, err := MakeHandle(w, r, uw, ur, nil)
	require.NoError(t, err)

	assertions := make(map[keybase1.SocialAssertion]keybase1.UID)
	assertions[uw[0]] = keybase1.MakeTestUID(2) // new writer
	assertions[uw[2]] = keybase1.MakeTestUID(1) // reader promoted to writer
	assertions[ur[0]] = keybase1.MakeTestUID(6) // new reader
	assertions[ur[2]] = keybase1.MakeTestUID(5) // already a reader
	assertions[ur[3]] = keybase1.MakeTestUID(1) // already a writer
	assertions[ur[4]] = keybase1.MakeTestUID(9) // new reader
	assertions[ur[5]] = keybase1.MakeTestUID(9) // already a reader

	h = h.ResolveAssertions(assertions)

	require.Equal(t, []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(1).AsUserOrTeam(),
		keybase1.MakeTestUID(2).AsUserOrTeam(),
		keybase1.MakeTestUID(3).AsUserOrTeam(),
		keybase1.MakeTestUID(4).AsUserOrTeam(),
	}, h.Writers)
	require.Equal(t, []keybase1.UserOrTeamID{
		keybase1.MakeTestUID(5).AsUserOrTeam(),
		keybase1.MakeTestUID(6).AsUserOrTeam(),
		keybase1.MakeTestUID(9).AsUserOrTeam(),
	}, h.Readers)
	require.Equal(t, []keybase1.SocialAssertion{
		{
			User:    "user7",
			Service: "service2",
		},
	}, h.UnresolvedWriters)
	require.Equal(t, []keybase1.SocialAssertion{
		{
			User:    "user8",
			Service: "service1",
		},
	}, h.UnresolvedReaders)
}


text:
* Release 1.0.0
* Add AMD support
* Resizable is broken, needs to be fixed in dialog extended


text:
@main

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

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    package="com.example.app1">

    <uses-permission android:name="android.permission.INTERNET"
            tools:node="remove" tools:selector="com.example.libXYZ"/>

</manifest>

@lib1

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lib1">

    <!-- Same permissions as main manifest -->
    <uses-permission android:name="android.permission.INTERNET" android:maxSdkVersion="18"/>

</manifest>

@lib2

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lib2">

    <!-- this should be merged -->
    <uses-permission android:name="android.permission.INTERNET"
                     android:maxSdkVersion="20"/>

</manifest>

@result

@errors

ERROR:'tools:selector="com.example.libXYZ"' is not a valid library identifier, valid identifiers are : com.example.lib1,com.example.lib2


text:
from sqlalchemy import desc

from findex_gui.web import db
from findex_gui.orm.models import Logging

class LogController:
    @staticmethod
    def get(category: str = None, limit: int = 10, offset: int = 0):
        q = db.session.query(Logging)

        if isinstance(category, str):
            q = q.filter(Logging.category == category)

        q = q.order_by(desc(Logging.date_added))

        if isinstance(limit, int):
            q = q.limit(limit)

        if isinstance(offset, int):
            q = q.offset(offset)

        return q.all()


text:
DTA-Simulator
=============

General simulator for the Dynamic Traffic Assignment with multiple commodities,
multiple origins and destinations with partial compliance.
All the code is in java and all dependencies are included.

Don't forget to enable assertions (-ea parameter on the JVM).

Documentation
-------------

Doxygen can be run to generate the documentation using code comments.

Possible improvements and optimizations
---------------------------------------

1) Register only the densities and flows for a given cell for all commodities
that goes through that cell. To do so
- Precompute when adding the path the possible commodities through the cells
- Register only the values for these commodities in the block describing the
cell in the x vector
2) Parallelize the forward computation and possibly the solving of the adjoint
equations

Linking to IpOpt
============
The gradient descent method has been coded in Java in order to have full control
on what is happening during the optimization.

One may try t use IpOpt instead. Then, having IpOpt installed is mandatory.
To build it see http://www.coin-or.org/download/source/Ipopt/ and take the
most recent version (the version 3.10.3 was used in this project).
Then follow the instructions in /Ipopt-3.xx.x/Ipopt/doc/documentation.pdf

Moreover, you need lib/libjipopt.so which is the java wrapper for Ipopt.
Some binaries are available for some platforms at:
https://projects.coin-or.org/Ipopt/wiki/JavaInterface

If there is not the binaries for your platform, you will have to compile it
from the sources. To do so, look at:
/Ipopt-3.xx.x/Ipopt/contrib/JavaInterface/README


text:
#ifndef CONDITIONVARIABLE_H
#define CONDITIONVARIABLE_H

#include <stdint.h>
#include "cmsis_os.h"
#include "rtos/Mutex.h"
#include "rtos/Semaphore.h"

#include "platform/NonCopyable.h"

namespace rtos {
/** \addtogroup rtos */
/** @{*/

struct Waiter;

/** This class provides a safe way to wait for or send notifications of condition changes
 *
 * This class is used in conjunction with a mutex to safely wait for or
 * notify waiters of condition changes to a resource accessible by multiple
 * threads.
 *
 * # Defined behavior
 * - All threads waiting on the condition variable wake when
 *   ConditionVariable::notify_all is called.
 * - If one or more threads are waiting on the condition variable at least
 *   one of them wakes when ConditionVariable::notify is called.
 *
 * # Undefined behavior
 * - The thread which is unblocked on ConditionVariable::notify_one is
 *   undefined if there are multiple waiters.
 * - The order which in which waiting threads acquire the condition variable's
 *   mutex after ConditionVariable::notify_all is called is undefined.
 * - When ConditionVariable::notify_one or ConditionVariable::notify_all is
 *   called and there are one or more waiters and one or more threads attempting
 *   to acquire the condition variable's mutex the order in which the mutex is
 *   acquired is undefined.
 * - The behavior of ConditionVariable::wait and ConditionVariable::wait_for
 *   is undefined if the condition variable's mutex is locked more than once by
 *   the calling thread.
 * - Spurious notifications (not triggered by the application) can occur
 *   and it is not defined when these occur.
 *
 * @note Synchronization level: Thread safe
 *
 * Example:
 * @code
 * #include "mbed.h"
 *
 * Mutex mutex;
 * ConditionVariable cond(mutex);
 *
 * // These variables are protected by locking mutex
 * uint32_t count = 0;
 * bool done = false;
 *
 * void worker_thread()
 * {
 *     mutex.lock();
 *     do {
 *         printf("Worker: Count %lu\r\n", count);
 *
 *         // Wait for a condition to change
 *         cond.wait();
 *
 *     } while (!done);
 *     printf("Worker: Exiting\r\n");
 *     mutex.unlock();
 * }
 *
 * int main() {
 *     Thread thread;
 *     thread.start(worker_thread);
 *
 *     for (int i = 0; i < 5; i++) {
 *
 *         mutex.lock();
 *         // Change count and notify waiters of this
 *         count++;
 *         printf("Main: Set count to %lu\r\n", count);
 *         cond.notify_all();
 *         mutex.unlock();
 *
 *         wait(1.0);
 *     }
 *
 *     mutex.lock();
 *     // Change done and notify waiters of this
 *     done = true;
 *     printf("Main: Set done\r\n");
 *     cond.notify_all();
 *     mutex.unlock();
 *
 *     thread.join();
 * }
 * @endcode
 */
class ConditionVariable : private mbed::NonCopyable<ConditionVariable> {
public:
    /** Create and Initialize a ConditionVariable object
     *
     * @note You cannot call this function from ISR context.
    */
    ConditionVariable(Mutex &mutex);

    /** Wait for a notification
     *
     * Wait until a notification occurs.
     *
     * @note - The thread calling this function must be the owner of the
     * ConditionVariable's mutex and it must be locked exactly once
     * @note - Spurious notifications can occur so the caller of this API
     * should check to make sure the condition they are waiting on has
     * been met
     *
     * Example:
     * @code
     * mutex.lock();
     * while (!condition_met) {
     *     cond.wait();
     * }
     *
     * function_to_handle_condition();
     *
     * mutex.unlock();
     * @endcode
     *
     * @note You cannot call this function from ISR context.
     */
    void wait();

    /** Wait for a notification until specified time
     *
     * @param   millisec  absolute end time referenced to Kernel::get_ms_count()
     * @return  true if a timeout occurred, false otherwise.
     *
     * @note - The thread calling this function must be the owner of the
     * ConditionVariable's mutex and it must be locked exactly once
     * @note - Spurious notifications can occur so the caller of this API
     * should check to make sure the condition they are waiting on has
     * been met
     *
     * Example:
     * @code
     * mutex.lock();
     * uint64_t end_time = Kernel::get_ms_count() + COND_WAIT_TIMEOUT;
     *
     * while (!condition_met) {
     *     if (cond.wait_until(end_time)) {
     *         break;
     *     }
     * }
     *
     * if (condition_met) {
     *     function_to_handle_condition();
     * }
     *
     * mutex.unlock();
     * @endcode
     *
     * @note You cannot call this function from ISR context.
     */
    bool wait_until(uint64_t millisec);

    /** Wait for a notification or timeout
     *
     * @param   millisec  timeout value or osWaitForever in case of no time-out.
     * @return  true if a timeout occurred, false otherwise.
     *
     * @note - The thread calling this function must be the owner of the
     * ConditionVariable's mutex and it must be locked exactly once
     * @note - Spurious notifications can occur so the caller of this API
     * should check to make sure the condition they are waiting on has
     * been met
     *
     * Example:
     * @code
     * mutex.lock();
     *
     * while (!condition_met) {
     *     cond.wait_for(MAX_SLEEP_TIME);
     *     if (!condition_met) {
     *         do_other_work_while_condition_false();
     *     }
     * }
     *
     * if (condition_met) {
     *     function_to_handle_condition();
     * }
     *
     * mutex.unlock();
     * @endcode
     *
     * @note You cannot call this function from ISR context.
     */
    bool wait_for(uint32_t millisec);

    /** Notify one waiter on this condition variable that a condition changed.
     *
     * @note - The thread calling this function must be the owner of the ConditionVariable's mutex
     *
     * @note You cannot call this function from ISR context.
     */
    void notify_one();

    /** Notify all waiters on this condition variable that a condition changed.
     *
     * @note - The thread calling this function must be the owner of the ConditionVariable's mutex
     *
     * @note You cannot call this function from ISR context.
     */
    void notify_all();

    /** ConditionVariable destructor
     *
     * @note You cannot call this function from ISR context.
     */
    ~ConditionVariable();

protected:
    struct Waiter {
        Waiter();
        Semaphore sem;
        Waiter *prev;
        Waiter *next;
        bool in_list;
    };

    static void _add_wait_list(Waiter **wait_list, Waiter *waiter);
    static void _remove_wait_list(Waiter **wait_list, Waiter *waiter);
    Mutex &_mutex;
    Waiter *_wait_list;
};

}
#endif

/** @}*/


text:
package com.akira.mis.module.sys.service;

import com.akira.mis.common.service.DatabaseHandlerService;
import com.akira.mis.module.sys.domain.Role;
import com.akira.mis.module.sys.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface RoleService extends DatabaseHandlerService<Role> {

    Role getRoleDetail(Role role);

    List<Role> listByUser(User user);
}


text:
"""
@brief      test log(time=25s)
"""
import os
import unittest
import shutil
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import (
    get_temp_folder, skipif_appveyor, skipif_travis, add_missing_development_version,
    skipif_circleci)
import ensae_teaching_cs

class TestNotebookRunner2aML2(unittest.TestCase):

    def setUp(self):
        add_missing_development_version(["pymyinstall", "pyensae", "pymmails", "jyquickhelper"],
                                        __file__, hide=True)

    @skipif_appveyor("too long for appveyor")
    @skipif_travis("execution does not stop")
    @skipif_circleci("too long for circleci")
    def test_notebook_runner_2a_ml(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")
        from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks, clean_function_1a
        from ensae_teaching_cs.data import simple_database
        temp = get_temp_folder(__file__, "temp_notebook2a_ml2")
        keepnote = ls_notebooks("td2a_ml")
        keepnote = [
            _ for _ in keepnote if (
                "machine_learning" not in _ and
                "overfitting" not in _)]
        shutil.copy(simple_database(), temp)

        def filter(i, n):
            if "SNCF" in n:
                return False
            if "Scraping" in n:
                return False
            if "deep_python" in n:
                return False
            if "h2o" in n:
                # h2o is not working from a virtual environment
                return False
            if "td2a" in os.path.split(n)[-1]:
                # already tested by others tests
                return False
            if "libraries" in n:
                return False
            if 'gradient' in n:
                return False
            return True

        execute_notebooks(temp, keepnote, filter, fLOG=fLOG,
                          clean_function=clean_function_1a,
                          dump=ensae_teaching_cs)

if __name__ == "__main__":
    unittest.main()


text:
core-icon
=========

See the [component page](http://polymer.github.io/core-icon) for more information.


text:
<?php
/**
 * Description of LearningStructureAdminController
 *
 * @author bartek
 */
namespace Traffic\StoreBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\AdminBundle\Exception\ModelManagerException;
use Symfony\Component\HttpFoundation\Request;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Symfony\Component\Routing\Annotation\Route;

class CategoryAdminController extends Controller {

    /**
     * return the Response object associated to the list action
     *
     * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
     *
     * @return Response
     */
    public function listAction()
    {
        if (false === $this->admin->isGranted('LIST')) {
            throw new AccessDeniedException();
        }

        $options = array(
            'decorate' => true,
            'rootOpen' => '
',
            'rootClose' => '
',
            'childOpen' => function($node) {
                return '
';
            },
            'childClose' => '
',
            'nodeDecorator' => function($node) {
                return '
'.$node['name'].'
';
            }
        );
        $repo = $this->admin->getObjectRepository();

        $htmlTree = $repo->childrenHierarchy(
            null, /* starting from root nodes */
            false, /* load all children, not only direct */
            $options
        );

        return $this->render($this->admin->getTemplate('tree'), array(
            'action' => 'list',
            'tree' => $htmlTree
        ));
    }

    public function treeRenameAction(Request $request){
        $ls_manager = $this->get('traffic.store.category.manager');

        $ls_manager->rename($request->get('node'), $request->get('name'));

        $response = new Response(json_encode(true));
        $response->headers->set('Content-Type', 'application/json');

        return $response;

    }

    public function treeRemoveAction(Request $request){
        $ls_manager = $this->get('traffic.store.category.manager');
        $node = $ls_manager->findById($request->get('node'));

        $this->admin->getObjectRepository()->removeFromTree($node);

        $response = new Response(json_encode(true));
        $response->headers->set('Content-Type', 'application/json');

        return $response;

    }

    public function treeAddAction(Request $request){
        $ls_manager = $this->get('traffic.store.category.manager');

        $parent = $ls_manager->findById($request->get('parent'));

        $node = $ls_manager->create('New Category');

        if($parent instanceof LearningStructure){
            $this->admin->getObjectRepository()->persistAsLastChildOf($node, $parent);
        }else{
            $this->admin->getObjectRepository()->persistAsLastChild($node);
        }
        $this->getDoctrine()->getEntityManager()->flush();

        $response = new Response(json_encode($node->getId()));
        $response->headers->set('Content-Type', 'application/json');

        return $response;

    }

    public function treeMoveAction(Request $request){
        $ls_manager = $this->get('traffic.store.category.manager');
        $ls_manager->move($request);

        $response = new Response(json_encode(true));
        $response->headers->set('Content-Type', 'application/json');

        return $response;

    }

}


text:
package jenkins.model;

import hudson.Extension;
import hudson.Util;
import hudson.XmlFile;
import hudson.util.FormValidation;
import hudson.util.XStream2;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

import static hudson.Util.fixNull;

/**
 * Stores the location of Jenkins (e-mail address and the HTTP URL.)
 *
 * @author Kohsuke Kawaguchi
 * @since 1.494
 */
@Extension
public class JenkinsLocationConfiguration extends GlobalConfiguration {
    /**
     * @deprecated
     */
    private transient String hudsonUrl;
    private String adminAddress;
    private String jenkinsUrl;

    // just to suppress warnings
    private transient String charset,useSsl;

    public static JenkinsLocationConfiguration get() {
        return GlobalConfiguration.all().get(JenkinsLocationConfiguration.class);
    }

    public JenkinsLocationConfiguration() {
        load();
    }

    @Override
    public synchronized void load() {
        // for backward compatibility, if we don't have our own data yet, then
        // load from Mailer.
        XmlFile file = getConfigFile();
        if(!file.exists()) {
            XStream2 xs = new XStream2();
            xs.addCompatibilityAlias("hudson.tasks.Mailer$DescriptorImpl",JenkinsLocationConfiguration.class);
            file = new XmlFile(xs,new File(Jenkins.getInstance().getRootDir(),"hudson.tasks.Mailer.xml"));
            if (file.exists()) {
                try {
                    file.unmarshal(this);
                    if (jenkinsUrl==null)
                        jenkinsUrl = hudsonUrl;
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to load "+file, e);
                }
            }
        } else {
            super.load();
        }

        updateSecureSessionFlag();
    }

    public String getAdminAddress() {
        String v = adminAddress;
        if(v==null)     v = Messages.Mailer_Address_Not_Configured();
        return v;
    }

    public void setAdminAddress(String adminAddress) {
        if(adminAddress.startsWith("\"") && adminAddress.endsWith("\"")) {
            // some users apparently quote the whole thing. Don't konw why
            // anyone does this, but it's a machine's job to forgive human mistake
            adminAddress = adminAddress.substring(1,adminAddress.length()-1);
        }
        this.adminAddress = adminAddress;
        save();
    }

    public String getUrl() {
        return jenkinsUrl;
    }

    public void setUrl(String hudsonUrl) {
        String url = Util.nullify(hudsonUrl);
        if(url!=null && !url.endsWith("/"))
            url += '/';
        this.jenkinsUrl = url;
        save();
        updateSecureSessionFlag();
    }

    /**
     * If the Jenkins URL starts from "https", force the secure session flag
     *
     * @see discussion of this topic in OWASP
     */
    private void updateSecureSessionFlag() {
        try {
            ServletContext context = Jenkins.getInstance().servletContext;
            Method m;
            try {
                m = context.getClass().getMethod("getSessionCookieConfig");
            } catch (NoSuchMethodException x) { // 3.0+
                LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x);
                return;
            }
            Object sessionCookieConfig = m.invoke(context);

            // not exposing session cookie to JavaScript to mitigate damage caused by XSS
            Class scc = Class.forName("javax.servlet.SessionCookieConfig");
            Method setHttpOnly = scc.getMethod("setHttpOnly",boolean.class);
            setHttpOnly.invoke(sessionCookieConfig,true);

            Method setSecure = scc.getMethod("setSecure",boolean.class);
            boolean v = fixNull(jenkinsUrl).startsWith("https");
            setSecure.invoke(sessionCookieConfig,v);
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e);
        }
    }

    @Override
    public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
        req.bindJSON(this,json);
        return true;
    }

    /**
     * Checks the URL in <tt>global.jelly</tt>
     */
    public FormValidation doCheckUrl(@QueryParameter String value) {
        if(value.startsWith("http://localhost"))
            return FormValidation.warning(Messages.Mailer_Localhost_Error());
        return FormValidation.ok();
    }

    public FormValidation doCheckAdminAddress(@QueryParameter String value) {
        try {
            new InternetAddress(value);
            return FormValidation.ok();
        } catch (AddressException e) {
            return FormValidation.error(e.getMessage());
        }
    }

    private static final Logger LOGGER = Logger.getLogger(JenkinsLocationConfiguration.class.getName());
}


text:
package fredboat.db;

import fredboat.commandmeta.MessagingException;

public class DatabaseNotReadyException extends MessagingException {

    DatabaseNotReadyException(String str) {
        super(str);
    }

    DatabaseNotReadyException() {
        super("The database isn't ready yet. The bot might have just started. Please try again in a moment.");
    }
}


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

namespace Microsoft.Azure.Commands.Network.Models
{
    using Newtonsoft.Json;

    public class PSServiceProviderProperties
    {
        [JsonProperty(Order = 1)]
        public string ServiceProviderName { get; set; }

        [JsonProperty(Order = 1)]
        public string PeeringLocation { get; set; }

        [JsonProperty(Order = 1)]
        public int BandwidthInMbps { get; set; }
    }
}


text:
#pragma once

// Local Variables:
// mode: c++
// End:

#include <list>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <cassert>
#include <functional>

typedef unsigned int u32;
class Semaphore {
public:
        inline Semaphore() : cnt(0) {}
        //~Semaphore(); use default
        inline void post() {
                std::lock_guard<std::mutex> lk(lock);
                cnt++;
                if (cnt <= 0)
                        cv.notify_one();
        }
        inline void notify_all() {
                std::lock_guard<std::mutex> lk(lock);
                if (cnt < 0) {
                        cnt = 0;
                        cv.notify_all();
                }
        }
        /*
          return true is no timeout happened, condition satisfied, we get a chance to move
          return false if timeout happened
         */
        inline bool wait(u32 sec) {
                std::unique_lock<std::mutex> lk(lock);
                cnt--;
                if (cnt < 0) {
                        if (sec != 0) {
                                auto r = cv.wait_for(lk, std::chrono::seconds(sec));
                                if (r == std::cv_status::timeout) {
                                        //we are not freed, so we free ourselves
                                        cnt++;
                                        return false;
                                }
                        } else {
                                cv.wait(lk);
                        }
                }
                return true;
        }
private:
        //a semaphore can be implemented using a condition_variable and a lock
        std::mutex lock;
        std::condition_variable cv;
        int cnt;//beging negative means some thread is waiting on the internal
                //condition_variable, otherwise(cnt>=0) means no one is waiting
};

class ThreadPoolExecutor {
public:
        //factory method: create a thread pool with a limited concurrency
        static inline ThreadPoolExecutor *NewFixedThreadPool(u32 nThreads) {
                return new ThreadPoolExecutor(nThreads, nThreads, 0);
        }
        //factory method: create a pool with only 1 single worker thread
        static inline ThreadPoolExecutor *NewSingleThreadExecutor() {
                return new ThreadPoolExecutor(1, 1, 0);
        }
        //factory method: create a pool with unlimited concurrency
        //but usually the OS has a limit, if you add too many task
        //too quickly, you get error from OS telling you that there
        //is not enough resources
        static inline ThreadPoolExecutor *NewCachedThreadPool() {
                return new ThreadPoolExecutor(0, 0xffffffff, 60);//max
        }

        /*
          this is the constructor, usually you do no need to call this unless
          the factory methods above do not fit you

          minSize: minimum number of threads in the pool, if you do not use
          PrestartAll(), then the actual number of threads in pool may be lower
          than this value at initial stage. But the number of threads would grow
          and after a certain period of time, the number of threads would be equal
          or greater than minSize

          maxSize: the maximum number of existing threads in the pool, the number
          of threads in the pool would never execced this value.
          NOTE: you should never specify a maxSize smaller than minSize and
          maxSize must be greater than 0

          alive_sec: keepAlive value of worker thread in seconds. When a thread is
          idle for alive_sec seconds, and the current number of threads is greater
          than minSize, then the idle thread would be killed, the size of pool would
          shrink.
          NOTE: if alive_sec == 0, it means there is no timeout. Idle threads would
          always be kept alive
         */
        ThreadPoolExecutor(u32 minSize, u32 maxSize, u32 alive_sec)
                : min(minSize),
                  max(maxSize),
                  cur(0),
                  act(0),
                  atm(alive_sec),
                  qbd(false),
                  dtm(0),
                  state(RUNNING) {
                          assert(maxSize != 0);
                          assert(minSize <= maxSize);
                          if (minSize > maxSize)
                                  maxSize = minSize;
                          if (maxSize == 0)
                                  maxSize = 1;
                  }
        /*
          destructor, it is guranteed that when this return, all worker threads
          asoociated with this pool are dead.
         */
        ~ThreadPoolExecutor();
        /*return false when already quitting
          it is guranteed that after this call there would be at least
          min threads in the pool
        */
        bool PrestartAllMinThreads();
        /*
          return the number of worker threads in the pool
         */
        u32 GetPoolSize();
        /*
          return the minimum number of threads that should be kept in the pool
          only at initial stage would the actually number of threads be smaller
          than this number
         */
        u32 GetMinPoolSize();
        /*return false when new min is bigger than max or when pool is quitting
         */
        bool SetMinPoolSize(u32 min);
        /*
          return the maximum number of threads that can be kept in the pool
          the actual number of threads should never exceed this value
         */
        u32 GetMaxPoolSize();
        /*
          return false when new min is bigger than max or when pool is quitting
          NOTE:do not call this too often, otherwise there may be performance
          degradation
         */
        bool SetMaxPoolSize(u32 max);
        /*
          return the number of thread currently working
         */
        u32 GetActiveCount();
        /*
          return KeepAliveTime, when a thread is idle for KeepAliveTime and there
          is still no work to do and the current number of threads is larger than
          minimum value, then the thread would be killed. The pool size would shrink
         */
        u32 GetKeepAliveTime();
        /*
          alive_sec == 0 means infinite
         */
        bool SetKeepAliveTime(u32 alive_sec);
        /*
          asap(as soon as possible) measn quit even if work queue is not empty
          otherwise pool threads would quit only when current work queue is empty
          i.e. all works are done
         */
        void Shutdown(bool asap=false);
        /*
          querry whether the pool is shutdown(all worker threads quit), this does
          not gurantee that all pending works are done if you use Shutdown(true)
          to shutdown. But if you use Shutdown(false) to shutdown, it is guranteed
          that when this returns true, all works put into the threads are also done.
         */
        bool IsShutdown();
        /*
          alive_sec is the timeout for this blocking operation, 0 means forever
          this call would block if the pool is still not shutdown(RUNNING or QUITTING).
          NOTE that you can call this on a pool without first calling Shutdown() and
          this call would block until someone else called Shutdown() and everything
          is shutdown.
         */
        bool AwaitTermination(u32 alive_sec);
        /*
          fun is work function.
          use this API to add work into the threadpool request queue
         */
        bool Execute(const std::function<void()> &task);
        bool SetDestructorTimeout(u32 tm);
private:
        std::mutex lock;
        u32 min;//minium number of threads, may not hold true for initial stage
                //when using on demand(not calling PrestartAllMinThreads()
        u32 max;//maximum nubmer of threads, this never would never at any circumstance
                //be exceeded
        u32 cur;//current number of threads
        u32 act;//current number of threads that is working(not idle)
        u32 atm;//alive timeout in seconds
        bool qbd;//quit before all works done
        u32 dtm;//destructor AwaitTermination timeout in seconds , 0 means forever
        enum {RUNNING, QUITTING, DEAD} state;
        std::condition_variable quitCond;//used to implement AwaitTermination()
        Semaphore sem;//used to control thread activity
        //request list
        std::list<std::function<void()> > req_q;
        //worker thread function
        static void InternalWorkerFunction(ThreadPoolExecutor *pool);
        //internally used to add one thread to threadpool
        inline void Add1Thread();
        //make sure that this call is already guarded by a lock
        inline void CommonCleanup();
};


text:
<?php

namespace Zend\Filter;

class DateTimeSelect extends AbstractDateDropdown
{
    /**
     * Year-Month-Day Hour:Min:Sec
     *
     * @var string
     */
    protected $format = '%6$s-%4$s-%1$s %2$s:%3$s:%5$s';

    /**
     * @var int
     */
    protected $expectedInputs = 6;

    /**
     * @param mixed $value
     * @return array|mixed|null|string
     * @throws Exception\RuntimeException
     */
    public function filter($value)
    {
        if (! is_array($value)) {
            // nothing to do
            return $value;
        }

        if ($this->isNullOnEmpty()
            && (
                empty($value['year'])
                || empty($value['month'])
                || empty($value['day'])
                || empty($value['hour'])
                || empty($value['minute'])
                || (isset($value['second']) && empty($value['second']))
            )
        ) {
            return;
        }

        if ($this->isNullOnAllEmpty()
            && (
                empty($value['year'])
                && empty($value['month'])
                && empty($value['day'])
                && empty($value['hour'])
                && empty($value['minute'])
                && (!isset($value['second']) || empty($value['second']))
            )
        ) {
            // Cannot handle this value
            return;
        }

        if (! isset($value['second'])) {
            $value['second'] = '00';
        }

        $this->filterable($value);

        ksort($value);

        $value = vsprintf($this->format, $value);

        return $value;
    }
}


text:
int
main(int argc, char **argv) {

    context_t context = init(argv[1]);
    int ret = get_image(context);
    return 0;
}


text:
package cache

import (
	"errors"
	"time"
)

const CACHE_TTL = 1 * time.Hour

type Cache struct {
	mappings map[string][][]string
	date     time.Time
}

func New() *Cache {
	return &Cache{map[string][][]string{}, time.Now().UTC()}
}

func NewWithTime(cached map[string][][]string, t time.Time) *Cache {
	return &Cache{cached, t}
}

func (c *Cache) Get() (mappings map[string][][]string, err error) {
	mappings = c.mappings
	if c.IsValid() {
		return
	}
	return nil, errors.New("cache is not valid!")
}

func (c *Cache) Update(mappings map[string][][]string) {
	c.mappings = mappings
	c.date = time.Now().UTC()
}

func (c *Cache) IsValid() bool {
	if len(c.mappings) == 0 {
		return false
	}

	expiration := c.date.Add(CACHE_TTL)
	dObj := &expiration
	return dObj.After(time.Now().UTC())
}


text:
import { useEffect, useState } from 'react';
import { ContainerGetter, SortEndHandler, arrayMove } from 'react-sortable-hoc';

import { c } from 'ttag';

import { applyFilters, updateFilterOrder } from '@proton/shared/lib/api/filters';

import { Loader } from '../../components';
import { useApi, useApiWithoutResult, useEventManager, useFeature, useFilters, useNotifications } from '../../hooks';
import { SettingsParagraph, SettingsSection } from '../account';
import { FeatureCode } from '../features';
import ActionsFilterToolbar from './ActionsFilterToolbar';
import FilterSortableList from './FilterSortableList';
import { Filter } from './interfaces';

function FiltersSection() {
    const { feature: applyFiltersFeature } = useFeature(FeatureCode.ApplyFilters);
    const { call } = useEventManager();
    const [filters, loading] = useFilters();
    const orderRequest = useApiWithoutResult(updateFilterOrder);
    const { createNotification } = useNotifications();
    const api = useApi();
    const handleApplyFilter = async (filterId: string) => {
        // Handle Filter API call
        await api(applyFilters([filterId]));

        createNotification({
            text: c('Action').t`Filters are being applied. This might take a few minutes.`,
            type: 'success',
        });
    };

    const [list, setFilters] = useState<Filter[]>(() => filters || []);

    useEffect(() => {
        if (!Array.isArray(filters)) {
            return;
        }
        setFilters(filters);
    }, [filters]);

    const getScrollContainer: ContainerGetter = () => document.querySelector('.main-area') as HTMLElement;

    const onSortEnd: SortEndHandler = async ({ oldIndex, newIndex }) => {
        try {
            const nextFilters: Filter[] = arrayMove(list, oldIndex, newIndex);
            setFilters(nextFilters);

            const filterIds = nextFilters.map(({ ID }) => ID);
            await orderRequest.request(filterIds);
            await call();
        } catch (e: any) {
            setFilters(filters);
        }
    };

    const contentRenderer = () => {
        if (loading) {
            return <Loader />;
        }

        return list.length ? (
            <FilterSortableList
                getContainer={getScrollContainer}
                items={list}
                onSortEnd={onSortEnd}
                onApplyFilter={handleApplyFilter}
                canApplyFilters={applyFiltersFeature?.Value === true}
            />
        ) : null;
    };

    return (
        <SettingsSection>
            <SettingsParagraph>
                {c('FilterSettings')
                    .t`Add a custom filter to automatically perform certain actions, like labeling or archiving messages. Filters can be edited and created directly via Sieve programming language.`}
            </SettingsParagraph>

            <ActionsFilterToolbar />

            {contentRenderer()}
        </SettingsSection>
    );
}

export default FiltersSection;


text:
from werkzeug.security import generate_password_hash, check_password_hash

def hash_pwd(password):
    return generate_password_hash(password)

def check_password(hashed, password):
    return check_password_hash(hashed, password)


text:
package uk.ac.ncl.openlab.intake24.client.survey.rules;

import org.workcraft.gwt.shared.client.Function1;
import org.workcraft.gwt.shared.client.Option;
import uk.ac.ncl.openlab.intake24.client.survey.*;

import static org.workcraft.gwt.shared.client.CollectionUtils.indexOf;

public class SelectUnconfirmedMeal implements SelectionRule {
    @Override
    public Option<Selection> apply(Survey state) {
        int firstUnconfirmedIndex = indexOf(state.meals, new Function1<Meal, Boolean>() {
            @Override
            public Boolean apply(Meal argument) {
                return argument.time.isEmpty();
            }
        });

        if (firstUnconfirmedIndex == -1)
            return new Option.None<Selection>();
        else
            return new Option.Some<Selection>(new Selection.SelectedMeal(firstUnconfirmedIndex, SelectionMode.AUTO_SELECTION));
    }

    @Override
    public String toString() {
        return "Select unconfirmed meal";
    }

    public static WithPriority<SelectionRule> withPriority(int priority) {
        return new WithPriority<SelectionRule>(new SelectUnconfirmedMeal(), priority);
    }
}


text:
package com.amazonaws.services.route53.model;

import com.amazonaws.AmazonServiceException;

/**
 *

 * This error indicates that you've reached the maximum number of hosted
 * zones that can be created for the current AWS account. You can request
 * an increase to the limit on the
 *  Contact Us
 * page.
 *

 */
public class TooManyHostedZonesException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new TooManyHostedZonesException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public TooManyHostedZonesException(String message) {
        super(message);
    }

}


text:
package com.intellij.rt.execution.junit.segments;

import java.io.OutputStream;
import java.io.IOException;

public class EchoOutputStream extends OutputStream {
  private final OutputStream myOut;
  private final OutputStream myEcho;

  public EchoOutputStream(OutputStream out, OutputStream echo) {
    myOut = out;
    myEcho = echo;
  }

  public synchronized void write(int b) throws IOException {
    myOut.write(b);
    myEcho.write(b);
  }
}


text:
#pragma once

namespace stm32plus {
  namespace usb {

    /*
     * Event class for device class control endpoint tx sent
     */

    struct DeviceClassSdkEp0TxSentEvent : UsbEventDescriptor {

      USBD_StatusTypeDef status;

      DeviceClassSdkEp0TxSentEvent()
        : UsbEventDescriptor(EventType::CLASS_EP0_TX_SENT),
          status(USBD_OK) {
      }
    };
  }
}


text:
package com.microsoft.azure.documentdb;

import org.json.JSONObject;

/**
 * Represents a conflict in the version of a particular resource.
 *
 * During rare failure scenarios, conflicts are generated for the documents in transit. Clients can inspect the
 * respective conflict instances  for resources and operations in conflict.
 *
 */
public final class Conflict extends Resource {
    /**
     * Initialize a conflict object.
     */
    public Conflict() {
        super();
    }

    /**
     * Initialize a conflict object from json string.
     *
     * @param jsonString the json string that represents the conflict.
     */
    public Conflict(String jsonString) {
        super(jsonString);
    }

    /**
     * Initialize a conflict object from json object.
     *
     * @param jsonObject the json object that represents the conflict.
     */
    public Conflict(JSONObject jsonObject) {
        super(jsonObject);
    }

    /**
     * Gets the operation kind.
     *
     * @return the operation kind.
     */
    public String getOperationKind() {
        return super.getString(Constants.Properties.OPERATION_TYPE);
    }

    /**
     * Gets the type of the conflicting resource.
     *
     * @return the resource type.
     */
    public String getResouceType() {
        return super.getString(Constants.Properties.RESOURCE_TYPE);
    }
}