text:
namespace mscorlib
{
	namespace System
	{
		namespace Security
		{
			namespace Cryptography
			{

				//Public Methods
				//Get Set Properties Methods
				//	Get/Set:HashName
				mscorlib::System::String  HMACSHA256::get_HashName() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HMAC", 0, NULL, "get_HashName", __native_object__, 0, NULL, NULL, NULL);
					return mscorlib::System::String(__result__);
				}

				void HMACSHA256::set_HashName(mscorlib::System::String  value)
				{
					MonoType *__parameter_types__[1];
					void *__parameters__[1];
					__parameter_types__[0] = Global::GetType(typeid(value).name());
					__parameters__[0] = (MonoObject*)value;
					Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HMAC", 0, NULL, "set_HashName", __native_object__, 1, __parameter_types__, __parameters__, NULL);
				}

				//	Get/Set:Key
				std::vector<mscorlib::System::Byte*>  HMACSHA256::get_Key() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HMAC", 0, NULL, "get_Key", __native_object__, 0, NULL, NULL, NULL);
					MonoArray *__array_ptr__ = (MonoArray*)__result__;
					uintptr_t __array_length__ = mono_array_length(__array_ptr__);
					std::vector<mscorlib::System::Byte*>  __array_result__(__array_length__);
					for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
					{
						MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
						__array_result__.push_back(new mscorlib::System::Byte (__array_item__));
					}
					return __array_result__;
				}

				void HMACSHA256::set_Key(std::vector<mscorlib::System::Byte*>  value)
				{
					MonoType *__parameter_types__[1];
					void *__parameters__[1];
					__parameter_types__[0] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
					__parameters__[0] = Global::FromArray<mscorlib::System::Byte*>(value, typeid(mscorlib::System::Byte).name());
					Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HMAC", 0, NULL, "set_Key", __native_object__, 1, __parameter_types__, __parameters__, NULL);
				}

				//	Get:CanTransformMultipleBlocks
				mscorlib::System::Boolean  HMACSHA256::get_CanTransformMultipleBlocks() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_CanTransformMultipleBlocks", __native_object__, 0, NULL, NULL, NULL);
					return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
				}

				//	Get:CanReuseTransform
				mscorlib::System::Boolean  HMACSHA256::get_CanReuseTransform() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_CanReuseTransform", __native_object__, 0, NULL, NULL, NULL);
					return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
				}

				//	Get:Hash
				std::vector<mscorlib::System::Byte*>  HMACSHA256::get_Hash() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_Hash", __native_object__, 0, NULL, NULL, NULL);
					MonoArray *__array_ptr__ = (MonoArray*)__result__;
					uintptr_t __array_length__ = mono_array_length(__array_ptr__);
					std::vector<mscorlib::System::Byte*>  __array_result__(__array_length__);
					for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
					{
						MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
						__array_result__.push_back(new mscorlib::System::Byte (__array_item__));
					}
					return __array_result__;
				}

				//	Get:HashSize
				mscorlib::System::Int32  HMACSHA256::get_HashSize() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_HashSize", __native_object__, 0, NULL, NULL, NULL);
					return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
				}

				//	Get:InputBlockSize
				mscorlib::System::Int32  HMACSHA256::get_InputBlockSize() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_InputBlockSize", __native_object__, 0, NULL, NULL, NULL);
					return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
				}

				//	Get:OutputBlockSize
				mscorlib::System::Int32  HMACSHA256::get_OutputBlockSize() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_OutputBlockSize", __native_object__, 0, NULL, NULL, NULL);
					return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
				}

			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;  // For Debug.Assert
using System.Windows.Threading;
using System.Threading;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation; // For Storyboard support
using System.Windows.Markup;
using System.Security.Permissions;
using System.IO;
using MS.Utility;
using MS.Internal;
using System;

#pragma warning disable 1634, 1691  // suppressing PreSharp warnings

namespace System.Windows
{
    ///
    ///     Styling and Templating
    ///
    [Localizability(LocalizationCategory.Ignore)]
    [DictionaryKeyProperty("TargetType")]
    [ContentProperty("Setters")]
    public class Style : DispatcherObject, INameScope, IAddChild, ISealable, IHaveResources, IQueryAmbient
    {
        static Style()
        {
            // Register for the "alternative Expression storage" feature, since
            // we store Expressions in per-instance StyleData.
            StyleHelper.RegisterAlternateExpressionStorage();
        }

        ///
        ///     Style construction
        ///
        public Style()
        {
            GetUniqueGlobalIndex();
        }

        ///
        ///     Style construction
        ///
        /// <param name="targetType">Type in which Style will be applied</param>
        public Style(Type targetType)
        {
            TargetType = targetType;

            GetUniqueGlobalIndex();
        }

        ///
        ///     Style construction
        ///
        /// <param name="targetType">Type in which Style will be applied</param>
        /// <param name="basedOn">Style to base this Style on</param>
        public Style(Type targetType, Style basedOn)
        {
            TargetType = targetType;
            BasedOn = basedOn;

            GetUniqueGlobalIndex();
        }

        #region INameScope
        ///
        /// Registers the name - Context combination
        ///
        /// <param name="name">Name to register</param>
        /// <param name="scopedElement">Element where name is defined</param>
        public void RegisterName(string name, object scopedElement)
        {
            // Verify Context Access
            VerifyAccess();

            _nameScope.RegisterName(name, scopedElement);
        }

        ///
        /// Unregisters the name - element combination
        ///
        /// <param name="name">Name of the element</param>
        public void UnregisterName(string name)
        {
            // Verify Context Access
            VerifyAccess();

            _nameScope.UnregisterName(name);
        }

        ///
        /// Find the element given name
        ///
        /// <param name="name">Name of the element</param>
        object INameScope.FindName(string name)
        {
            // Verify Context Access
            VerifyAccess();

            return _nameScope.FindName(name);
        }

        private NameScope _nameScope = new NameScope();
        #endregion IIdScope

        ///
        /// Each Style gets its own unique index used for Style.GetHashCode
        ///
        private void GetUniqueGlobalIndex()
        {
            lock (Synchronized)
            {
                // Setup unqiue global index
                StyleInstanceCount++;
                GlobalIndex = StyleInstanceCount;
            }
        }

        ///
        ///     Style mutability state
        ///
        /// <remarks>
        ///     A style is sealed when another style is basing on it, or,
        ///     when it's applied
        /// </remarks>
        public bool IsSealed
        {
            get
            {
                // Verify Context Access
                VerifyAccess();

                return _sealed;
            }
        }

        ///
        ///     Type that this style is intended
        ///
        /// <remarks>
        ///     By default, the target type is FrameworkElement
        /// </remarks>
        [Ambient]
        [Localizability(LocalizationCategory.NeverLocalize)]
        public Type TargetType
        {
            get
            {
                // Verify Context Access
                VerifyAccess();

                return _targetType;
            }

            set
            {
                // Verify Context Access
                VerifyAccess();

                if (_sealed)
                {
                    throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "Style"));
                }

                if( value == null )
                {
                    throw new ArgumentNullException("value");
                }

                if (!typeof(FrameworkElement).IsAssignableFrom(value) &&
                    !typeof(FrameworkContentElement).IsAssignableFrom(value) &&
                    !(DefaultTargetType == value))
                {
                    #pragma warning suppress 6506 // value is obviously not null
                    throw new ArgumentException(SR.Get(SRID.MustBeFrameworkDerived, value.Name));
                }

                _targetType = value;

                SetModified(TargetTypeID);
            }
        }

        ///
        ///     Style to base on
        ///
        [DefaultValue(null)]
        [Ambient]
        public Style BasedOn
        {
            get
            {
                // Verify Context Access
                VerifyAccess();

                return _basedOn;
            }
            set
            {
                // Verify Context Access
                VerifyAccess();

                if (_sealed)
                {
                    throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "Style"));
                }

                if( value == this )
                {
                    // Basing on self is not allowed.  This is a degenerate case
                    //  of circular reference chain, the full check for circular
                    //  reference is done in Seal().
                    throw new ArgumentException(SR.Get(SRID.StyleCannotBeBasedOnSelf));
                }

                _basedOn = value;

                SetModified(BasedOnID);
            }
        }

        ///
        ///     Visual triggers
        ///
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public TriggerCollection Triggers
        {
            get
            {
                // Verify Context Access
                VerifyAccess();

                if (_visualTriggers == null)
                {
                    _visualTriggers = new TriggerCollection();

                    // If the style has been sealed prior to this the newly
                    // created TriggerCollection also needs to be sealed
                    if (_sealed)
                    {
                        _visualTriggers.Seal();
                    }
                }
                return _visualTriggers;
            }
        }

        ///
        ///     The collection of property setters for the target type
        ///

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public SetterBaseCollection Setters
        {
            get
            {
                // Verify Context Access
                VerifyAccess();

                if( _setters == null )
                {
                    _setters = new SetterBaseCollection();

                    // If the style has been sealed prior to this the newly
                    // created SetterBaseCollection also needs to be sealed
                    if (_sealed)
                    {
                        _setters.Seal();
                    }
                }
                return _setters;
            }
        }

        ///
        ///     The collection of resources that can be
        ///     consumed by the container and its sub-tree.
        ///
        [Ambient]
        public ResourceDictionary Resources
        {
            get
            {
                // Verify Context Access
                VerifyAccess();

                if( _resources == null )
                {
                    _resources = new ResourceDictionary();

                    // A Style ResourceDictionary can be accessed across threads
                    _resources.CanBeAccessedAcrossThreads = true;

                    // If the style has been sealed prior to this the newly
                    // created ResourceDictionary also needs to be sealed
                    if (_sealed)
                    {
                        _resources.IsReadOnly = true;
                    }
                }
                return _resources;
            }
            set
            {
                // Verify Context Access
                VerifyAccess();

                if( _sealed )
                {
                    throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "Style"));
                }

                _resources = value;

                if (_resources != null)
                {
                    // A Style ResourceDictionary can be accessed across threads
                    _resources.CanBeAccessedAcrossThreads = true;
                }
            }
        }

        ResourceDictionary IHaveResources.Resources
        {
            get { return Resources; }
            set { Resources = value; }
        }

        ///
        ///     Tries to find a Reosurce for the given resourceKey in the current
        ///     style's ResourceDictionary or the basedOn style's ResourceDictionary
        ///     in that order.
        ///
        internal object FindResource(object resourceKey, bool allowDeferredResourceReference, bool mustReturnDeferredResourceReference)
        {
            if ((_resources != null) && _resources.Contains(resourceKey))
            {
                bool canCache;
                return _resources.FetchResource(resourceKey, allowDeferredResourceReference, mustReturnDeferredResourceReference, out canCache);
            }
            if (_basedOn != null)
            {
                return _basedOn.FindResource(resourceKey, allowDeferredResourceReference, mustReturnDeferredResourceReference);
            }
            return DependencyProperty.UnsetValue;
        }

        internal ResourceDictionary FindResourceDictionary(object resourceKey)
        {
            Debug.Assert(resourceKey != null, "Argument cannot be null");
            if (_resources != null && _resources.Contains(resourceKey))
            {
                return _resources;
            }
            if (_basedOn != null)
            {
                return _basedOn.FindResourceDictionary(resourceKey);
            }
            return null;
        }

        bool IQueryAmbient.IsAmbientPropertyAvailable(string propertyName)
        {
            // We want to make sure that StaticResource resolution checks the .Resources
            // Ie.  The Ambient search should look at Resources if it is set.
            // Even if it wasn't set from XAML (eg. the Ctor (or derived Ctor) added stuff)
            switch (propertyName)
            {
                case "Resources":
                    if (_resources == null)
                    {
                        return false;
                    }
                    break;
                case "BasedOn":
                    if (_basedOn == null)
                    {
                        return false;
                    }
                    break;
            }
            return true;
        }

        ///
        /// This method is called to Add a Setter object as a child of the Style.
        /// This method is used primarily by the parser to set style properties and events.
        ///
        ///<param name="value">
        /// The object to add as a child; it must be a SetterBase subclass.
        ///</param>
        void IAddChild.AddChild (Object value)
        {
            // Verify Context Access
            VerifyAccess();

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            SetterBase sb = value as SetterBase;

            if (sb == null)
            {
                throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(SetterBase)), "value");
            }

            Setters.Add(sb);
        }

        ///
        /// This method is called by the parser when text appears under the tag in markup.
        /// As default Styles do not support text, calling this method has no effect.
        ///
        ///<param name="text">
        /// Text to add as a child.
        ///</param>
        void IAddChild.AddText (string text)
        {
            // Verify Context Access
            VerifyAccess();

            XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this);
        }

        ///
        ///     Given a set of values for the PropertyValue struct, put that in
        /// to the PropertyValueList, overwriting any existing entry.
        ///
        private void UpdatePropertyValueList(
            DependencyProperty dp,
            PropertyValueType valueType,
            object value)
        {
            // Check for existing value on dp
            int existingIndex = -1;
            for( int i = 0; i < PropertyValues.Count; i++ )
            {
                if( PropertyValues[i].Property == dp )
                {
                    existingIndex = i;
                    break;
                }
            }

            if( existingIndex >= 0 )
            {
                // Overwrite existing value for dp
                PropertyValue propertyValue = PropertyValues[existingIndex];
                propertyValue.ValueType = valueType;
                propertyValue.ValueInternal = value;
                // Put back modified struct
                PropertyValues[existingIndex] = propertyValue;
            }
            else
            {
                // Store original data
                PropertyValue propertyValue = new PropertyValue();
                propertyValue.ValueType = valueType;
                propertyValue.ChildName = StyleHelper.SelfName;
                propertyValue.Property = dp;
                propertyValue.ValueInternal = value;

                PropertyValues.Add(propertyValue);
            }
        }

        internal void CheckTargetType(object element)
        {
            // In the most common case TargetType is Default
            // and we can avoid a call to IsAssignableFrom() who's performance is unknown.
            if(DefaultTargetType == TargetType)
                return;

            Type elementType = element.GetType();
            if(!TargetType.IsAssignableFrom(elementType))
            {
                throw new InvalidOperationException(SR.Get(SRID.StyleTargetTypeMismatchWithElement,
                                                    this.TargetType.Name,
                                                    elementType.Name));
            }
        }

        ///
        /// This Style and all factories/triggers are now immutable
        ///
        public void Seal()
        {
            // Verify Context Access
            VerifyAccess();

            // 99% case - Style is already sealed.
            if (_sealed)
            {
                return;
            }

            // Most parameter checking is done as "upstream" as possible, but some
            //  can't be checked until Style is sealed.
            if (_targetType == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.NullPropertyIllegal, "TargetType"));
            }

            if (_basedOn != null)
            {
                if(DefaultTargetType != _basedOn.TargetType &&
                    !_basedOn.TargetType.IsAssignableFrom(_targetType))
                {
                    throw new InvalidOperationException(SR.Get(SRID.MustBaseOnStyleOfABaseType, _targetType.Name));
                }
            }

            // Seal setters
            if (_setters != null)
            {
                _setters.Seal();
            }

            // Seal triggers
            if (_visualTriggers != null)
            {
                _visualTriggers.Seal();
            }

            // Will throw InvalidOperationException if we find a loop of
            //  BasedOn references.  (A.BasedOn = B, B.BasedOn = C, C.BasedOn = A)
            CheckForCircularBasedOnReferences();

            // Seal BasedOn Style chain
            if (_basedOn != null)
            {
                _basedOn.Seal();
            }

            // Seal the ResourceDictionary
            if (_resources != null)
            {
                _resources.IsReadOnly = true;
            }

            //
            // Build shared tables
            //

            // Process all Setters set on the selfStyle. This stores all the property
            // setters on the current styles into PropertyValues list, so it can be used
            // by ProcessSelfStyle in the next step. The EventSetters for the current
            // and all the basedOn styles are merged into the EventHandlersStore on the
            // current style.
            ProcessSetters(this);

            // Add an entry in the EventDependents list for
            // the TargetType's EventHandlersStore. Notice
            // that the childIndex is 0.
            StyleHelper.AddEventDependent(0, this.EventHandlersStore, ref EventDependents);

            // Process all PropertyValues (all are "Self") in the Style
            // chain (base added first)
            ProcessSelfStyles(this);

            // Process all TriggerBase PropertyValues ("Self" triggers
            // and child triggers) in the Style chain last (highest priority)
            ProcessVisualTriggers(this);

            // Sort the ResourceDependents, to help avoid duplicate invalidations
            StyleHelper.SortResourceDependents(ref ResourceDependents);

            // All done, seal self and call it a day.
            _sealed = true;

            // Remove thread affinity so it can be accessed across threads
            DetachFromDispatcher();
        }

        ///
        ///     This method checks to see if the BasedOn hierarchy contains
        /// a loop in the chain of references.
        ///
        /// <remarks>
        /// Classic "when did we enter the cycle" problem where we don't know
        ///  what to start remembering and what to check against.  Brute-
        ///  force approach here is to remember everything with a stack
        ///  and do a linear comparison through everything.  Since the Style
        ///  BasedOn hierarchy is not expected to be large, this should be OK.
        /// </remarks>
        private void CheckForCircularBasedOnReferences()
        {
            Stack basedOnHierarchy = new Stack(10);  // 10 because that's the default value (see MSDN) and the perf team wants us to specify something.
            Style latestBasedOn = this;

            while( latestBasedOn != null )
            {
                if( basedOnHierarchy.Contains( latestBasedOn ) )
                {
                    // Uh-oh.  We've seen this Style before.  This means
                    //  the BasedOn hierarchy contains a loop.
                    throw new InvalidOperationException(SR.Get(
                        SRID.StyleBasedOnHasLoop));

                    // Debugging note: If we stop here, the basedOnHierarchy
                    //  object is still alive and we can browse through it to
                    //  see what we've explored.  (This does not apply if
                    //  somebody catches this exception and re-throws.)
                }

                // Haven't seen it, push on stack and go to next level.
                basedOnHierarchy.Push( latestBasedOn );
                latestBasedOn = latestBasedOn.BasedOn;
            }

            return;
        }

        // Iterates through the setters collection and adds the EventSetter information into
        // an EventHandlersStore for easy and fast retrieval during event routing. Also adds
        // an entry in the EventDependents list for EventhandlersStore holding the TargetType's
        // events.
        private void ProcessSetters(Style style)
        {
            // Walk down to bottom of based-on chain
            if (style == null)
            {
                return;
            }

            style.Setters.Seal(); // Does not mark individual setters as sealed, that's up to the loop below.

            // On-demand create the PropertyValues list, so that we can specify the right size.

            if(PropertyValues.Count == 0)
            {
                PropertyValues = new FrugalStructList<System.Windows.PropertyValue>(style.Setters.Count);
            }

            // Add EventSetters to local EventHandlersStore
            for (int i = 0; i < style.Setters.Count; i++)
            {
                SetterBase setterBase = style.Setters[i];
                Debug.Assert(setterBase != null, "Setter collection must contain non-null instances of SetterBase");

                // Setters are folded into the PropertyValues table only for the current style. The
                // processing of BasedOn Style properties will occur in subsequent call to ProcessSelfStyle
                Setter setter = setterBase as Setter;
                if (setter != null)
                {
                    // Style Setters are not allowed to have a child target name - since there are no child nodes in a Style.
                    if( setter.TargetName != null )
                    {
                        throw new InvalidOperationException(SR.Get(SRID.SetterOnStyleNotAllowedToHaveTarget, setter.TargetName));
                    }

                    if (style == this)
                    {
                        DynamicResourceExtension dynamicResource = setter.ValueInternal as DynamicResourceExtension;
                        if (dynamicResource == null)
                        {
                            UpdatePropertyValueList( setter.Property, PropertyValueType.Set, setter.ValueInternal );
                        }
                        else
                        {
                            UpdatePropertyValueList( setter.Property, PropertyValueType.Resource, dynamicResource.ResourceKey );
                        }
                    }
                }
                else
                {

                    Debug.Assert(setterBase is EventSetter,
                                 "Unsupported SetterBase subclass in style triggers ({0})", setterBase.GetType().ToString());

                    // Add this to the _eventHandlersStore

                    EventSetter eventSetter = (EventSetter)setterBase;
                    if (_eventHandlersStore == null)
                    {
                        _eventHandlersStore = new EventHandlersStore();
                    }
                    _eventHandlersStore.AddRoutedEventHandler(eventSetter.Event, eventSetter.Handler, eventSetter.HandledEventsToo);

                    SetModified(HasEventSetter);

                    // If this event setter watches the loaded/unloaded events, set the optimization
                    // flag.

                    if (eventSetter.Event == FrameworkElement.LoadedEvent || eventSetter.Event == FrameworkElement.UnloadedEvent)
                    {
                        _hasLoadedChangeHandler = true;
                    }

                }
            }

            // Process EventSetters on based on style so they get merged
            // into the EventHandlersStore for the current style.
            ProcessSetters(style._basedOn);
        }

        private void ProcessSelfStyles(Style style)
        {
            // Walk down to bottom of based-on chain
            if (style == null)
            {
                return;
            }

            ProcessSelfStyles(style._basedOn);

            // Merge in "self" PropertyValues while walking back up the tree
            // "Based-on" style "self" rules are always added first (lower priority)
            for (int i = 0; i < style.PropertyValues.Count; i++)
            {
                PropertyValue propertyValue = style.PropertyValues[i];

                StyleHelper.UpdateTables(ref propertyValue, ref ChildRecordFromChildIndex,
                    ref TriggerSourceRecordFromChildIndex, ref ResourceDependents, ref _dataTriggerRecordFromBinding,
                    null /*_childIndexFromChildID*/, ref _hasInstanceValues);

                // Track properties on the container that are being driven by
                // the Style so that they can be invalidated during style changes
                StyleHelper.AddContainerDependent(propertyValue.Property, false /*fromVisualTrigger*/, ref ContainerDependents);
            }
        }

        private void ProcessVisualTriggers(Style style)
        {
            // Walk down to bottom of based-on chain
            if (style == null)
            {
                return;
            }

            ProcessVisualTriggers(style._basedOn);

            if (style._visualTriggers != null)
            {
                // Merge in "self" and child TriggerBase PropertyValues while walking
                // back up the tree. "Based-on" style rules are always added first
                // (lower priority)
                int triggerCount = style._visualTriggers.Count;
                for (int i = 0; i < triggerCount; i++)
                {
                    TriggerBase trigger = style._visualTriggers[i];

                    // Set things up to handle Setter values
                    for (int j = 0; j < trigger.PropertyValues.Count; j++)
                    {
                        PropertyValue propertyValue = trigger.PropertyValues[j];

                        // Check for trigger rules that act on container
                        if (propertyValue.ChildName != StyleHelper.SelfName)
                        {
                            throw new InvalidOperationException(SR.Get(SRID.StyleTriggersCannotTargetTheTemplate));
                        }

                        TriggerCondition[] conditions = propertyValue.Conditions;
                        for (int k=0; k<conditions.Length; k++)
                        {
                            if( conditions[k].SourceName != StyleHelper.SelfName )
                            {
                                throw new InvalidOperationException(SR.Get(SRID.TriggerOnStyleNotAllowedToHaveSource, conditions[k].SourceName));
                            }
                        }

                        // Track properties on the container that are being driven by
                        // the Style so that they can be invalidated during style changes
                        StyleHelper.AddContainerDependent(propertyValue.Property, true /*fromVisualTrigger*/, ref this.ContainerDependents);

                        StyleHelper.UpdateTables(ref propertyValue, ref ChildRecordFromChildIndex,
                            ref TriggerSourceRecordFromChildIndex, ref ResourceDependents, ref _dataTriggerRecordFromBinding,
                            null /*_childIndexFromChildID*/, ref _hasInstanceValues);
                    }

                    // Set things up to handle TriggerActions
                    if( trigger.HasEnterActions || trigger.HasExitActions )
                    {
                        if( trigger is Trigger )
                        {
                            StyleHelper.AddPropertyTriggerWithAction( trigger, ((Trigger)trigger).Property, ref this.PropertyTriggersWithActions );
                        }
                        else if( trigger is MultiTrigger )
                        {
                            MultiTrigger multiTrigger = (MultiTrigger)trigger;
                            for( int k = 0; k < multiTrigger.Conditions.Count; k++ )
                            {
                                Condition triggerCondition = multiTrigger.Conditions[k];

                                StyleHelper.AddPropertyTriggerWithAction( trigger, triggerCondition.Property, ref this.PropertyTriggersWithActions );
                            }
                        }
                        else if( trigger is DataTrigger )
                        {
                            StyleHelper.AddDataTriggerWithAction( trigger, ((DataTrigger)trigger).Binding, ref this.DataTriggersWithActions );
                        }
                        else if( trigger is MultiDataTrigger )
                        {
                            MultiDataTrigger multiDataTrigger = (MultiDataTrigger)trigger;
                            for( int k = 0; k < multiDataTrigger.Conditions.Count; k++ )
                            {
                                Condition dataCondition = multiDataTrigger.Conditions[k];

                                StyleHelper.AddDataTriggerWithAction( trigger, dataCondition.Binding, ref this.DataTriggersWithActions );
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException(SR.Get(SRID.UnsupportedTriggerInStyle, trigger.GetType().Name));
                        }
                    }

                    // Set things up to handle EventTrigger
                    EventTrigger eventTrigger = trigger as EventTrigger;
                    if( eventTrigger != null )
                    {
                        if( eventTrigger.SourceName != null && eventTrigger.SourceName.Length > 0 )
                        {
                            throw new InvalidOperationException(SR.Get(SRID.EventTriggerOnStyleNotAllowedToHaveTarget, eventTrigger.SourceName));
                        }

                        StyleHelper.ProcessEventTrigger(eventTrigger,
                                                        null /*_childIndexFromChildID*/,
                                                        ref _triggerActions,
                                                        ref EventDependents,
                                                        null /*_templateFactoryRoot*/,
                                                        null,
                                                        ref _eventHandlersStore,
                                                        ref _hasLoadedChangeHandler);
                    }
                }
            }
        }

        ///
        ///     Serves as a hash function for a particular type, suitable for use in
        ///     hashing algorithms and data structures like a hash table
        ///
        /// <returns>The Style's GlobalIndex</returns>
        public override int GetHashCode()
        {
            // Verify Context Access
            VerifyAccess();

            return GlobalIndex;
        }

        #region ISealable

        ///
        /// Can this style be sealed
        ///
        bool ISealable.CanSeal
        {
            get { return true; }
        }

        ///
        /// Is this style sealed
        ///
        bool ISealable.IsSealed
        {
            get { return IsSealed; }
        }

        ///
        /// Seal this style
        ///
        void ISealable.Seal()
        {
            Seal();
        }

        #endregion ISealable

        internal bool HasResourceReferences
        {
            get
            {
                return ResourceDependents.Count > 0;
            }
        }

        ///
        ///     Store all the event handlers for this Style TargetType
        ///
        internal EventHandlersStore EventHandlersStore
        {
            get { return _eventHandlersStore; }
        }

        ///
        ///     Does the current style or any of its template children
        ///     have any event setters OR event triggers
        ///
        internal bool HasEventDependents
        {
            get
            {
                return (EventDependents.Count > 0);
            }
        }

        ///
        ///     Does the current style or any of its template children
        ///     have event setters, ignoring event triggers.
        ///
        internal bool HasEventSetters
        {
            get
            {
                return IsModified(HasEventSetter);
            }
        }

        //
        //  Says if this style contains any per-instance values
        //
        internal bool HasInstanceValues
        {
            get { return _hasInstanceValues; }
        }

        //
        // Says if we have anything listening for the Loaded or Unloaded
        // event (used for an optimization in FrameworkElement).
        //

        internal bool HasLoadedChangeHandler
        {
            get { return _hasLoadedChangeHandler; }
            set { _hasLoadedChangeHandler = value; }
        }

        // Special equality check that takes into account 'null'
        private static bool IsEqual(object a, object b)
        {
            return (a != null) ? a.Equals(b) : (b == null);
        }

        internal bool IsBasedOnModified { get { return IsModified(BasedOnID); } }

        private EventHandlersStore _eventHandlersStore = null;

        private bool _sealed;
        private bool _hasInstanceValues;

        internal static readonly Type DefaultTargetType = typeof(IFrameworkInputElement);

        private bool _hasLoadedChangeHandler;

        private Type _targetType = DefaultTargetType;
        private Style _basedOn;

        private TriggerCollection _visualTriggers = null;

        private SetterBaseCollection _setters = null;

        // Holds resources that are applicable to the container
        // of this style and its sub-tree.
        internal ResourceDictionary _resources = null;

        /* property */ internal int GlobalIndex;

        // Style tables
        // Synchronized (write locks, lock-free reads): Covered by Style instance lock
        /* property */ internal FrugalStructList<ChildRecord> ChildRecordFromChildIndex = new FrugalStructList<ChildRecord>(); // Indexed by Child.ChildIndex
        // Synchronized (write locks, lock-free reads): Covered by Style instance lock

        //
        // Shared tables used during OnTriggerSourcePropertyInvalidated
        //
        internal FrugalStructList<ItemStructMap<TriggerSourceRecord>> TriggerSourceRecordFromChildIndex = new FrugalStructList<ItemStructMap<TriggerSourceRecord>>();
        // Dictionary of property triggers that have TriggerActions, keyed via DP.GlobalIndex affecting those triggers.
        //  Each trigger can be listed multiple times, if they are dependent on multiple properties.
        internal FrugalMap PropertyTriggersWithActions;

        // Original Style data (not including based-on data)
        // Synchronized (write locks, lock-free reads): Covered by Style instance lock
        /* property */ internal FrugalStructList<System.Windows.PropertyValue> PropertyValues = new FrugalStructList<System.Windows.PropertyValue>();

        // Properties driven on the container (by the Style) that should be
        // invalidated when the style gets applied/unapplied. These properties
        // could have been set via Style.SetValue or TriggerBase.SetValue
        // Synchronized (write locks, lock-free reads): Covered by Style instance lock
        /* property */ internal FrugalStructList<ContainerDependent> ContainerDependents = new FrugalStructList<ContainerDependent>();

        // Properties driven by a resource that should be invalidated
        // when a resource dictionary changes
        // Synchronized (write locks, lock-free reads): Covered by Style instance lock
        /* property */ internal FrugalStructList<ChildPropertyDependent> ResourceDependents = new FrugalStructList<ChildPropertyDependent>();

        // Events driven by a this style. An entry for every childIndex that has associated events.
        // childIndex '0' is used to represent events set on the style's TargetType. This data-structure
        // will be frequently looked up during event routing.
        // Synchronized (write locks, lock-free reads): Covered by Style instance lock
        /* property */ internal ItemStructList<ChildEventDependent> EventDependents = new ItemStructList<ChildEventDependent>(1);

        // Used by EventTrigger: Maps a RoutedEventID to a set of TriggerAction objects
        //  to be performed.
        internal HybridDictionary _triggerActions = null;

        // Data trigger information.  An entry for each Binding that appears in a
        // condition of a data trigger.
        // Synchronized: Covered by Style instance
        internal HybridDictionary _dataTriggerRecordFromBinding;

        // An entry for each Binding that appears in a DataTrigger with EnterAction or ExitAction
        //  This overlaps but should not be the same as _dataTriggerRecordFromBinding above:
        //   A DataTrigger can have Setters but no EnterAction/ExitAction.  (The reverse can also be true.)
        internal HybridDictionary DataTriggersWithActions = null;

        // Unique index for every instance of Style
        // Synchronized: Covered by Style.Synchronized
        private static int StyleInstanceCount = 0;

        // Global, cross-object synchronization
        internal static object Synchronized = new object();

        private const int TargetTypeID = 0x01;
        internal const int BasedOnID    = 0x02;

        // Using the modified flags to note whether we have an EventSetter.
        private const int HasEventSetter = 0x10;

        private int _modified = 0;

        private void SetModified(int id) { _modified |= id; }
        internal bool IsModified(int id) { return (id & _modified) != 0; }
    }
}


text:
package com.google.auto.value.processor;

import static com.google.auto.common.MoreStreams.toImmutableMap;

import com.google.auto.common.MoreElements;
import com.google.auto.common.MoreTypes;
import com.google.common.base.Equivalence;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.Elements;
import javax.lang.model.util.SimpleTypeVisitor8;
import javax.lang.model.util.Types;

/** Methods for handling type variables. */
final class TypeVariables {
  private TypeVariables() {}

  /**
   * Returns a map from methods to return types, where the return types are not necessarily the
   * original return types of the methods. Consider this example:
   *
   *

   * @AutoValue class {@code Foo<T>} {
   *   abstract T getFoo();
   *
   *   @AutoValue.Builder
   *   abstract class {@code Builder<T>} {
   *     abstract Builder setFoo(T t);
   *     abstract {@code Foo<T>} build();
   *   }
   * }
   *

   *
   * We want to be able to check that the parameter type of {@code setFoo} is the same as the return
   * type of {@code getFoo}. But in fact it isn't, because the {@code T} of {@code Foo<T>} is not
   * the same as the {@code T} of {@code Foo.Builder<T>}. So we create a parallel {@code Foo<T>}
   * where the {@code T} is the one from {@code Foo.Builder<T>}. That way the types do
   * correspond. This method then returns the return types of the given methods as they appear in
   * that parallel class, meaning the type given for {@code getFoo()} is the {@code T} of {@code
   * Foo.Builder<T>}.
   *
   *
We do the rewrite this way around (applying the type parameter from {@code Foo.Builder} to
   * {@code Foo}) because if we hit one of the historical Eclipse bugs with {@link Types#asMemberOf}
   * then {@link EclipseHack#methodReturnType} can use fallback logic, which only works for methods
   * with no arguments.
   *
   * @param methods the methods whose return types are to be rewritten.
   * @param sourceType the class containing those methods ({@code Foo} in the example).
   * @param targetType the class to translate the methods into ({@code Foo.Builder<T>}) in the
   *     example.
   */
  static ImmutableMap<ExecutableElement, TypeMirror> rewriteReturnTypes(
      Elements elementUtils,
      Types typeUtils,
      Collection<ExecutableElement> methods,
      TypeElement sourceType,
      TypeElement targetType) {
    List<? extends TypeParameterElement> sourceTypeParameters = sourceType.getTypeParameters();
    List<? extends TypeParameterElement> targetTypeParameters = targetType.getTypeParameters();
    Preconditions.checkArgument(
        sourceTypeParameters.toString().equals(targetTypeParameters.toString()),
        "%s != %s",
        sourceTypeParameters,
        targetTypeParameters);
    // What we're doing is only valid if the type parameters are "the same". The check here even
    // requires the names to be the same. The logic would still work without that, but we impose
    // that requirement elsewhere and it means we can check in this simple way.
    EclipseHack eclipseHack = new EclipseHack(elementUtils, typeUtils);
    TypeMirror[] targetTypeParameterMirrors = new TypeMirror[targetTypeParameters.size()];
    for (int i = 0; i < targetTypeParameters.size(); i++) {
      targetTypeParameterMirrors[i] = targetTypeParameters.get(i).asType();
    }
    DeclaredType parallelSource = typeUtils.getDeclaredType(sourceType, targetTypeParameterMirrors);
    return methods.stream()
        .collect(toImmutableMap(m -> m, m -> eclipseHack.methodReturnType(m, parallelSource)));
  }

  /**
   * Tests whether a given parameter can be given to a static method like {@code
   * ImmutableMap.copyOf} to produce a value that can be assigned to the given target type.
   *
   *
For example, suppose we have this method in {@code ImmutableMap}:

   * {@code static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V>)}

   * and we want to know if we can do this:
   *
   *

   * {@code ImmutableMap<String, Integer> actualParameter = ...;}
   * {@code ImmutableMap<String, Number> target = ImmutableMap.copyOf(actualParameter);}
   *

   *
   * We will infer {@code K=String}, {@code V=Number} based on the target type, and then rewrite the
   * formal parameter type from

   * {@code Map<? extends K, ? extends V>} to

   * {@code Map<? extends String, ? extends Number>}. Then we can check whether {@code
   * actualParameter} is assignable to that.
   *
   *
The logic makes some simplifying assumptions, which are met for the {@code copyOf} and
   * {@code of} methods that we use this for. The method must be static, it must have exactly one
   * parameter, and it must have type parameters without bounds that are the same as the type
   * parameters of its return type. We can see that these assumptions are met for the {@code
   * ImmutableMap.copyOf} example above.
   */
  static boolean canAssignStaticMethodResult(
      ExecutableElement method,
      TypeMirror actualParameterType,
      TypeMirror targetType,
      Types typeUtils) {
    if (!targetType.getKind().equals(TypeKind.DECLARED)
        || !method.getModifiers().contains(Modifier.STATIC)
        || method.getParameters().size() != 1) {
      return false;
    }
    List<? extends TypeParameterElement> typeParameters = method.getTypeParameters();
    List<? extends TypeMirror> targetTypeArguments =
        MoreTypes.asDeclared(targetType).getTypeArguments();
    if (typeParameters.size() != targetTypeArguments.size()) {
      return false;
    }
    Map<Equivalence.Wrapper<TypeVariable>, TypeMirror> typeVariables = new LinkedHashMap<>();
    for (int i = 0; i < typeParameters.size(); i++) {
      TypeVariable v = MoreTypes.asTypeVariable(typeParameters.get(i).asType());
      typeVariables.put(MoreTypes.equivalence().wrap(v), targetTypeArguments.get(i));
    }
    Function<TypeVariable, TypeMirror> substitute =
        v -> typeVariables.get(MoreTypes.equivalence().wrap(v));
    TypeMirror formalParameterType = method.getParameters().get(0).asType();
    SubstitutionVisitor substitutionVisitor = new SubstitutionVisitor(substitute, typeUtils);
    TypeMirror substitutedParameterType = substitutionVisitor.visit(formalParameterType, null);
    if (substitutedParameterType.getKind().equals(TypeKind.WILDCARD)) {
      // If the target type is Optional<? extends Foo> then <T> T Optional.of(T) will give us
      // ? extends Foo here, and typeUtils.isAssignable will return false. But we can in fact
      // give a Foo as an argument, so we just replace ? extends Foo with Foo.
      WildcardType wildcard = MoreTypes.asWildcard(substitutedParameterType);
      if (wildcard.getExtendsBound() != null) {
        substitutedParameterType = wildcard.getExtendsBound();
      }
    }
    return typeUtils.isAssignable(actualParameterType, substitutedParameterType);
  }

  static TypeMirror substituteTypeVariables(
      TypeMirror input, Function<TypeVariable, TypeMirror> substitute, Types typeUtils) {
    SubstitutionVisitor substitutionVisitor = new SubstitutionVisitor(substitute, typeUtils);
    return substitutionVisitor.visit(input, null);
  }

  /**
   * Rewrites types such that references to type variables in the given map are replaced by the
   * values of those variables.
   */
  private static class SubstitutionVisitor extends SimpleTypeVisitor8<TypeMirror, Void> {
    private final Function<TypeVariable, TypeMirror> substitute;
    private final Types typeUtils;

    SubstitutionVisitor(Function<TypeVariable, TypeMirror> substitute, Types typeUtils) {
      this.substitute = substitute;
      this.typeUtils = typeUtils;
    }

    @Override
    protected TypeMirror defaultAction(TypeMirror t, Void p) {
      return t;
    }

    @Override
    public TypeMirror visitTypeVariable(TypeVariable t, Void p) {
      TypeMirror substituted = substitute.apply(t);
      return (substituted == null) ? t : substituted;
    }

    @Override
    public TypeMirror visitDeclared(DeclaredType t, Void p) {
      List<? extends TypeMirror> typeArguments = t.getTypeArguments();
      TypeMirror[] substitutedTypeArguments = new TypeMirror[typeArguments.size()];
      for (int i = 0; i < typeArguments.size(); i++) {
        substitutedTypeArguments[i] = visit(typeArguments.get(i));
      }
      return typeUtils.getDeclaredType(
          MoreElements.asType(t.asElement()), substitutedTypeArguments);
    }

    @Override
    public TypeMirror visitWildcard(WildcardType t, Void p) {
      TypeMirror ext = visitOrNull(t.getExtendsBound());
      if (ext != null && ext.getKind().equals(TypeKind.WILDCARD)) {
        // An example of where this happens is if we have this method in ImmutableSet:
        //    static <E> ImmutableSet<E> copyOf(Collection<? extends E>)
        // and we want to know if we can do this (where T is parameter of the enclosing class):
        //    ImmutableSet<T> actualParameter = ...
        //    ImmutableSet<? extends T> target = ImmutableSet.copyOf(actualParameter);
        // We will infer E=<? extends T> and rewrite the formal parameter type to
        // Collection<? extends ? extends T>, which we must simplify to Collection<? extends T>.
        return ext;
      }
      return typeUtils.getWildcardType(ext, visitOrNull(t.getSuperBound()));
    }

    @Override
    public TypeMirror visitArray(ArrayType t, Void p) {
      TypeMirror comp = visit(t.getComponentType());
      if (comp.getKind().equals(TypeKind.WILDCARD)) {
        // An example of where this happens is if we have this method in ImmutableSet:
        //    static <E> ImmutableSet<E> copyOf(E[])
        // and we want to know if we can do this:
        //    String[] actualParameter = ...
        //    ImmutableSet<? extends T> target = ImmutableSet.copyOf(actualParameter);
        // We will infer E=<? extends T> and rewrite the formal parameter type to
        // <? extends T>[], which we must simplify to T[].
        // TODO: what if getExtendsBound() returns null?
        comp = MoreTypes.asWildcard(comp).getExtendsBound();
      }
      return typeUtils.getArrayType(comp);
    }

    // We'd like to override visitIntersectionType here for completeness, but Types has no method
    // to fabricate a new IntersectionType. Anyway, currently IntersectionType can only occur as
    // the result of TypeVariable.getUpperBound(), but the TypeMirror we're starting from is not
    // that, and if we encounter a TypeVariable during our visit we don't visit its upper bound.

    private TypeMirror visitOrNull(TypeMirror t) {
      if (t == null) {
        return null;
      } else {
        return visit(t);
      }
    }
  }
}


text:
import $ from 'jquery';
import nv from 'nvd3';
import * as binaryPrefix from './binary-prefix';

$(() => {
    const dateFormat = d3.time.format('%Y-%m-%d');

    function setChartSize(graph) {
        const width = graph.parent.node().getBoundingClientRect().width;
        const height = 200;

        graph.chart
            .width(width)
            .height(height);

        graph.data
            .attr('width', width)
            .attr('height', height);
    }

    const el = document.getElementById('tab-traffic');
    if (!el) {
        console.warning("No element of id tab-traffic exists!")
        return
    }
    el.addEventListener('shown.bs.tab', () => {
        d3.select(".traffic-graph").each(function () {
            const trafficGraph = {
                parent: d3.select(this),
                url: this.dataset.url,
                days: this.dataset.days,
            };

            nv.addGraph({
                generate: () => {
                    trafficGraph.chart = nv.models.multiBarChart()
                        .margin({top: 25, right: 75, bottom: 30, left: 60})
                        .stacked(true)
                        .groupSpacing(0.4)
                        .color(["#b55d1f", "#1f77b4"]);
                    trafficGraph.chart.yScale(binaryPrefix.linearScale());
                    trafficGraph.chart.yAxis.tickFormat(binaryPrefix.format);

                    trafficGraph.data = trafficGraph.parent.append("svg");

                    setChartSize(trafficGraph);

                    return trafficGraph.chart;
                },
                callback: graph => {
                    nv.utils.windowResize(() => {
                        setChartSize(trafficGraph);

                        trafficGraph.data
                            .transition().duration(0)
                            .call(graph);
                    });

                    loadTrafficData(trafficGraph);
                },
            });
        });
    }, {once: true});

    function loadTrafficData(trafficGraph) {
        d3.json(`${trafficGraph.url}/${trafficGraph.days}`,
            (error, resp) => {
            if (error) throw error;

            // Normalize data
            const traffic = resp.items.traffic;
            traffic.forEach(d => {
                d.timestamp = d3.time.format.iso.parse(d.timestamp);
            });

            // Traffic graph
            const data = [{
                key: "Upload",
                nonStackable: false,
                values: traffic.map(d => ({
                    x: d.timestamp,
                    y: d.egress,
                })),
            },
                {
                    key: "Download",
                    nonStackable: false,
                    values: traffic.map(d => ({
                        x: d.timestamp,
                        y: d.ingress,
                    })),
                }];

            trafficGraph.chart.xAxis.tickFormat(d => dateFormat(d));

            if (!traffic.some(d => !!d.ingress || !!d.egress))
                trafficGraph.chart.forceY([0, 1000]);

            trafficGraph.data.datum(data).transition().duration(250).call(trafficGraph.chart);
        });
    }

    const selectDays = document.querySelector('.select-days');
    if (!selectDays) {
        // TODO find out why that field does not exist anymore
        console.warn("No element of selector `.select-days`!");
        return
    }
    selectDays.addEventListener('change', ev => loadTrafficData(ev.target));
});


text:
<?php

namespace TunaCMS\Bundle\EditablesBundle\PageCache;

use Masterminds\HTML5;
use TunaCMS\Bundle\EditablesBundle\Factory\EditableFactory;
use TunaCMS\Bundle\EditablesBundle\Model\EditableInterface;
use TunaCMS\Bundle\EditablesBundle\Model\PageInterface;

class PageCacheManager
{
    const HTML5_OPTIONS = [
        'disable_html_ns' => true,
    ];

    /**
     * @var HTML5
     */
    protected $html5;

    /**
     * @var EditableFactory
     */
    protected $editableFactory;

    public function __construct(EditableFactory $editableFactory)
    {
        $this->editableFactory = $editableFactory;
        $this->html5 = new HTML5(self::HTML5_OPTIONS);
    }

    public function updatePageCache(PageInterface $page)
    {
        if (!strlen($page->getTemplate())) {
            return;
        }

        $wrappedTemplate = sprintf('
%s
', $page->getTemplate());

        $document = $this->html5->loadHTML($wrappedTemplate);
        $editablesMap = self::getEditablesMap($page);
        $xpath = new \DOMXPath($document);

        $editableElements = $xpath->query('//*[@data-editable]');

        /* @var $element \DOMElement */
        foreach ($editableElements as $element) {
            $alias = $element->getAttribute('data-editable');

            if (array_key_exists($alias, $editablesMap)) {
                $this->renderEditable($element, $editablesMap[$alias]);
            } else {
                self::removeEditableAttributes($element);
            }
        }

        $pageCompiledContent = $this->html5->saveHTML($this->getHtmlContentNodes($document));
        $pageCompiledContent = $this->stripDivWrapper($pageCompiledContent);

        $page->setCompiledBody($pageCompiledContent);
    }

    protected function getHtmlContentNodes(\DOMDocument $document)
    {
        return $document->childNodes->item(1)->childNodes;
    }

    protected function renderEditable(\DOMElement $element, EditableInterface $editable)
    {
        $this->removeEditableAttributes($element);
        $type = $editable->getType();
        $rendererType = $this->editableFactory->getTypeFromClassName($type);
        $renderer = $this->editableFactory->getRendererInstance($rendererType);
        $renderer->render($this->html5, $element, $editable);
    }

    protected function removeEditableAttributes(\DOMElement $element)
    {
        $element->removeAttribute('data-editable');
        $element->removeAttribute('data-editable-type');
        $element->removeAttribute('data-editable-filter');
    }

    protected function stripDivWrapper($html)
    {
        return substr($html, strlen('
'), -strlen('
'));
    }

    /**
     * @param PageInterface $page
     *
     * @return array|EditableInterface[]
     */
    protected function getEditablesMap(PageInterface $page)
    {
        $editablesMap = [];

        foreach ($page->getEditables() as $editable) {
            $editablesMap[$editable->getAlias()] = $editable;
        }

        return $editablesMap;
    }
}


text:
.. _dojox/editor/plugins/InsertEntity:

=================================
dojox.editor.plugins.InsertEntity
=================================

:Authors: Jared Jurkiewicz
:Project owner: Jared Jurkiewicz
:since: V1.4

.. contents ::
    :depth: 2

Have you ever wanted to easily insert the copyright symbol, the trademark symbol, or any of a variety of mathematical symbols into the document you're editing in the dijit.Editor?   If so, then this plugin is for you!  This plugin provides a subset of entity characters that can be inserted into your documents.  The symbols provided are primarily the non-ascii 8859 characters and a large set of greek symbols used in mathematics.

Features
========

Once required in and enabled, this plugin provides the following features to dijit.Editor.

* Button with icon in toolbar for inserting a symbol from a subset of entity characters at the current location in the document.
* Keyboard hotkey: CTRL-SHIFT-S for inserting a symbol at the current location in the editor.  (Note that this is a similar keybind to those used by commercial word processors, so it will hopefully be familiar and easy to pick up.).
* A key-navigable grid of symbols to select the one to insert.

Usage
=====

Basic Usage
-----------
Usage of this plugin is quite simple and painless.

First include the CSS for it:

.. css ::

    @import "dojox/editor/plugins/resources/css/InsertEntity.css";

Then require it into the page where you're using the editor:

.. js ::

    dojo.require("dijit.Editor");
    dojo.require("dojox.editor.plugins.InsertEntity");

Once it has been required in, all you have to do is include it in the list of extraPlugins (or the plugins property if you're reorganizing the toolbar) for you want to load into the editor.  For example:

.. html ::

And that's it.  The editor instance you can reference by 'dijit.byId("editor")' is now enabled with the InsertEntity plugin!  You can use the button or hotkey to insert entity characters as you desire.

Limitations
===========

Something to be aware of is that if you also use the :ref:`dojox.editor.plugins.PrettyPrint <dojox/editor/plugins/PrettyPrint>` plugin is that you will need to reconfigure PrettyPrint to escape more entities.  Otherwise, entity encoding will not be preserved when the value is retrieved from the editor.  This can be done as follows:

.. html ::

The above configures prettyprint to escape all the same entities that the InsertEntity plugin can insert.

Examples
========

Basic Usage
-----------

.. code-example::
  :djConfig: parseOnLoad: true
  :version: 1.4

  .. js ::

      dojo.require("dijit.Editor");
      dojo.require("dijit._editor.plugins.ViewSource");
      dojo.require("dojox.editor.plugins.InsertEntity");
      dojo.require("dojox.editor.plugins.PrettyPrint");
      dojo.require("dojox.html.entities");

  .. css ::

      @import "{{baseUrl}}dojox/editor/plugins/resources/css/InsertEntity.css";

  .. html ::

    Enter some text or select a position, then push the InsertEntity button or use CTRL-SHIFT-S, to insert an entity character of your choosing at that point. Note that viewsource and prettyprint are also enabled so that you can see the entities and their encodings.

    blah blah & blah!

    One cell

    Two cell

item one

    item two

See Also
========

* :ref:`dijit.Editor <dijit/Editor>`
* :ref:`dijit._editor.plugins <dijit/_editor/plugins>`
* :ref:`dojox.editor.plugins <dojox/editor/plugins>`


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="2dp">

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_alignParentTop="true"
        android:layout_width="80dp"
        android:layout_height="60dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/placeholder"
        android:scaleType="fitStart"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:maxLines="3"/>

</LinearLayout>


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Collections.Generic;
using System.Threading.Tasks;

namespace Squidex.Shared.Users
{
    public interface IUserResolver
    {
        Task<IUser> FindByIdOrEmailAsync(string idOrEmail);

        Task<List<IUser>> QueryByEmailAsync(string email);
    }
}


text:
q2pc
====

A 2-phase commit system that runs over Q-Jump (or not). Can be configured to run over TCP, UPD+retires, UDP without retries or UDP+Broadcast (assuming QJUmp).

Building
========

Requirements
------------
- cake build system
- libchaste C library
- clang or gcc

Building q2pc requires the Cake build system, available from
https://github.com/Zomojo/Cake.git

Follow the instructions in INSTALL to configure cake

q2pc also requires the libchaste C library, which is available from
https://github.com/mgrosvenor/libchaste

Building
--------

To build q2pc, make sure that the symbolic link to libchaste (in the deps directory) is pointing to the right place and run ./build.sh from the root directory.

To build a release version run "./build.sh --variant=release"

Running
=======

q2pc supports the following options

|Mode     | Type          | Short|Long Option    | Description                                                                  |
|---------|---------------|------|---------------|------------------------------------------------------------------------------|
|Optional | Integer |-s  |--server        |  Put q2pc in server mode, specify the number of clients [0]  |
|Optional | Integer |-T  |--threads       |  The number of threads to use [1]  |
|Optional | String  |-c  |--client        |  Put q2pc in client mode, specify server address in x.x.x.x format [(null)]  |
|Optional | Integer |-C  |--id            |  The client ID to use for this client (must be >0) [-1]  |
|Flag     | Boolean |-u  |--udp-ln        |  Use Linux based UDP transport [default]   |
|Flag     | Boolean |-t  |--tcp-ln        |  Use Linux based TCP transport   |
|Flag     | Boolean |-r  |--rdp-ln        |  Use Linux based UDP transport with reliability   |
|Flag     | Boolean |-q  |--udp-qj        |  Use broadcast based UDP transport over Q-Jump   |
|Optional | Integer |-p  |--port          |  Port to use for all transports [7331]  |
|Optional | String  |-B  |--broadcast     |  The broadcast IP address to use in UDP mode ini x.x.x.x format [127.0.0.0]  |
|Optional | String  |-i  |--iface         |  The interface name to use [eth4]  |
|Optional | Integer |-m  |--message-size  |  Size of the messages to use [128]  |
|Flag     | Boolean |-n  |--no-colour     |  Turn off colour log output   |
|Flag     | Boolean |-0  |--log-stdout    |  Log to standard out   |
|Flag     | Boolean |-1  |--log-stderr    |  Log to standard error [default]   |
|Optional | String  |-F  |--log-file      |  Log to the file supplied [(null)]   |
|Optional | Integer |-v  |--log-level     |  Log level verbosity (0 = lowest, 6 = highest) [3]  |
|Optional | Integer |-w  |--wait          |  How long to wait for client/server delay (us) [2000000]  |
|Optional | Integer |-o  |--rto           |  How long to wait before retransmitting a request (us) [200000]  |
|Optional | Integer |-R  |--report-int    |  reporting interval for statistics [100]  |
|Optional | Integer |-S  |--stats-len     |  length of stats to keep [1000]  |
|Flag     | Boolean |-h  |--help          |  Print this help message   |


text:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "tcpconnector.h"

using namespace std;

int main(int argc, char** argv)
{
    if (argc != 3) {
        printf("usage: %s <port> <ip>\n", argv[0]);
        exit(1);
    }

    int len;
    string message;
    char line[256];
    TCPConnector* connector = new TCPConnector();
    TCPStream* stream = connector->connect(argv[2], atoi(argv[1]));
    if (stream) {
        message = "Is there life on Mars?";
        stream->send(message.c_str(), message.size());
        printf("sent - %s\n", message.c_str());
        len = stream->receive(line, sizeof(line));
        line[len] = 0;
        printf("received - %s\n", line);
        delete stream;
    }

    stream = connector->connect(argv[2], atoi(argv[1]));
    if (stream) {
        message = "Why is there air?";
        stream->send(message.c_str(), message.size());
        printf("sent - %s\n", message.c_str());
        len = stream->receive(line, sizeof(line));
        line[len] = 0;
        printf("received - %s\n", line);
        delete stream;
    }
    exit(0);
}


text:
module Taroxd
  module Metadata
    def self.read(source)
      return unless source.include?('@taroxd metadata')
      metadata = {}
      source.scan(/^# @(\w+)(?: +(.+))?/) do |key, value|
        key = key.to_sym
        value ||= ""
        original_value = metadata[key]
        value = original_value ? "#{original_value}\n#{value}" : value
        metadata[key] = value.chomp
      end
      metadata
    end
  end
end


text:
namespace boost { namespace iostreams {

template<typename Container>
class back_insert_device {
public:
    typedef typename Container::value_type  char_type;
    typedef sink_tag                        category;
    back_insert_device(Container& cnt) : container(&cnt) { }
    std::streamsize write(const char_type* s, std::streamsize n)
    {
        container->insert(container->end(), s, s + n);
        return n;
    }
protected:
    Container* container;
};

template<typename Container>
back_insert_device<Container> back_inserter(Container& cnt)
{ return back_insert_device<Container>(cnt); }

} } // End namespaces iostreams, boost.

#endif // #ifndef BOOST_IOSTREAMS_BACK_INSERTER_HPP_INCLUDED


text:
<?php

/**
 * The "projects" collection of methods.
 * Typical usage is:
 *  <code>
 *   $dfareportingService = new Google_Service_Dfareporting(...);
 *   $projects = $dfareportingService->projects;
 *  </code>
 */
class Google_Service_Dfareporting_Resource_Projects extends Google_Service_Resource
{
  /**
   * Gets one project by ID. (projects.get)
   *
   * @param string $profileId User profile ID associated with this request.
   * @param string $id Project ID.
   * @param array $optParams Optional parameters.
   * @return Google_Service_Dfareporting_Project
   */
  public function get($profileId, $id, $optParams = array())
  {
    $params = array('profileId' => $profileId, 'id' => $id);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Dfareporting_Project");
  }
  /**
   * Retrieves a list of projects, possibly filtered. This method supports paging.
   * (projects.listProjects)
   *
   * @param string $profileId User profile ID associated with this request.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string advertiserIds Select only projects with these advertiser
   * IDs.
   * @opt_param string ids Select only projects with these IDs.
   * @opt_param int maxResults Maximum number of results to return.
   * @opt_param string pageToken Value of the nextPageToken from the previous
   * result page.
   * @opt_param string searchString Allows searching for projects by name or ID.
   * Wildcards (*) are allowed. For example, "project*2015" will return projects
   * with names like "project June 2015", "project April 2015", or simply "project
   * 2015". Most of the searches also add wildcards implicitly at the start and
   * the end of the search string. For example, a search string of "project" will
   * match projects with name "my project", "project 2015", or simply "project".
   * @opt_param string sortField Field by which to sort the list.
   * @opt_param string sortOrder Order of sorted results, default is ASCENDING.
   * @return Google_Service_Dfareporting_ProjectsListResponse
   */
  public function listProjects($profileId, $optParams = array())
  {
    $params = array('profileId' => $profileId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Dfareporting_ProjectsListResponse");
  }
}


text:
var validator = require('validator'),
    crypto = require('crypto'),
    Gravatar = require('machinepack-gravatar');

/**
 * Local Authentication Protocol
 *
 * The most widely used way for websites to authenticate users is via a username
 * and/or email as well as a password. This module provides functions both for
 * registering entirely new users, assigning passwords to already registered
 * users and validating login requesting.
 *
 * For more information on local authentication in Passport.js, check out:
 * http://passportjs.org/guide/username-password/
 */

/**
 * Register a new user
 *
 * This method creates a new user from a specified email, username and password
 * and assign the newly created user a local Passport.
 *
 * @param {Object}   req
 * @param {Object}   res
 * @param {Function} next
 */
exports.register = function(req, res, next) {
    var email = req.param('email'),
        username = req.param('username'),
        password = req.param('password'),
        confirmPassword = req.param('confirmPassword');

    if (!email) {
        req.flash('error', 'Error.Passport.Email.Missing');
    }

    if (!username) {
        req.flash('error', 'Error.Passport.Username.Missing');
    }

    if (!password) {
        req.flash('error', 'Error.Passport.Password.Missing');
    }

    if (!confirmPassword) {
        req.flash('error', 'Error.Passport.ConfirmPassword.Missing');
    }

    if (!email || !username || !password || !confirmPassword) {
        return next(new Error('Missing requied fields.'));
    }

    Gravatar.getImageUrl({
        emailAddress: req.param('email'),
        gravatarSize: 2048,
        defaultImage: process.env.S3_BUCKET_URL + '/assets/images/default_avatar.png',
        rating: 'g',
        useHttps: true
    }).exec({
        error: function(err) {
            return next(err);
        },
        success: function(gravatarUrl) {

            User.create({
                username: username,
                email: email,
                gravatar: gravatarUrl,
                setUsername: true
            }, function(err, user) {
                if (err) {
                    if (err.code === 'E_VALIDATION') {
                        if (err.invalidAttributes.email) {
                            req.flash('error', 'Error.Passport.Email.Exists');
                        } else {
                            req.flash('error', 'Error.Passport.User.Exists');
                        }
                    }

                    return next(err);
                }

                // Generating accessToken for API authentication
                var token = crypto.randomBytes(48).toString('base64');

                Passport.create({
                    protocol: 'local',
                    password: password,
                    user: user.id,
                    accessToken: token
                }, function(err, passport) {
                    if (err) {
                        if (err.code === 'E_VALIDATION') {
                            req.flash('error', 'Error.Passport.Password.Invalid');
                        }

                        return user.destroy(function(destroyErr) {
                            next(destroyErr || err);
                        });
                    }

                    return next(null, user);
                });
            });
        }
    });
};

/**
 * Assign local Passport to user
 *
 * This function can be used to assign a local Passport to a user who doens't
 * have one already. This would be the case if the user registered using a
 * third-party service and therefore never set a password.
 *
 * @param {Object}   req
 * @param {Object}   res
 * @param {Function} next
 */
exports.connect = function(req, res, next) {
    var user = req.user,
        password = req.param('password');

    Passport.findOne({
        protocol: 'local',
        user: user.id
    }, function(err, passport) {
        if (err) {
            return next(err);
        }

        if (!passport) {
            Passport.create({
                protocol: 'local',
                password: password,
                user: user.id
            }, function(err, passport) {
                next(err, user);
            });
        } else {
            next(null, user);
        }
    });
};

/**
 * Validate a login request
 *
 * Looks up a user using the supplied identifier (email or username) and then
 * attempts to find a local Passport associated with the user. If a Passport is
 * found, its password is checked against the password supplied in the form.
 *
 * @param {Object}   req
 * @param {string}   identifier
 * @param {string}   password
 * @param {Function} next
 */
exports.login = function(req, identifier, password, next) {
    var isEmail = validator.isEmail(identifier),
        query = {};

    if (isEmail) {
        query.email = identifier;
    } else {
        query.username = identifier;
    }

    User.findOne(query, function(err, user) {
        if (err) {
            return next(err);
        }

        if (!user) {
            if (isEmail) {
                req.flash('error', 'Error.Passport.Email.NotFound');
            } else {
                req.flash('error', 'Error.Passport.Username.NotFound');
            }
            return next(null, false);
        }

        Passport.findOne({
            protocol: 'local',
            user: user.id
        }, function(err, passport) {
            if (passport) {
                passport.validatePassword(password, function(err, res) {
                    if (err) {
                        return next(err);
                    }

                    if (!res) {
                        req.flash('error', 'Error.Passport.Password.Wrong');
                        return next(null, false);
                    } else {
                        return next(null, user);
                    }
                });
            } else {
                req.flash('error', 'Error.Passport.Password.NotSet');
                return next(null, false);
            }
        });
    });
};


text:
/**************************************************************************/
/**
 * @file    system_W7500x.h
 * @author  IOP Team
 * @version V1.0.0
 * @date    01-May-2015
 * @brief   CMSIS Cortex-M0 Core Peripheral Access Layer Header File for
 *          Device W7500x
 ******************************************************************************
 *
 * @attention
 * @par Revision history
 *    <2015/05/01> 1st Release
 *
 *
© COPYRIGHT 2015 WIZnet Co.,Ltd.

 ******************************************************************************
 */

#ifndef SYSTEM_W7500x_H   /* ToDo: replace '<Device>' with your device name */
#define SYSTEM_W7500x_H

#ifdef __cplusplus
extern "C" {
#endif

#include "W7500x.h"

extern uint32_t SystemCoreClock;     /*!< System Clock Frequency (Core Clock)  */
extern uint32_t GetSystemClock(void);    /*!< Get System Clock Frequency */

/**
 * Initialize the system
 *
 * @param  none
 * @return none
 *
 * @brief  Setup the microcontroller system.
 *         Initialize the System and update the SystemCoreClock variable.
 */
extern void SystemInit (void);

/**
 * Update SystemCoreClock variable
 *
 * @param  none
 * @return none
 *
 * @brief  Updates the SystemCoreClock with current core Clock
 *         retrieved from cpu registers.
 */
extern void SystemCoreClockUpdate (void);

/*----------------------------------------------------------------------------
  Define clocks
 *----------------------------------------------------------------------------*/
#define EXTERN_XTAL     (8000000UL)     /* External Oscillator Frequency        */
#define INTERN_XTAL     (8000000UL)     /* Internal Oscillator Frequency         */

#ifdef __cplusplus
}
#endif

#endif /* SYSTEM_W7500x_H */


text:
'use strict';

var _typeof = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol == "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } }

(function (global, factory) {
    (typeof exports == 'undefined' ? 'undefined' : _typeof(exports)) == 'object' && typeof module != 'undefined' ? factory(exports) : typeof define == 'function' && define.amd ? define(['exports'], factory) : factory(global.$solway = global.$solway || {});
})(window, function (exports) {
    _newArrowCheck(void 0, void 0);

    var drag = function (_ref) {
        var dv = _ref.ele;

        _newArrowCheck(void 0, void 0);

        dv.setAttribute('style', (dv.getAttribute('style') || '') + 'position: absolute;transition: all 0.1s ease 0s;-webkit-transition: all 0.1s ease 0s;-o-transition: all 0.1s ease 0s;-moz-transition: all 0.1s ease 0s;-moz-user-select: -moz-none; -moz-user-select: none; -o-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none;');
        var x = 0,
            y = 0,
            l = 0,
            t = 0,
            isDown = !1;

        dv.addEventListener('mousedown', eleMousedown);
        document.addEventListener('mousemove', eleMousemove);
        dv.addEventListener('mouseup', eleMouseup);

        function eleMousedown(e) {
            x = e.clientX;
            y = e.clientY;

            l = dv.offsetLeft;
            t = dv.offsetTop;

            isDown = !0;

            dv.style.cursor = 'move';
            return !1;
        }

        function eleMousemove(e) {
            if (isDown == !1) {
                return;
            }

            var nx = e.clientX,
                ny = e.clientY,
                nl = nx - (x - l),
                nt = ny - (y - t);

            dv.style.left = nl + 'px';
            dv.style.top = nt + 'px';
            return !1;
        }

        function eleMouseup() {
            isDown = !1;
            dv.style.cursor = 'default';
            return !1;
        }
        return {
            destroy: function () {
                function destroy() {
                    if (dv){
                        dv.removeEventListener('mousedown', eleMousedown);
                        document.removeEventListener('mousemove', eleMousemove);
                        dv.removeEventListener('mouseup', eleMouseup);
                        dv = null;
                    }
                }

                return destroy;
            }()
        };
    }.bind(void 0);

    exports.drag = drag;
}.bind(void 0));


text:
'use strict';

//global variables
var hours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', 'Total'];
var stores = [];
var total = [];
var tableElement;
var rowData;

//global functions
function hourHeader() {  //print the hours of operation
  var tableEl = document.getElementById('table');
  var newRow = document.createElement('tr');
  var storeName = document.createElement('th');
  storeName.textContent = 'Stores';
  newRow.setAttribute('id', 'tableFormat');
  newRow.appendChild(storeName);
  for (var i = 0; i < hours.length; i ++) {
    var rowData = document.createElement('th');
    rowData.textContent = hours[i];
    newRow.appendChild(rowData);
  }
  tableEl.appendChild(newRow);
};

function getHourTotal() { //sum the amount of cookies sold each hour
  total = [];
  for (var i = 0; i < hours.length; i ++){
    var hour = 0;
    for (var j = 0; j < stores.length; j++){
      var storeCount = stores[j].location[i];
      hour = hour + storeCount;
    }
    total.push(hour);
  }
};

function footerHeader() { //print the total cookies sold each hour
  tableElement = document.getElementById('table');
  var newRow = document.createElement('tr');
  var blankHead = document.createElement('th');
  newRow.setAttribute('id', 'tableTotal');
  newRow.setAttribute('class', 'tableFormat');
  blankHead.textContent = 'Totals';
  newRow.appendChild(blankHead);
  for (var i = 0; i < total.length; i ++) {
    rowData = document.createElement('td');
    rowData.textContent = total[i];
    newRow.appendChild(rowData);
  }
  tableElement.appendChild(newRow);
};

function removeRow() {
  var oldTableEl = document.getElementById('table');
  var oldRowEl = document.getElementById('tableTotal');
  var remove = oldTableEl.removeChild(oldRowEl);
  remove;
}

//In progress.  Looking to add an animation event to the index.html site
// function fadeOut(element) {
//   var mouseMove = document.getElementById('footer');
//
// }

//Store object
function Store(minHourlyCust, maxHourlyCust, avgCookies, name){
  this.minHourlyCust = parseInt(minHourlyCust);
  this.maxHourlyCust = parseInt(maxHourlyCust);
  this.avgCookies = avgCookies;
  this.location = [];
  this.name = name;
};

//methods
Store.prototype.cookiesPerHour = function() {   //calculate the amount of cookies sold per hour
  for (var i = 0; i < hours.length - 1; i++) {
    var people = Math.round(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
    var amount = Math.round(people * this.avgCookies);
    this.location.push(amount);
  }
};

Store.prototype.amount = function() {   //add the total amount of cookies sold
  var sum = 0;
  for(var i = 0; i < this.location.length; i ++){
    sum += this.location[i];
  }
  this.location.push(sum);
  // console.log(this.location);
};

Store.prototype.cookieTotals = function() {   //print the information into a table on the sales.html page
  var arr = this.location;
  var tableEl2 = document.getElementById('table');
  var newRow = document.createElement('tr');
  newRow.setAttribute('id', 'rowInfo');
  var nameEl = document.createElement('th');
  nameEl.textContent = this.name;
  newRow.appendChild(nameEl);
  for (var i = 0; i < arr.length; i ++) {
    var rowData = document.createElement('td');
    rowData.textContent = arr[i];
    newRow.appendChild(rowData);
    // console.log('Inside cookie totals: ' + arr[i]);
  }

  tableEl2.appendChild(newRow);
};

Store.prototype.print = function() {    //call the methods in proper order
  this.cookiesPerHour();
  this.amount();
  this.cookieTotals();
};

//event listeners
var formEl = document.getElementById('store-info');   //When form is submitted, populate table with new info

formEl.addEventListener('submit', function(event){
  event.preventDefault();
  event.stopPropagation();

  var location = event.target.location.value;
  var minCustomer = event.target.minCust.value;
  var maxCustomer = event.target.maxCust.value;
  var avgSold = event.target.avgSold.value;
  var newStore = new Store(minCustomer, maxCustomer, avgSold, location);
  stores.push(newStore);
  removeRow();

  newStore.print();
  getHourTotal();
  footerHeader();
  console.log(stores);
}, false);

// Inprogress.  Working on adding an animation element to index.html
// window.addEventListener('scroll', fadeOut, false);

//created stores
var firstAndPike = new Store(23, 65, 6.3, 'First and Pike');
stores.push(firstAndPike);
var seatac = new Store(2, 23, 1.2, 'Seatac');
stores.push(seatac);
var seattleCenter = new Store(11, 38, 3.7, 'Seattle Center');
stores.push(seattleCenter);
var capitalHill = new Store(20, 38, 2.3, 'Capital Hill');
stores.push(capitalHill);
var alki = new Store(2, 16, 4.6, 'Alki');
stores.push(alki);

//call the stores to print
hourHeader();
firstAndPike.print();
seatac.print();
seattleCenter.print();
capitalHill.print();
alki.print();
getHourTotal();
footerHeader();


text:
<?php

namespace Drupal\system\Tests\Plugin;

use Drupal\Component\Plugin\Exception\ExceptionInterface;

/**
 * Tests that plugins are correctly instantiated.
 *
 * @group Plugin
 */
class FactoryTest extends PluginTestBase {

  /**
   * Test that DefaultFactory can create a plugin instance.
   */
  function testDefaultFactory() {
    // Ensure a non-derivative plugin can be instantiated.
    $plugin = $this->testPluginManager->createInstance('user_login', array('title' => 'Please enter your login name and password'));
    $this->assertIdentical(get_class($plugin), 'Drupal\plugin_test\Plugin\plugin_test\mock_block\MockUserLoginBlock', 'Correct plugin class instantiated with default factory.');
    $this->assertIdentical($plugin->getTitle(), 'Please enter your login name and password', 'Plugin instance correctly configured.');

    // Ensure that attempting to instantiate non-existing plugins throws a
    // PluginException.
    try {
      $this->testPluginManager->createInstance('non_existing');
      $this->fail('Drupal\Component\Plugin\Exception\ExceptionInterface expected');
    }
    catch (ExceptionInterface $e) {
      $this->pass('Drupal\Component\Plugin\Exception\ExceptionInterface expected and caught.');
    }
    catch (\Exception $e) {
      $this->fail('Drupal\Component\Plugin\Exception\ExceptionInterface expected, but ' . get_class($e) . ' was thrown.');
    }
  }

  /**
   * Test that the Reflection factory can create a plugin instance.
   *
   * The mock plugin classes use different values for their constructors
   * allowing us to test the reflection capabilities as well.
   *
   * We use derivative classes here because the block test type has the
   * reflection factory and it provides some additional variety in plugin
   * object creation.
   */
  function testReflectionFactory() {
    // Ensure a non-derivative plugin can be instantiated.
    $plugin = $this->mockBlockManager->createInstance('user_login', array('title' => 'Please enter your login name and password'));
    $this->assertIdentical(get_class($plugin), 'Drupal\plugin_test\Plugin\plugin_test\mock_block\MockUserLoginBlock', 'Correct plugin class instantiated.');
    $this->assertIdentical($plugin->getTitle(), 'Please enter your login name and password', 'Plugin instance correctly configured.');

    // Ensure a derivative plugin can be instantiated.
    $plugin = $this->mockBlockManager->createInstance('menu:main_menu', array('depth' => 2));
    $this->assertIdentical($plugin->getContent(), '

1

1.1

', 'Derived plugin instance correctly instantiated and configured.');

    // Ensure that attempting to instantiate non-existing plugins throws a
    // PluginException. Test this for a non-existing base plugin, a non-existing
    // derivative plugin, and a base plugin that may not be used without
    // deriving.
    foreach (array('non_existing', 'menu:non_existing', 'menu') as $invalid_id) {
      try {
        $this->mockBlockManager->createInstance($invalid_id);
        $this->fail('Drupal\Component\Plugin\Exception\ExceptionInterface expected');
      }
      catch (ExceptionInterface $e) {
        $this->pass('Drupal\Component\Plugin\Exception\ExceptionInterface expected and caught.');
      }
      catch (\Exception $e) {
        $this->fail('An unexpected Exception of type "' . get_class($e) . '" was thrown with message ' . $e->getMessage());
      }
    }
  }

}


text:
#pragma once

#include "GameState.hpp"
#include "Input.hpp"

namespace arduino_pong
{

class Renderer;

class GameField
{
public:
    GameField();

    void update();
    void render(Renderer& renderer);
    void reset();

private:
    void handleCollision(int paddleNum);
	void resetBall(float angle);

	void renderCurrentPoints(Renderer& renderer);

    Input input_;
    GameState state_;
    GameState oldState_;
    bool init_;
};

}  // namespace arduino_pong


text:
package com.jing.zookeeper.main;

import com.jing.zookeeper.data.Client;
import com.jing.zookeeper.publish.PublishManager;

/**
 * @author jingsir
 **
 *         取消发布Main函数
 */
public class CanclePublishMain {

	public static void main(String[] args) {
		Client zkClient = new Client();
		PublishManager.getInstance().unpublish(zkClient);
	}

}


text:
package org.springframework.boot.actuate.metrics.repository.redis;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assume;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import static org.junit.Assert.fail;

/**
 * @author Eric Bottard
 * @author Gary Russell
 * @author Dave Syer
 */
public class RedisServer implements TestRule {

	private static final String EXTERNAL_SERVERS_REQUIRED = "EXTERNAL_SERVERS_REQUIRED";

	protected JedisConnectionFactory resource;

	private final String resourceDescription = "Redis ConnectionFactory";

	private static final Log logger = LogFactory.getLog(RedisServer.class);

	public static RedisServer running() {
		return new RedisServer();
	}

	private RedisServer() {
	}

	@Override
	public Statement apply(final Statement base, Description description) {
		try {
			this.resource = obtainResource();
		}
		catch (Exception ex) {
			maybeCleanup();
			return failOrSkip(ex);
		}

		return new Statement() {

			@Override
			public void evaluate() throws Throwable {
				try {
					base.evaluate();
				}
				finally {
					try {
						cleanupResource();
					}
					catch (Exception ignored) {
						RedisServer.logger.warn(
								"Exception while trying to cleanup proper resource",
								ignored);
					}
				}
			}

		};
	}

	private Statement failOrSkip(Exception exception) {
		String serversRequired = System.getenv(EXTERNAL_SERVERS_REQUIRED);
		if ("true".equalsIgnoreCase(serversRequired)) {
			logger.error(this.resourceDescription + " IS REQUIRED BUT NOT AVAILABLE",
					exception);
			fail(this.resourceDescription + " IS NOT AVAILABLE");
			// Never reached, here to satisfy method signature
			return null;
		}
		else {
			logger.error(this.resourceDescription + " IS NOT AVAILABLE, SKIPPING TESTS",
					exception);
			return new Statement() {

				@Override
				public void evaluate() throws Throwable {
					Assume.assumeTrue("Skipping test due to "
							+ RedisServer.this.resourceDescription
							+ " not being available", false);
				}
			};
		}
	}

	private void maybeCleanup() {
		if (this.resource != null) {
			try {
				cleanupResource();
			}
			catch (Exception ignored) {
				logger.warn("Exception while trying to cleanup failed resource", ignored);
			}
		}
	}

	public RedisConnectionFactory getResource() {
		return this.resource;
	}

	/**
	 * Perform cleanup of the {@link #resource} field, which is guaranteed to be non null.
	 *
	 * @throws Exception any exception thrown by this method will be logged and swallowed
	 */
	protected void cleanupResource() throws Exception {
		this.resource.destroy();
	}

	/**
	 * Try to obtain and validate a resource. Implementors should either set the
	 * {@link #resource} field with a valid resource and return normally, or throw an
	 * exception.
	 * @return the jedis connection factory
	 * @throws Exception if the factory cannot be obtained
	 */
	protected JedisConnectionFactory obtainResource() throws Exception {
		JedisConnectionFactory resource = new JedisConnectionFactory();
		resource.afterPropertiesSet();
		resource.getConnection().close();
		return resource;
	}

}


text:
In order to run these files, you need to build the project with the following
instruction. And then execute them using the interactive shell runner `grun.sh`

    ./gradlew build copyDevToLib
    .. copy these files into groovysh folder ..
    cd groovysh
    ./grun.sh ../example/filename

You will also need the static binary of wkhtmltox.