text:
typedef tree<LPCWSTR> b_tree;
typedef list<WCHAR*> WStrList;

const LPWSTR kOutOfMemory = L"Out of memory";

class ConsoleArgs
{
public:
    // Place the fully-qualified filename in the given output buffer
    bool GetFullFileName(LPCWSTR szSource, __deref_out_ecount(cbFilenameBuffer) LPWSTR filenameBuffer, DWORD cbFilenameBuffer, bool fOutputFilename);

    ConsoleArgs() :
            m_rgArgs(NULL),
            m_listArgs(NULL),
            m_errorOccured(false),
            m_lastErrorMessage(nullptr)
    {
    };

    ~ConsoleArgs()
    {
        CleanUpArgs();
    };

    // returns false if there are errors
    bool ExpandResponseFiles(__in int argc, __deref_in_ecount(argc) const LPCWSTR * argv, __deref_out int * pargc2, __out LPWSTR ** pppargv2);

    // Frees all memory used by the arg list and the argv/argc array
    void CleanUpArgs();

    LPWSTR ErrorMessage()
    {
        if (m_errorOccured)
        {
            return m_lastErrorMessage;
        }
        else
        {
            return nullptr;
        }
    }

private:
    void SetErrorMessage(__deref_in LPCWSTR pwzMessage);
    b_tree * MakeLeaf( LPCWSTR szText);
    void CleanupTree( b_tree * root);
    HRESULT TreeAdd( b_tree ** root, LPCWSTR szAdd);
    void TextToArgs( LPCWSTR szText, WStrList ** listReplace);
    bool ReadTextFile(LPCWSTR pwzFilename, __deref_out LPWSTR *ppwzTextBuffer);
    void ProcessResponseArgs();

    LPWSTR * m_rgArgs;
    WStrList * m_listArgs;

    bool m_errorOccured;
    LPWSTR m_lastErrorMessage;
};

#endif // __CONSOLEARGS_H__

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Designer.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;
using System.Diagnostics;

using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;

namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{

    /// <summary>
    /// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default.
    /// Set this attribute to false on Properties that should not be visible for Automation.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true), CLSCompliant(false)]
    public class AutomationBrowsableAttribute : System.Attribute
    {
        internal AutomationBrowsableAttribute(bool browsable)
        {
            this.browsable = browsable;
        }

        public bool Browsable
        {
            get
            {
                return this.browsable;
            }
        }

        private bool browsable;
    }

    /// <summary>
    ///  Encapsulates BuildAction enumeration
    /// </summary>
    public sealed class BuildAction
    {
        private readonly string actionName;

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction None = new BuildAction("None");
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction Compile = new BuildAction("Compile");
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction Content = new BuildAction("Content");
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction EmbeddedResource = new BuildAction("EmbeddedResource");
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction ApplicationDefinition = new BuildAction("ApplicationDefinition");
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction Page = new BuildAction("Page");
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "BuildAction type is immutable")]
        public static readonly BuildAction Resource = new BuildAction("Resource");

        internal BuildAction(string actionName)
        {
            this.actionName = actionName;
        }

        public string Name { get { return this.actionName; } }

        public override bool Equals(object other)
        {
            BuildAction action = other as BuildAction;
            return action != null && this.actionName == action.actionName;
        }

        public override int GetHashCode()
        {
            return this.actionName.GetHashCode();
        }

        public override string ToString()
        {
            return string.Format("BuildAction={0}", this.actionName);
        }

        public static bool operator ==(BuildAction b1, BuildAction b2)
        {
            return Equals(b1, b2);
        }

        public static bool operator !=(BuildAction b1, BuildAction b2)
        {
            return !(b1 == b2);
        }
    }

    /// <summary>
    /// To create your own localizable node properties, subclass this and add public properties
    /// decorated with your own localized display name, category and description attributes.
    /// </summary>
    [CLSCompliant(false), ComVisible(true)]
    public class NodeProperties : LocalizableProperties,
        ISpecifyPropertyPages,
        IVsGetCfgProvider,
        IVsSpecifyProjectDesignerPages,
        EnvDTE80.IInternalExtenderProvider,
        IVsBrowseObject,
        IVsBuildMacroInfo
    {
        private HierarchyNode node;

        [Browsable(false)]
        [AutomationBrowsable(false)]
        public HierarchyNode Node
        {
            get { return this.node; }
        }

        /// <summary>
        /// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned.
        /// </summary>
        [Browsable(false)]
        [AutomationBrowsable(false)]
        public virtual string Name
        {
            get { return this.node.Caption; }
        }

        internal NodeProperties(HierarchyNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }
            this.node = node;
        }

        public virtual void GetPages(CAUUID[] pages)
        {
            // We do not check whether the supportsProjectDesigner is set to false on the ProjectNode.
            // We rely that the caller knows what to call on us.
            if (pages == null)
            {
                throw new ArgumentNullException("pages");
            }

            if (pages.Length == 0)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
            }

            // behave similar to C#\VB - return empty array
            pages[0] = new CAUUID();
            pages[0].cElems = 0;
        }

        /// <summary>
        /// We support this interface so the build event command dialog can display a list
        /// of tokens for the user to select from.
        /// </summary>
        public int GetBuildMacroValue(string buildMacroName, out string buildMacroValue)
        {
            buildMacroValue = string.Empty;

            if (string.IsNullOrEmpty(buildMacroName) == true)
                return NativeMethods.S_OK;

            if (buildMacroName.Equals("SolutionDir", StringComparison.OrdinalIgnoreCase) ||
                buildMacroName.Equals("SolutionPath", StringComparison.OrdinalIgnoreCase) ||
                buildMacroName.Equals("SolutionName", StringComparison.OrdinalIgnoreCase) ||
                buildMacroName.Equals("SolutionFileName", StringComparison.OrdinalIgnoreCase) ||
                buildMacroName.Equals("SolutionExt", StringComparison.OrdinalIgnoreCase))
            {
                string solutionPath = Environment.GetEnvironmentVariable("SolutionPath");

                if (buildMacroName.Equals("SolutionDir", StringComparison.OrdinalIgnoreCase))
                {
                    buildMacroValue = Path.GetDirectoryName(solutionPath);
                    return NativeMethods.S_OK;
                }
                else if (buildMacroName.Equals("SolutionPath", StringComparison.OrdinalIgnoreCase))
                {
                    buildMacroValue = solutionPath;
                    return NativeMethods.S_OK;
                }
                else if (buildMacroName.Equals("SolutionName", StringComparison.OrdinalIgnoreCase))
                {
                    buildMacroValue = Path.GetFileNameWithoutExtension((string)solutionPath);
                    return NativeMethods.S_OK;
                }
                else if (buildMacroName.Equals("SolutionFileName", StringComparison.OrdinalIgnoreCase))
                {
                    buildMacroValue = Path.GetFileName((string)solutionPath);
                    return NativeMethods.S_OK;
                }
                else if (buildMacroName.Equals("SolutionExt", StringComparison.OrdinalIgnoreCase))
                {
                    buildMacroValue = Path.GetExtension((string)solutionPath);
                    return NativeMethods.S_OK;
                }
            }

            buildMacroValue = this.Node.ProjectMgr.GetBuildMacroValue(buildMacroName);
            return NativeMethods.S_OK;
        }

        /// <summary>
        /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent.
        /// </summary>
        /// <param name="pages">The pages to return.</param>
        /// <returns></returns>
        public virtual int GetProjectDesignerPages(CAUUID[] pages)
        {
            this.GetCommonPropertyPages(pages);
            return VSConstants.S_OK;
        }

        public virtual int GetCfgProvider(out IVsCfgProvider p)
        {
            p = null;
            return VSConstants.E_NOTIMPL;
        }

        /// <summary>
        /// Maps back to the hierarchy or project item object corresponding to the browse object.
        /// </summary>
        /// <param name="hier">Reference to the hierarchy object.</param>
        /// <param name="itemid">Reference to the project item.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
        public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
        {
            if (this.node == null)
            {
                throw new InvalidOperationException();
            }
            hier = Node.ProjectMgr.InteropSafeIVsHierarchy;
            itemid = this.node.ID;
            return VSConstants.S_OK;
        }

        /// <summary>
        /// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base
        /// </summary>
        /// <returns>Caption of Hierarchy node instance</returns>
        public override string GetComponentName()
        {
            string caption = this.Node.Caption;
            if (string.IsNullOrEmpty(caption))
            {
                return base.GetComponentName();
            }
            else
            {
                return caption;
            }
        }

        public string GetProperty(string name, string def)
        {
            string a = this.Node.ItemNode.GetMetadata(name);
            return (a == null) ? def : a;
        }

        public void SetProperty(string name, string value)
        {
            this.Node.ItemNode.SetMetadata(name, value);
        }

        /// <summary>
        /// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support
        /// configuration independent properties.
        /// </summary>
        /// <param name="pages">The pages to return.</param>
        private void GetCommonPropertyPages(CAUUID[] pages)
        {
            // We do not check whether the supportsProjectDesigner is set to false on the ProjectNode.
            // We rely that the caller knows what to call on us.
            if (pages == null)
            {
                throw new ArgumentNullException("pages");
            }

            if (pages.Length == 0)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
            }

            // Only the project should show the property page the rest should show the project properties.
            if (this.node != null && (this.node is ProjectNode))
            {
                // Retrieve the list of guids from hierarchy properties.
                // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
                string guidsList = String.Empty;
                IVsHierarchy hierarchy = Node.ProjectMgr.InteropSafeIVsHierarchy;
                object variant = null;
                ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant));
                guidsList = (string)variant;

                Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
                if (guids == null || guids.Length == 0)
                {
                    pages[0] = new CAUUID();
                    pages[0].cElems = 0;
                }
                else
                {
                    pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
                }
            }
            else
            {
                pages[0] = new CAUUID();
                pages[0].cElems = 0;
            }
        }

        bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject)
        {
            IVsHierarchy outerHierarchy = Node.ProjectMgr.InteropSafeIVsHierarchy;
            if (outerHierarchy is EnvDTE80.IInternalExtenderProvider)
            {
                return ((EnvDTE80.IInternalExtenderProvider)outerHierarchy).CanExtend(extenderCATID, extenderName, extendeeObject);
            }
            return false;
        }

        object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie)
        {
            IVsHierarchy outerHierarchy = Node.ProjectMgr.InteropSafeIVsHierarchy;
            if (outerHierarchy is EnvDTE80.IInternalExtenderProvider)
            {
                return ((EnvDTE80.IInternalExtenderProvider)outerHierarchy).GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie);
            }
            return null;
        }

        object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject)
        {
            IVsHierarchy outerHierarchy = Node.ProjectMgr.InteropSafeIVsHierarchy;
            if (outerHierarchy is EnvDTE80.IInternalExtenderProvider)
            {
                return ((EnvDTE80.IInternalExtenderProvider)outerHierarchy).GetExtenderNames(extenderCATID, extendeeObject);
            }
            return null;
        }

        [Browsable(false)]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CATID")]
        public virtual string ExtenderCATID
        {
            get
            {
                Guid catid = this.Node.ProjectMgr.GetCATIDForType(this.GetType());
                if (Guid.Empty.CompareTo(catid) == 0)
                {
                    return null;
                }
                return catid.ToString("B");
            }
        }

        [Browsable(false)]
        public object ExtenderNames()
        {
            EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders));
            Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object");
            if (extenderService == null)
            {
                throw new InvalidOperationException();
            }
            return extenderService.GetExtenderNames(this.ExtenderCATID, this);
        }

        public object Extender(string extenderName)
        {
            EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders));
            Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object");
            if (extenderService == null)
            {
                throw new InvalidOperationException();
            }
            return extenderService.GetExtender(this.ExtenderCATID, extenderName, this);
        }
    }

    internal sealed class BuildActionPropertyDescriptor : DesignPropertyDescriptor
    {
        private readonly BuildActionConverter converter;

        /// <summary>
        /// Return type converter for property
        /// </summary>
        public override TypeConverter Converter
        {
            get
            {
                return this.converter;
            }
        }

        /// <summary>
        /// Constructor.  Copy the base property descriptor and also hold a pointer
        /// to it for calling its overridden abstract methods.
        /// </summary>
        internal BuildActionPropertyDescriptor(PropertyDescriptor prop, BuildActionConverter converter)
            : base(prop)
        {
            this.converter = converter;
        }
    }

    [CLSCompliant(false), ComVisible(true)]
    public abstract class BuildableNodeProperties : NodeProperties
    {
        /// <summary>
        /// Specifies the build action as a projBuildAction so that automation can get the
        /// expected enum value.
        /// </summary>
        [SRCategoryAttribute(SR.Advanced)]
        [LocDisplayName(SR.BuildAction)]
        [SRDescriptionAttribute(SR.BuildActionDescription)]
        [TypeConverter(typeof(BuildActionTypeConverter))]
        public VSLangProj.prjBuildAction BuildAction
        {
            get
            {
                var res = BuildActionTypeConverter.Instance.ConvertFromString(this.Node.ProjectMgr.BuildActionConverter, this.Node.ItemNode.ItemName);
                if (res is VSLangProj.prjBuildAction)
                {
                    return (VSLangProj.prjBuildAction)res;
                }
                return VSLangProj.prjBuildAction.prjBuildActionNone;
            }
            set
            {
                this.Node.ItemNode.ItemName = BuildActionTypeConverter.Instance.ConvertToString(this.Node.ProjectMgr.BuildActionConverter, value);
            }
        }

        [Browsable(false)]
        [AutomationBrowsable(true)]
        public virtual string ItemType
        {
            get
            {
                return BuildActionTypeConverter.Instance.ConvertToString(this.Node.ProjectMgr.BuildActionConverter, this.BuildAction);
            }
            set
            {
                var res = BuildActionTypeConverter.Instance.ConvertFromString(this.Node.ProjectMgr.BuildActionConverter, value);
                if (res is VSLangProj.prjBuildAction)
                {
                    this.BuildAction = (VSLangProj.prjBuildAction)res;
                }
                else
                {
                    this.BuildAction = VSLangProj.prjBuildAction.prjBuildActionNone;
                }
            }
        }

        public override PropertyDescriptor CreateDesignPropertyDescriptor(PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.PropertyType.Equals(typeof(BuildAction)))
            {
                return new BuildActionPropertyDescriptor(propertyDescriptor, this.Node.ProjectMgr.BuildActionConverter);
            }
            return base.CreateDesignPropertyDescriptor(propertyDescriptor);
        }

        internal BuildableNodeProperties(HierarchyNode node) : base(node) { }
    }

    class BuildActionTypeConverter : StringConverter
    {
        internal static readonly BuildActionTypeConverter Instance = new BuildActionTypeConverter();

        public BuildActionTypeConverter()
        {
        }

        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (sourceType == typeof(string)) ? true : base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return (destinationType == typeof(string)) ? true : base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                var reply = ConvertToString(GetBuildActionConverter(context), value);
                if (reply != null) return reply;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        public string ConvertToString(BuildActionConverter buildActionConverter, object value)
        {
            switch ((VSLangProj.prjBuildAction)value)
            {
            case VSLangProj.prjBuildAction.prjBuildActionCompile:
                return "Compile";
            case VSLangProj.prjBuildAction.prjBuildActionContent:
                return "Content";
            case VSLangProj.prjBuildAction.prjBuildActionEmbeddedResource:
                return "EmbeddedResource";
            case VSLangProj.prjBuildAction.prjBuildActionNone:
                return "None";
            default:
                if (buildActionConverter != null)
                {
                    // Not standard buildAction, so must have been registered.
                    // Convert it to the name of the BuildAction at position index in the StandardValues from the BuildActionConverter
                    int index = (int)value;
                    var actions = buildActionConverter.RegisteredBuildActions;
                    if (index >= 0 && index < actions.Count)
                    {
                        return actions[index].Name;
                    }
                }
                return "None";
            }
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                var reply = ConvertFromString(GetBuildActionConverter(context), (string)value);
                if (reply != null) return reply;
            }
            return base.ConvertFrom(context, culture, value);
        }

        public object ConvertFromString(BuildActionConverter buildActionConverter, string value)
        {
            if (value.Equals("Compile", StringComparison.OrdinalIgnoreCase))
            {
                return VSLangProj.prjBuildAction.prjBuildActionCompile;
            }
            else if (value.Equals("Content", StringComparison.OrdinalIgnoreCase))
            {
                return VSLangProj.prjBuildAction.prjBuildActionContent;
            }
            else if (value.Equals("EmbeddedResource", StringComparison.OrdinalIgnoreCase))
            {
                return VSLangProj.prjBuildAction.prjBuildActionEmbeddedResource;
            }
            else if (value.Equals("None", StringComparison.OrdinalIgnoreCase))
            {
                return VSLangProj.prjBuildAction.prjBuildActionNone;
            }
            else
            {
                if (buildActionConverter != null)
                {
                    // Not standard buildAction, so must have been registered.
                    // Convert it to the index in the StandardValues from the BuildActionConverter.
                    var actions = buildActionConverter.RegisteredBuildActions;
                    var reply = actions.ToList().FindIndex(i => value.Equals(i.Name, StringComparison.OrdinalIgnoreCase));
                    if (reply != -1) return (VSLangProj.prjBuildAction)reply;
                }
            }
            return VSLangProj.prjBuildAction.prjBuildActionNone;
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var buildActionConverter = GetBuildActionConverter(context);
            if(buildActionConverter != null)
            {
                var results = new List<VSLangProj.prjBuildAction>();
                foreach (var a in buildActionConverter.RegisteredBuildActions)
                {
                    results.Add((VSLangProj.prjBuildAction)this.ConvertFrom(context, CultureInfo.CurrentUICulture, a.Name));
                }
                return new StandardValuesCollection(results);
            }
            else
            {
                return new StandardValuesCollection(new[] { VSLangProj.prjBuildAction.prjBuildActionNone, VSLangProj.prjBuildAction.prjBuildActionCompile, VSLangProj.prjBuildAction.prjBuildActionContent, VSLangProj.prjBuildAction.prjBuildActionEmbeddedResource });
            }
        }

        private static BuildActionConverter GetBuildActionConverter(ITypeDescriptorContext context)
        {
            if (context != null)
            {
                BuildableNodeProperties nodeProperties = context.Instance as BuildableNodeProperties;
                if (nodeProperties != null)
                {
                    return nodeProperties.Node.ProjectMgr.BuildActionConverter;
                }
            }
            return null;
        }
    }

    [CLSCompliant(false), ComVisible(true)]
    public class FileNodeProperties : BuildableNodeProperties
    {
        [SRCategoryAttribute(SR.Advanced)]
        [LocDisplayName(SR.CopyToOutputDirectory)]
        [SRDescriptionAttribute(SR.CopyToOutputDirectoryDescription)]
        public virtual CopyToOutputDirectory CopyToOutputDirectory
        {
            get
            {
                string value = this.Node.ItemNode.GetEvaluatedMetadata(ProjectFileConstants.CopyToOutputDirectory);
                if (string.IsNullOrEmpty(value))
                {
                    return CopyToOutputDirectory.DoNotCopy;
                }
                return (CopyToOutputDirectory)Enum.Parse(typeof(CopyToOutputDirectory), value);
            }
            set
            {
                if (value == CopyToOutputDirectory.DoNotCopy)
                    this.Node.ItemNode.SetMetadata(ProjectFileConstants.CopyToOutputDirectory, null);
                else
                    this.Node.ItemNode.SetMetadata(ProjectFileConstants.CopyToOutputDirectory, value.ToString());
            }
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.FileName)]
        [SRDescriptionAttribute(SR.FileNameDescription)]
        public string FileName
        {
            get
            {
                return this.Node.Caption;
            }
            set
            {
                this.Node.SetEditLabel(value);
            }
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.FullPath)]
        [SRDescriptionAttribute(SR.FullPathDescription)]
        public string FullPath
        {
            get
            {
                return this.Node.Url;
            }
        }

        [Browsable(false)]
        public string Extension
        {
            get
            {
                return Path.GetExtension(this.Node.Caption);
            }
        }

        internal FileNodeProperties(HierarchyNode node)
            : base(node)
        {
        }

        public override string GetClassName()
        {
            return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture);
        }
    }

    [CLSCompliant(false), ComVisible(true)]
    public class DependentFileNodeProperties : BuildableNodeProperties
    {
        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.FileName)]
        [SRDescriptionAttribute(SR.FileNameDescription)]
        public virtual string FileName
        {
            get
            {
                return this.Node.Caption;
            }
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.FullPath)]
        [SRDescriptionAttribute(SR.FullPathDescription)]
        public string FullPath
        {
            get
            {
                return this.Node.Url;
            }
        }

        internal DependentFileNodeProperties(HierarchyNode node)
            : base(node)
        {
        }

        public override string GetClassName()
        {
            return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture);
        }
    }

    [CLSCompliant(false), ComVisible(true)]
    public class ProjectNodeProperties : NodeProperties
        , VSLangProj.ProjectProperties
    {
        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.ProjectFolder)]
        [SRDescriptionAttribute(SR.ProjectFolderDescription)]
        [AutomationBrowsable(false)]
        public string ProjectFolder
        {
            get
            {
                return this.Node.ProjectMgr.ProjectFolder;
            }
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.ProjectFile)]
        [SRDescriptionAttribute(SR.ProjectFileDescription)]
        [AutomationBrowsable(false)]
        public string ProjectFile
        {
            get
            {
                return this.Node.ProjectMgr.ProjectFile;
            }
            set
            {
                this.Node.ProjectMgr.ProjectFile = value;
            }
        }

        [Browsable(false)]
        public string FileName
        {
            get
            {
                return this.Node.ProjectMgr.ProjectFile;
            }
            set
            {
                this.Node.ProjectMgr.ProjectFile = value;
            }
        }

        [Browsable(false)]
        public string ReferencePath
        {
            get
            {
                return this.Node.ProjectMgr.GetProjectProperty(ProjectFileConstants.ReferencePath, true);
            }
            set
            {
                this.Node.ProjectMgr.SetProjectProperty(ProjectFileConstants.ReferencePath, value);
            }
        }

        [Browsable(false)]
        public string FullPath
        {
            get
            {
                string fullPath = this.Node.ProjectMgr.ProjectFolder;
                if (!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
                {
                    return fullPath + Path.DirectorySeparatorChar;
                }
                else
                {
                    return fullPath;
                }
            }
        }

        internal ProjectNodeProperties(ProjectNode node)
            : base(node)
        {
        }

        public override string GetClassName()
        {
            return SR.GetString(SR.ProjectProperties, CultureInfo.CurrentUICulture);
        }

        /// <summary>
        /// ICustomTypeDescriptor.GetEditor
        /// To enable the "Property Pages" button on the properties browser
        /// the browse object (project properties) need to be unmanaged
        /// or it needs to provide an editor of type ComponentEditor.
        /// </summary>
        /// <param name="editorBaseType">Type of the editor</param>
        /// <returns>Editor</returns>
        public override object GetEditor(Type editorBaseType)
        {
            // Override the scenario where we are asked for a ComponentEditor
            // as this is how the Properties Browser calls us
            if (editorBaseType == typeof(ComponentEditor))
            {
                IOleServiceProvider sp;
                ErrorHandler.ThrowOnFailure(this.Node.GetSite(out sp));
                return new PropertiesEditorLauncher(new ServiceProvider(sp));
            }

            return base.GetEditor(editorBaseType);
        }

        public override int GetCfgProvider(out IVsCfgProvider p)
        {
            if (this.Node != null && this.Node.ProjectMgr != null)
            {
                return this.Node.ProjectMgr.GetCfgProvider(out p);
            }

            return base.GetCfgProvider(out p);
        }

        string VSLangProj.ProjectProperties.__id
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {
                    var path = this.Node.ProjectMgr.BuildProject.FullPath;
                    return Path.GetFileNameWithoutExtension(path);
                });
            }
        }

        VSLangProj.ProjectConfigurationProperties VSLangProj.ProjectProperties.ActiveConfigurationSettings
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {

                    var buildMgr = this.Node.ProjectMgr.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager;
                    var activeCfg = new IVsProjectCfg[] { null };
                    var hr = buildMgr.FindActiveProjectCfg(IntPtr.Zero, IntPtr.Zero, Node.ProjectMgr.InteropSafeIVsHierarchy, activeCfg);
                    if (ErrorHandler.Succeeded(hr))
                    {
                        return (VSLangProj.ProjectConfigurationProperties)((ProjectConfig)activeCfg[0]).ConfigurationProperties;
                    }
                    else
                    {
                        return null;
                    }
                });
            }
        }

        object VSLangProj.ProjectProperties.__project
        {
            get { return this.Node; }
        }

        string VSLangProj.ProjectProperties.AbsoluteProjectDirectory
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {
                    var path = this.Node.ProjectMgr.BuildProject.FullPath;
                    return Path.GetDirectoryName(path);
                });
            }
        }

        string VSLangProj.ProjectProperties.LocalPath
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {
                    var path = this.Node.ProjectMgr.BuildProject.DirectoryPath;
                    return path;
                });
            }
        }

        string VSLangProj.ProjectProperties.URL
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {
                    var path = this.Node.ProjectMgr.BuildProject.FullPath;
                    return new Uri(path).AbsoluteUri;
                });
            }
        }

        string VSLangProj.ProjectProperties.ActiveFileSharePath
        {
            get { throw new NotImplementedException(); } // E_NOTIMPL
        }

        VSLangProj.prjWebAccessMethod VSLangProj.ProjectProperties.ActiveWebAccessMethod
        {
            get { throw new NotImplementedException(); } // E_NOTIMPL
        }

        string VSLangProj.ProjectProperties.ApplicationIcon
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {
                    return this.Node.ProjectMgr.GetProjectProperty("ApplicationIcon");
                });
            }
            set
            {
                UIThread.DoOnUIThread(() =>
                {
                    this.Node.ProjectMgr.SetProjectProperty("ApplicationIcon", value);
                });
            }
        }

        private string GetProp(string name)
        {
            return UIThread.DoOnUIThread(() =>
            {
                return this.Node.ProjectMgr.GetProjectProperty(name);
            });
        }
        private void SetProp(string name, string value)
        {
            UIThread.DoOnUIThread(() =>
            {
                this.Node.ProjectMgr.SetProjectProperty(name, value);
            });
        }

        string VSLangProj.ProjectProperties.AssemblyKeyContainerName
        {
            get { return this.GetProp("AssemblyKeyContainerName"); }
            set { this.SetProp("AssemblyKeyContainerName", value); }
        }

        string VSLangProj.ProjectProperties.AssemblyName
        {
            get { return this.GetProp("AssemblyName"); }
            set { this.SetProp("AssemblyName", value); }
        }

        string VSLangProj.ProjectProperties.AssemblyOriginatorKeyFile
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        VSLangProj.prjOriginatorKeyMode VSLangProj.ProjectProperties.AssemblyOriginatorKeyMode
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
        VSLangProj.prjScriptLanguage VSLangProj.ProjectProperties.DefaultClientScript
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
        VSLangProj.prjTargetSchema VSLangProj.ProjectProperties.DefaultTargetSchema
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
        VSLangProj.prjHTMLPageLayout VSLangProj.ProjectProperties.DefaultHTMLPageLayout
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        bool VSLangProj.ProjectProperties.DelaySign
        {
            get
            {
                var p = this.GetProp("DelaySign");
                return String.Equals(p, "true", StringComparison.OrdinalIgnoreCase);
            }
            set
            {
                this.SetProp("DelaySign", value ? "true" : "false");
            }
        }

        string VSLangProj.ProjectProperties.FileName
        {
            get
            {
                return UIThread.DoOnUIThread(() =>
                {
                    var path = this.Node.ProjectMgr.BuildProject.FullPath;
                    return Path.GetFileName(path);
                });
            }
            set
            {
                UIThread.DoOnUIThread(() =>
                {
                    var path = this.Node.ProjectMgr.BuildProject.FullPath;
                    var newPath = Path.Combine(Path.GetDirectoryName(path), value);
                    this.Node.ProjectMgr.RenameProjectFile(newPath);
                });
            }
        }

        string VSLangProj.ProjectProperties.FileSharePath
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        bool VSLangProj.ProjectProperties.LinkRepair
        {
            get { return false; }
            set { throw new NotImplementedException(); }
        }

        string VSLangProj.ProjectProperties.OfflineURL
        {
            get { throw new NotImplementedException(); }
        }

        VSLangProj.prjCompare VSLangProj.ProjectProperties.OptionCompare
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        VSLangProj.prjOptionExplicit VSLangProj.ProjectProperties.OptionExplicit
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        VSLangProj.prjOptionStrict VSLangProj.ProjectProperties.OptionStrict
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        private string RootNamespace
        {
            get { return this.GetProp("RootNamespace"); }
            set { this.SetProp("RootNamespace", value); }

        }
        string VSLangProj.ProjectProperties.DefaultNamespace
        {
            get { return this.RootNamespace; }
            set { this.RootNamespace = value; }
        }

        string VSLangProj.ProjectProperties.RootNamespace
        {
            get { return this.RootNamespace; }
            set { this.RootNamespace = value; }
        }

        string VSLangProj.ProjectProperties.ServerExtensionsVersion
        {
            get { throw new NotImplementedException(); }
        }

        string VSLangProj.ProjectProperties.StartupObject
        {
            get { return this.GetProp("StartupObject"); }
            set { this.SetProp("StartupObject", value); }
        }

        VSLangProj.prjWebAccessMethod VSLangProj.ProjectProperties.WebAccessMethod
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        string VSLangProj.ProjectProperties.WebServer
        {
            get { throw new NotImplementedException(); }
        }

        string VSLangProj.ProjectProperties.WebServerVersion
        {
            get { throw new NotImplementedException(); }
        }

        object VSLangProj.ProjectProperties.get_Extender(string name)
        {
            return UIThread.DoOnUIThread(() => this.Extender(name));
        }

        object VSLangProj.ProjectProperties.ExtenderNames
        {
            get { return UIThread.DoOnUIThread(() => this.ExtenderNames()); }
        }

        VSLangProj.prjProjectType VSLangProj.ProjectProperties.ProjectType
        {
            get { return VSLangProj.prjProjectType.prjProjectTypeLocal; }
        }

        private VSLangProj.prjOutputType OutputType
        {
            get
            {
                var typ = this.GetProp(ProjectFileConstants.OutputType);
                switch (typ)
                {
                    case "WinExe": return VSLangProj.prjOutputType.prjOutputTypeWinExe;
                    case "Library": return VSLangProj.prjOutputType.prjOutputTypeLibrary;
                    default: return VSLangProj.prjOutputType.prjOutputTypeExe;
                }
            }
            set
            {
                string propVal;
                switch (value)
                {
                    case VSLangProj.prjOutputType.prjOutputTypeWinExe:
                        propVal = "WinExe";
                        break;
                    case VSLangProj.prjOutputType.prjOutputTypeLibrary:
                        propVal = "Library";
                        break;
                    default:
                        propVal = "Exe";
                        break;
                }
                this.SetProp(ProjectFileConstants.OutputType, propVal);
            }
        }

        VSLangProj.prjOutputType VSLangProj.ProjectProperties.OutputType
        {
            get { return this.OutputType; }
            set { this.OutputType = value; }
        }

        string VSLangProj.ProjectProperties.OutputFileName
        {
            get
            {
                var assemblyName = this.GetProp("AssemblyName");
                string extension;
                switch (this.OutputType)
                {
                    case VSLangProj.prjOutputType.prjOutputTypeLibrary:
                        extension = ".dll";
                        break;
                    default:
                        extension = ".exe";
                        break;
                }
                return assemblyName + extension;
            }
        }
    }

    [CLSCompliant(false), ComVisible(true)]
    public class FolderNodeProperties : NodeProperties
    {
        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.FolderName)]
        [SRDescriptionAttribute(SR.FolderNameDescription)]
        [AutomationBrowsable(false)]
        public string FolderName
        {
            get
            {
                return this.Node.Caption;
            }
            set
            {
                this.Node.SetEditLabel(value);
                this.Node.ReDraw(UIHierarchyElement.Caption);
            }
        }

        [Browsable(false)]
        [AutomationBrowsable(true)]
        public string FileName
        {
            get
            {
                return this.Node.Caption;
            }
            set
            {
                this.Node.SetEditLabel(value);
            }
        }

        [Browsable(false)]
        [AutomationBrowsable(true)]
        public string FullPath
        {
            get
            {
                string fullPath = this.Node.GetMkDocument();
                if (!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
                {
                    return fullPath + Path.DirectorySeparatorChar;
                }
                else
                {
                    return fullPath;
                }
            }
        }

        internal FolderNodeProperties(HierarchyNode node)
            : base(node)
        {
        }

        public override string GetClassName()
        {
            return SR.GetString(SR.FolderProperties, CultureInfo.CurrentUICulture);
        }
    }

    [CLSCompliant(false), ComVisible(true)]
    public class ReferenceNodeProperties : NodeProperties
    {
        bool copyLocalDefault;

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.RefName)]
        [SRDescriptionAttribute(SR.RefNameDescription)]
        [Browsable(true)]
        [AutomationBrowsable(true)]
        public override string Name
        {
            get
            {
                return this.Node.Caption;
            }
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.CopyToLocal)]
        [SRDescriptionAttribute(SR.CopyToLocalDescription)]
        public bool CopyToLocal
        {
            get
            {
                string copyLocal = this.GetProperty(ProjectFileConstants.Private, null);
                if (copyLocal == null || copyLocal.Length == 0)
                    return copyLocalDefault;
                return bool.Parse(copyLocal);
            }
            set
            {
                this.SetProperty(ProjectFileConstants.Private, value.ToString());
            }
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.FullPath)]
        [SRDescriptionAttribute(SR.FullPathDescription)]
        public virtual string FullPath
        {
            get
            {
                return this.Node.Url;
            }
        }

        internal ReferenceNodeProperties(HierarchyNode node)
            : this(node, false)
        {
        }

        internal ReferenceNodeProperties(HierarchyNode node, bool copyLocalDefault)
            : base(node)
        {
            this.copyLocalDefault = copyLocalDefault;
        }

        public override string GetClassName()
        {
            return SR.GetString(SR.ReferenceProperties, CultureInfo.CurrentUICulture);
        }
    }

    class FSharpCoreVersionConverter : StringConverter
    {
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;
        }

        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var props = (FSharpCoreAssemblyReferenceProperties)context.Instance;
            var fsharpCoreVersionLookup = (IFSharpCoreVersionLookupService)props.Node.ProjectMgr.Site.GetService(typeof(IFSharpCoreVersionLookupService));
            var frameworkName = new FrameworkName(props.Node.ProjectMgr.GetTargetFrameworkMoniker());
            var versions = fsharpCoreVersionLookup.ListAvailableFSharpCoreVersions(frameworkName);
            return new StandardValuesCollection(Array.ConvertAll(versions, x => x.Version));
        }
    }

    [ComVisible(true)]
    public class FSharpCoreAssemblyReferenceProperties : ReferenceNodeProperties
    {
        internal FSharpCoreAssemblyReferenceProperties(AssemblyReferenceNode node, bool copyLocalDefault)
            : base(node, copyLocalDefault)
        {
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.Version)]
        [SRDescriptionAttribute(SR.VersionDescription)]
        [TypeConverter(typeof(FSharpCoreVersionConverter))]
        public string Version
        {
            get { return Node.ProjectMgr.TargetFSharpCoreVersion; }
            set
            {
                try
                {
                    Node.ProjectMgr.TargetFSharpCoreVersion = value;
                }
                catch (COMException e)
                {
                    // OLE_E_PROMPTSAVECANCELLED means that user has pressed cancel in 'Proceed with changing reference' dialog
                    // do not propagate it
                    if (e.HResult != VSConstants.OLE_E_PROMPTSAVECANCELLED)
                        throw;
                }
            }
        }
    }

    [ComVisible(true)]
    public class AssemblyReferenceProperties : ReferenceNodeProperties
    {
        internal AssemblyReferenceProperties(AssemblyReferenceNode node, bool copyLocalDefault)
            : base(node, copyLocalDefault)
        {
        }

        [SRCategoryAttribute(SR.Misc)]
        [LocDisplayName(SR.SpecificVersion)]
        [SRDescriptionAttribute(SR.SpecificVersionDescription)]
        public bool SpecificVersion
        {
            get
            {
                string specificVersion = this.GetProperty(ProjectFileConstants.SpecificVersion, null);
                if (string.IsNullOrEmpty(specificVersion))
                {
                    string name = this.GetProperty(ProjectFileConstants.Include, null);
                    return name.IndexOf("Version=", StringComparison.Ordinal) != -1;
                }
                return bool.Parse(specificVersion);
            }
            set
            {
                if (value)
                {
                    AssemblyReferenceNode me = (AssemblyReferenceNode)Node;
                    // we want to set a specific version, e.g. "System, Version=2.0.0.0",
                    // but this requires having successfully resolved the reference
                    if (me.ResolvedAssembly == null)
                    {
                        me.DoOneOffResolve();
                    }
                    if (me.ResolvedAssembly != null)
                    {
                        this.Node.ItemNode.Rename(me.ResolvedAssembly.FullName);
                        // Note: line above is logical equivalent of line below, but Include is a special property with special Rename() OM
                        //this.SetProperty(ProjectFileConstants.Include, me.AssemblyName.FullName);
                        this.SetProperty(ProjectFileConstants.SpecificVersion, "True");
                    }
                    else
                    {
                        // Could not resolve the reference, e.g. because someone changed the .fsproj file
                        // to point to a non-existent file on disk.  In this case there is nothing we can do,
                        // so fail silently (that's what C# does).
                    }
                }
                else
                {
                    this.SetProperty(ProjectFileConstants.SpecificVersion, "False");
                }
            }
        }

    }

    [ComVisible(true)]
    public class ProjectReferencesProperties : ReferenceNodeProperties
    {
        internal ProjectReferencesProperties(ProjectReferenceNode node)
            : base(node, true)
        {
        }

        public override string FullPath
        {
            get
            {
                return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath;
            }
        }
    }
}


text:
package haus

// Environment represents a single environment from the haus config file.
type Environment struct {
	Name string
	Requirements []string
	Variables map[string]string
}


text:
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db.models import Q
from django.db import connection

from api.api_views import APIView
# noinspection PyProtectedMember
from api.fields import get_boolean_value
from api.status import HTTP_201_CREATED, HTTP_200_OK
from api.signals import user_relationship_changed
from api.exceptions import PermissionDenied
from api.accounts.user.base.serializers import ApiKeysSerializer, UserSerializer, ExtendedUserSerializer
from api.accounts.user.utils import get_user, get_users
from api.accounts.messages import LOG_USER_CREATE, LOG_USER_UPDATE, LOG_USER_DELETE
from api.task.response import SuccessTaskResponse, FailureTaskResponse
from gui.models import User, AdminPermission
from vms.models import Dc

class UserView(APIView):
    serializer = UserSerializer
    dc_bound = False
    order_by_default = order_by_fields = ('username',)
    order_by_field_map = {'created': 'id'}

    def __init__(self, request, username, data, many=False):
        super(UserView, self).__init__(request)
        self.username = username
        self.data = data
        self.many = many
        sr = ('dc_bound', 'default_dc')
        pr = ()

        if not settings.ACL_ENABLED and self.data:
            self.data.pop('groups', None)

        if self.extended:
            self.serializer = ExtendedUserSerializer
            pr = ('roles__dc_set',)

        if username:
            self.user = get_user(request, username, sr=sr, pr=pr, data=data)
        else:
            if self.full or self.extended:
                if self.extended:
                    pr = ('roles', 'roles__dc_set')
                else:
                    pr = ('roles',)
            else:
                sr = ()
                pr = ()

            self.user = get_users(request, data=data, sr=sr, pr=pr, where=Q(is_active=self.active),
                                  order_by=self.order_by)

    def is_active(self, data):
        return self.request.method == 'GET' and get_boolean_value(data.get('active', True))

    @property
    def active(self):
        if self.data:
            return self.is_active(self.data)
        else:
            return True

    def user_modify(self, update=False, serializer=None):
        affected_groups = ()

        if not serializer:
            serializer = self.serializer

        user = self.user
        ser = serializer(self.request, user, data=self.data, partial=update)

        if not ser.is_valid():
            return FailureTaskResponse(self.request, ser.errors, obj=user, dc_bound=False)

        ser.save()
        if update:
            msg = LOG_USER_UPDATE
            status = HTTP_200_OK
        else:
            msg = LOG_USER_CREATE
            status = HTTP_201_CREATED

        res = SuccessTaskResponse(self.request, ser.data, status=status, obj=user, msg=msg, owner=ser.object,
                                  detail_dict=ser.detail_dict(), dc_bound=False)
        task_id = res.data.get('task_id')

        if serializer == UserSerializer:
            # User's is_staff attribute was changed -> Clear the cached list of super admins
            if ser.is_staff_changed:
                User.clear_super_admin_ids()

            # User's groups were changed, which may affect the cached list of DC admins for DCs which are attached
            # to these groups. So we need to clear the list of admins cached for each affected DC
            # noinspection PyProtectedMember
            if user._roles_to_save is not None:
                # noinspection PyProtectedMember
                affected_groups = set(user._roles_to_save)
                affected_groups.update(ser.old_roles)
                affected_dcs = Dc.objects.distinct().filter(roles__in=affected_groups,
                                                            roles__permissions__id=AdminPermission.id)
                for dc in affected_dcs:
                    User.clear_dc_admin_ids(dc)

            # User was removed from some groups and may loose access to DCs which are attached to this group
            # So we better set his current_dc to default_dc
            if ser.old_roles and not user.is_staff:
                user.reset_current_dc()

        connection.on_commit(lambda: user_relationship_changed.send(task_id, user_name=user.username,  # Signal!
                                                                    affected_groups=tuple(
                                                                        group.id for group in affected_groups)))
        return res

    def get(self):
        return self._get(self.user, self.data, self.many, field_name='username')

    def post(self):
        if not self.request.user.is_staff and self.data:
            self.data.pop('dc_bound', None)  # default DC binding cannot be changed when creating object

        return self.user_modify(update=False)

    def put(self):
        return self.user_modify(update=True)

    def delete(self):
        user = self.user
        # Predefined users can not be deleted
        if user.id in (settings.ADMIN_USER, settings.SYSTEM_USER, self.request.user.id):
            raise PermissionDenied

        relations = user.get_relations()
        if relations:
            message = {
                'detail': _('Cannot delete user, because he has relations to some objects.'),
                'relations': relations
            }
            return FailureTaskResponse(self.request, message, obj=user, dc_bound=False)

        dd = {'email': user.email, 'date_joined': user.date_joined}
        username = user.username
        was_staff = user.is_staff
        old_roles = list(user.roles.all())
        ser = self.serializer(self.request, user)
        ser.object.delete()

        res = SuccessTaskResponse(self.request, None, obj=user, msg=LOG_USER_DELETE, detail_dict=dd, dc_bound=False)
        task_id = res.data.get('task_id')
        connection.on_commit(lambda: user_relationship_changed.send(task_id, user_name=username,  # Signal!
                                                                    affected_groups=tuple(
                                                                        group.id for group in old_roles)))

        # User was removed, which may affect the cached list of DC admins for DCs which are attached to user's groups
        # So we need to clear the list of admins cached for each affected DC
        affected_dcs = Dc.objects.distinct().filter(roles__in=old_roles, roles__permissions__id=AdminPermission.id)
        for dc in affected_dcs:
            User.clear_dc_admin_ids(dc)

        if was_staff:
            User.clear_super_admin_ids()

        return res

    def api_key(self):
        # Allow show and regenerate API keys only for logged in users
        if self.request.auth == 'api_key':
            raise PermissionDenied

        if self.request.method.lower() == 'get':
            return self._get(self.user, self.data, serializer=ApiKeysSerializer)
        else:
            # noinspection PyTypeChecker
            return self.user_modify(update=True, serializer=ApiKeysSerializer)


text:
set -e

LN_TARGET="$COURSEBUILDER_RESOURCES"
LN_SOURCE="$SOURCE_DIR/lib"

# Declare resources subject to static serving. OS X is still on bash 3.x, so we
# have to fake out associative arrays rather than use declare -A.
STATIC_SERV=( \
    "codemirror-4.5.0:/static/codemirror"
    "crossfilter-1.3.7:/static/crossfilter-1.3.7"
    "d3-3.4.3:/static/d3-3.4.3"
    "dagre-0.7.4:/static/dagre-0.7.4"
    "dagre-d3-0.4.17p:/static/dagre-d3-0.4.17p"
    "dc.js-1.6.0:/static/dc.js-1.6.0"
    "dependo-0.1.4:/static/dependo-0.1.4"
    "inputex-3.1.0:/static/inputex-3.1.0"
    "jquery-2.2.4:/static/jquery"
    "jqueryui-1.11.4:/static/jqueryui"
    "material-design-iconic-font-1.1.1:/static/material-design-icons"
    "underscore-1.4.3:/static/underscore-1.4.3"
    "yui_2in3-2.9.0:/static/2in3"
    "yui_3.6.0:/static/yui_3.6.0"
    "polymer-1.2.0:/static/polymer-1.2.0" \
)

# Prepare files for static serving
if [ "$ALLOW_STATIC_SERV" = true ] ; then
  echo Static serving enabled

  # Prepare target directory for static files; use symlink to
  # $COURSEBUILDER_RESOURCES to avoid polluting current view
  if [ ! -d "$LN_TARGET/_static/" ]; then
    mkdir "$COURSEBUILDER_RESOURCES/_static/"
  fi
  if [ ! -L "$LN_SOURCE/_static" -a ! -d "$LN_SOURCE/_static" ]; then
    ln -s "$COURSEBUILDER_RESOURCES/_static/" "$LN_SOURCE/"
  fi

  # Unzip required files
  for entry in "${STATIC_SERV[@]}"; do
    KEY="${entry%%:*}"
    if [ ! -f "$LN_SOURCE/_static/$KEY/.gcb_install_succeeded" ]; then
      echo "Unzipping $KEY.zip into $LN_SOURCE/_static/$KEY"
      unzip -o "$DISTRIBUTED_LIBS_DIR/$KEY.zip" \
          -d "$LN_SOURCE/_static/$KEY" > /dev/null
      touch "$LN_SOURCE/_static/$KEY/.gcb_install_succeeded"
    fi
  done
else
  echo Static serving disabled

  # Remove all static files
  if [ -d "$LN_TARGET/_static/" ]; then
    rm -rf "$LN_TARGET/_static/"
  fi
  if [ -L "$LN_SOURCE/_static" ]; then
    rm "$LN_SOURCE/_static"
  fi
fi

# Generate static serving config file; we do pay special attention to '\n'
# characters and their expansion
STATIC_YAML_TEXT=""
STATIC_YAML_TEXT="# GENERATED; DO NOT MODIFY"$'\n'
STATIC_YAML_TEXT+=$"env_variables:"$'\n'
STATIC_YAML_TEXT+=$"  GCB_STATIC_SERV_ENABLED: $ALLOW_STATIC_SERV"$'\n'
if [ "$ALLOW_STATIC_SERV" = true ] ; then
  STATIC_YAML_TEXT+=$"handlers:"$'\n'
  for entry in "${STATIC_SERV[@]}"; do
    KEY=${entry%%:*}
    VALUE=${entry#*:}
    STATIC_YAML_TEXT+=$"- url: $VALUE"$'\n'
    STATIC_YAML_TEXT+=$"  static_dir: lib/_static/$KEY"$'\n'
    STATIC_YAML_TEXT+=$"  expiration: 10m"$'\n'
  done

  # Also serve a directory for html imports
  STATIC_YAML_TEXT+=$"- url: /static/html-imports"$'\n'
  STATIC_YAML_TEXT+=$"  static_dir: lib/_static/html-imports"$'\n'
  STATIC_YAML_TEXT+=$"  expiration: 10m"$'\n'
fi

# '\n' at EOF is truncated, unless followed by another character, like ' '
STATIC_YAML_TEXT+=$' '

# Write out a new static.yaml, if content differs or file does not exist;
# we do NOT want to override this file all the time as there maybe another
# test running concurrently that uses it at this very moment
STATIC_YAML="$SOURCE_DIR/static.yaml"
CURRENT_STATIC_YAML_TEXT=""
if [ -f "$STATIC_YAML" ]; then
  CURRENT_STATIC_YAML_TEXT=$(< "$STATIC_YAML")
fi
if [ "$CURRENT_STATIC_YAML_TEXT" = "$STATIC_YAML_TEXT" ]; then
  echo Using current "$STATIC_YAML"
else
  echo Creating new "$STATIC_YAML"
  echo "$STATIC_YAML_TEXT" > "$STATIC_YAML"
fi


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
             xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
             targetNamespace="Examples">
    <process id="process" isExecutable="true">
        <startEvent id="startEvent" name="StartEvent">
            <timerEventDefinition>
                <timeCycle>R2/2021-07-01T19:22:00Z/P1D</timeCycle>
            </timerEventDefinition>
        </startEvent>
        <sequenceFlow id="start2Script" sourceRef="startEvent" targetRef="scriptExecutor"></sequenceFlow>

        <scriptTask id="scriptExecutor" name="Script Executor" scriptFormat="groovy">
            <script>execution.setVariable("executed", true)</script>
        </scriptTask>

        <sequenceFlow id="script2Task" sourceRef="scriptExecutor" targetRef="task1"></sequenceFlow>
        <userTask id="task1" name="Task A"/>
        <sequenceFlow id="task2End" sourceRef="scriptExecutor" targetRef="endEvent"></sequenceFlow>
        <endEvent id="endEvent"></endEvent>
    </process>
</definitions>


text:
#include "curl_setup.h"

#include "urldata.h"
#include "sendf.h"
#include "select.h"
#include "progress.h"
#include "speedcheck.h"
#include "pingpong.h"
#include "multiif.h"
#include "non-ascii.h"
#include "sslgen.h"

#define _MPRINTF_REPLACE /* use our functions only */
#include <XMCurl/mprintf.h>

#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"

#ifdef USE_PINGPONG

/* Returns timeout in ms. 0 or negative number means the timeout has already
   triggered */
long Curl_pp_state_timeout(struct pingpong *pp)
{
  struct connectdata *conn = pp->conn;
  struct SessionHandle *data=conn->data;
  long timeout_ms; /* in milliseconds */
  long timeout2_ms; /* in milliseconds */
  long response_time= (data->set.server_response_timeout)?
    data->set.server_response_timeout: pp->response_time;

  /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine
     remaining time, or use pp->response because SERVER_RESPONSE_TIMEOUT is
     supposed to govern the response for any given server response, not for
     the time from connect to the given server response. */

  /* Without a requested timeout, we only wait 'response_time' seconds for the
     full response to arrive before we bail out */
  timeout_ms = response_time -
    Curl_tvdiff(Curl_tvnow(), pp->response); /* spent time */

  if(data->set.timeout) {
    /* if timeout is requested, find out how much remaining time we have */
    timeout2_ms = data->set.timeout - /* timeout time */
      Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */

    /* pick the lowest number */
    timeout_ms = CURLMIN(timeout_ms, timeout2_ms);
  }

  return timeout_ms;
}

/*
 * Curl_pp_statemach()
 */
CURLcode Curl_pp_statemach(struct pingpong *pp, bool block)
{
  struct connectdata *conn = pp->conn;
  curl_socket_t sock = conn->sock[FIRSTSOCKET];
  int rc;
  long interval_ms;
  long timeout_ms = Curl_pp_state_timeout(pp);
  struct SessionHandle *data=conn->data;
  CURLcode result = CURLE_OK;

  if(timeout_ms <=0 ) {
    failf(data, "server response timeout");
    return CURLE_OPERATION_TIMEDOUT; /* already too little time */
  }

  if(block) {
    interval_ms = 1000;  /* use 1 second timeout intervals */
    if(timeout_ms < interval_ms)
      interval_ms = timeout_ms;
  }
  else
    interval_ms = 0; /* immediate */

  if(Curl_pp_moredata(pp))
    /* We are receiving and there is data in the cache so just read it */
    rc = 1;
  else if(!pp->sendleft && Curl_ssl_data_pending(conn, FIRSTSOCKET))
    /* We are receiving and there is data ready in the SSL library */
    rc = 1;
  else
    rc = Curl_socket_ready(pp->sendleft?CURL_SOCKET_BAD:sock, /* reading */
                           pp->sendleft?sock:CURL_SOCKET_BAD, /* writing */
                           interval_ms);

  if(block) {
    /* if we didn't wait, we don't have to spend time on this now */
    if(Curl_pgrsUpdate(conn))
      result = CURLE_ABORTED_BY_CALLBACK;
    else
      result = Curl_speedcheck(data, Curl_tvnow());

    if(result)
      return result;
  }

  if(rc == -1) {
    failf(data, "select/poll error");
    result = CURLE_OUT_OF_MEMORY;
  }
  else if(rc)
    result = pp->statemach_act(conn);

  return result;
}

/* initialize stuff to prepare for reading a fresh new response */
void Curl_pp_init(struct pingpong *pp)
{
  struct connectdata *conn = pp->conn;
  pp->nread_resp = 0;
  pp->linestart_resp = conn->data->state.buffer;
  pp->pending_resp = TRUE;
  pp->response = Curl_tvnow(); /* start response time-out now! */
}

/***********************************************************************
 *
 * Curl_pp_vsendf()
 *
 * Send the formated string as a command to a pingpong server. Note that
 * the string should not have any CRLF appended, as this function will
 * append the necessary things itself.
 *
 * made to never block
 */
CURLcode Curl_pp_vsendf(struct pingpong *pp,
                        const char *fmt,
                        va_list args)
{
  ssize_t bytes_written;
  size_t write_len;
  char *fmt_crlf;
  char *s;
  CURLcode error;
  struct connectdata *conn = pp->conn;
  struct SessionHandle *data = conn->data;

#ifdef HAVE_GSSAPI
  enum protection_level data_sec = conn->data_prot;
#endif

  DEBUGASSERT(pp->sendleft == 0);
  DEBUGASSERT(pp->sendsize == 0);
  DEBUGASSERT(pp->sendthis == NULL);

  fmt_crlf = aprintf("%s\r\n", fmt); /* append a trailing CRLF */
  if(!fmt_crlf)
    return CURLE_OUT_OF_MEMORY;

  s = vaprintf(fmt_crlf, args); /* trailing CRLF appended */
  free(fmt_crlf);
  if(!s)
    return CURLE_OUT_OF_MEMORY;

  bytes_written = 0;
  write_len = strlen(s);

  Curl_pp_init(pp);

  error = Curl_convert_to_network(data, s, write_len);
  /* Curl_convert_to_network calls failf if unsuccessful */
  if(error) {
    free(s);
    return error;
  }

#ifdef HAVE_GSSAPI
  conn->data_prot = PROT_CMD;
#endif
  error = Curl_write(conn, conn->sock[FIRSTSOCKET], s, write_len,
                     &bytes_written);
#ifdef HAVE_GSSAPI
  DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST);
  conn->data_prot = data_sec;
#endif

  if(error) {
    free(s);
    return error;
  }

  if(conn->data->set.verbose)
    Curl_debug(conn->data, CURLINFO_HEADER_OUT,
               s, (size_t)bytes_written, conn);

  if(bytes_written != (ssize_t)write_len) {
    /* the whole chunk was not sent, keep it around and adjust sizes */
    pp->sendthis = s;
    pp->sendsize = write_len;
    pp->sendleft = write_len - bytes_written;
  }
  else {
    free(s);
    pp->sendthis = NULL;
    pp->sendleft = pp->sendsize = 0;
    pp->response = Curl_tvnow();
  }

  return CURLE_OK;
}

/***********************************************************************
 *
 * Curl_pp_sendf()
 *
 * Send the formated string as a command to a pingpong server. Note that
 * the string should not have any CRLF appended, as this function will
 * append the necessary things itself.
 *
 * made to never block
 */
CURLcode Curl_pp_sendf(struct pingpong *pp,
                       const char *fmt, ...)
{
  CURLcode res;
  va_list ap;
  va_start(ap, fmt);

  res = Curl_pp_vsendf(pp, fmt, ap);

  va_end(ap);

  return res;
}

/*
 * Curl_pp_readresp()
 *
 * Reads a piece of a server response.
 */
CURLcode Curl_pp_readresp(curl_socket_t sockfd,
                          struct pingpong *pp,
                          int *code, /* return the server code if done */
                          size_t *size) /* size of the response */
{
  ssize_t perline; /* count bytes per line */
  bool keepon=TRUE;
  ssize_t gotbytes;
  char *ptr;
  struct connectdata *conn = pp->conn;
  struct SessionHandle *data = conn->data;
  char * const buf = data->state.buffer;
  CURLcode result = CURLE_OK;

  *code = 0; /* 0 for errors or not done */
  *size = 0;

  ptr=buf + pp->nread_resp;

  /* number of bytes in the current line, so far */
  perline = (ssize_t)(ptr-pp->linestart_resp);

  keepon=TRUE;

  while((pp->nread_resp<BUFSIZE) && (keepon && !result)) {

    if(pp->cache) {
      /* we had data in the "cache", copy that instead of doing an actual
       * read
       *
       * pp->cache_size is cast to ssize_t here.  This should be safe, because
       * it would have been populated with something of size int to begin
       * with, even though its datatype may be larger than an int.
       */
      DEBUGASSERT((ptr+pp->cache_size) <= (buf+BUFSIZE+1));
      memcpy(ptr, pp->cache, pp->cache_size);
      gotbytes = (ssize_t)pp->cache_size;
      free(pp->cache);    /* free the cache */
      pp->cache = NULL;   /* clear the pointer */
      pp->cache_size = 0; /* zero the size just in case */
    }
    else {
      int res;
#ifdef HAVE_GSSAPI
      enum protection_level prot = conn->data_prot;
      conn->data_prot = PROT_CLEAR;
#endif
      DEBUGASSERT((ptr+BUFSIZE-pp->nread_resp) <= (buf+BUFSIZE+1));
      res = Curl_read(conn, sockfd, ptr, BUFSIZE-pp->nread_resp,
                      &gotbytes);
#ifdef HAVE_GSSAPI
      DEBUGASSERT(prot  > PROT_NONE && prot < PROT_LAST);
      conn->data_prot = prot;
#endif
      if(res == CURLE_AGAIN)
        return CURLE_OK; /* return */

      if((res == CURLE_OK) && (gotbytes > 0))
        /* convert from the network encoding */
        res = Curl_convert_from_network(data, ptr, gotbytes);
      /* Curl_convert_from_network calls failf if unsuccessful */

      if(CURLE_OK != res) {
        result = (CURLcode)res; /* Set outer result variable to this error. */
        keepon = FALSE;
      }
    }

    if(!keepon)
      ;
    else if(gotbytes <= 0) {
      keepon = FALSE;
      result = CURLE_RECV_ERROR;
      failf(data, "response reading failed");
    }
    else {
      /* we got a whole chunk of data, which can be anything from one
       * byte to a set of lines and possible just a piece of the last
       * line */
      ssize_t i;
      ssize_t clipamount = 0;
      bool restart = FALSE;

      data->req.headerbytecount += (long)gotbytes;

      pp->nread_resp += gotbytes;
      for(i = 0; i < gotbytes; ptr++, i++) {
        perline++;
        if(*ptr=='\n') {
          /* a newline is CRLF in pp-talk, so the CR is ignored as
             the line isn't really terminated until the LF comes */

          /* output debug output if that is requested */
#ifdef HAVE_GSSAPI
          if(!conn->sec_complete)
#endif
            if(data->set.verbose)
              Curl_debug(data, CURLINFO_HEADER_IN,
                         pp->linestart_resp, (size_t)perline, conn);

          /*
           * We pass all response-lines to the callback function registered
           * for "headers". The response lines can be seen as a kind of
           * headers.
           */
          result = Curl_client_write(conn, CLIENTWRITE_HEADER,
                                     pp->linestart_resp, perline);
          if(result)
            return result;

          if(pp->endofresp(conn, pp->linestart_resp, perline, code)) {
            /* This is the end of the last line, copy the last line to the
               start of the buffer and zero terminate, for old times sake */
            char *meow;
            int n;
            for(meow=pp->linestart_resp, n=0; meow<ptr; meow++, n++)
              buf[n] = *meow;
            *meow=0; /* zero terminate */
            keepon=FALSE;
            pp->linestart_resp = ptr+1; /* advance pointer */
            i++; /* skip this before getting out */

            *size = pp->nread_resp; /* size of the response */
            pp->nread_resp = 0; /* restart */
            break;
          }
          perline=0; /* line starts over here */
          pp->linestart_resp = ptr+1;
        }
      }

      if(!keepon && (i != gotbytes)) {
        /* We found the end of the response lines, but we didn't parse the
           full chunk of data we have read from the server. We therefore need
           to store the rest of the data to be checked on the next invoke as
           it may actually contain another end of response already! */
        clipamount = gotbytes - i;
        restart = TRUE;
        DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing "
                     "server response left\n",
                     (int)clipamount));
      }
      else if(keepon) {

        if((perline == gotbytes) && (gotbytes > BUFSIZE/2)) {
          /* We got an excessive line without newlines and we need to deal
             with it. We keep the first bytes of the line then we throw
             away the rest. */
          infof(data, "Excessive server response line length received, "
                "%zd bytes. Stripping\n", gotbytes);
          restart = TRUE;

          /* we keep 40 bytes since all our pingpong protocols are only
             interested in the first piece */
          clipamount = 40;
        }
        else if(pp->nread_resp > BUFSIZE/2) {
          /* We got a large chunk of data and there's potentially still
             trailing data to take care of, so we put any such part in the
             "cache", clear the buffer to make space and restart. */
          clipamount = perline;
          restart = TRUE;
        }
      }
      else if(i == gotbytes)
        restart = TRUE;

      if(clipamount) {
        pp->cache_size = clipamount;
        pp->cache = malloc(pp->cache_size);
        if(pp->cache)
          memcpy(pp->cache, pp->linestart_resp, pp->cache_size);
        else
          return CURLE_OUT_OF_MEMORY;
      }
      if(restart) {
        /* now reset a few variables to start over nicely from the start of
           the big buffer */
        pp->nread_resp = 0; /* start over from scratch in the buffer */
        ptr = pp->linestart_resp = buf;
        perline = 0;
      }

    } /* there was data */

  } /* while there's buffer left and loop is requested */

  pp->pending_resp = FALSE;

  return result;
}

int Curl_pp_getsock(struct pingpong *pp,
                    curl_socket_t *socks,
                    int numsocks)
{
  struct connectdata *conn = pp->conn;

  if(!numsocks)
    return GETSOCK_BLANK;

  socks[0] = conn->sock[FIRSTSOCKET];

  if(pp->sendleft) {
    /* write mode */
    return GETSOCK_WRITESOCK(0);
  }

  /* read mode */
  return GETSOCK_READSOCK(0);
}

CURLcode Curl_pp_flushsend(struct pingpong *pp)
{
  /* we have a piece of a command still left to send */
  struct connectdata *conn = pp->conn;
  ssize_t written;
  CURLcode result = CURLE_OK;
  curl_socket_t sock = conn->sock[FIRSTSOCKET];

  result = Curl_write(conn, sock, pp->sendthis + pp->sendsize -
                      pp->sendleft, pp->sendleft, &written);
  if(result)
    return result;

  if(written != (ssize_t)pp->sendleft) {
    /* only a fraction was sent */
    pp->sendleft -= written;
  }
  else {
    free(pp->sendthis);
    pp->sendthis=NULL;
    pp->sendleft = pp->sendsize = 0;
    pp->response = Curl_tvnow();
  }
  return CURLE_OK;
}

CURLcode Curl_pp_disconnect(struct pingpong *pp)
{
  if(pp->cache) {
    free(pp->cache);
    pp->cache = NULL;
  }
  return CURLE_OK;
}

bool Curl_pp_moredata(struct pingpong *pp)
{
  return (!pp->sendleft && pp->cache && pp->nread_resp < pp->cache_size) ?
         TRUE : FALSE;
}

#endif


text:
module EventQueueSpec (spec) where

import           Helper

import           EventQueue

withGitRepository :: IO a -> IO a
withGitRepository action = inTempDirectory (readProcess "git" ["init"] "" >> action)

spec :: Spec
spec = do
  describe "processEvents" $ do
    around_ withGitRepository $ do

      context "with FileEvent" $ do
        it "returns TriggerAction" $ do
          processEvents [FileEvent FileModified "test/FooSpec.hs"] `shouldReturn` TriggerAction ["test/FooSpec.hs"]

        context "with git ignored files" $ do
          it "returns NoneAction" $ do
            writeFile ".gitignore" "test/FooSpec.hs"
            processEvents [FileEvent FileModified "test/FooSpec.hs"] `shouldReturn` NoneAction

        context "when a Spec file is added" $ do
          it "returns ReloadAction" $ do
            processEvents [FileEvent FileAdded "test/FooSpec.hs"] `shouldReturn` ReloadAction "test/FooSpec.hs" FileAdded

          it "takes precedence over TriggerAll" $ do
            processEvents [TriggerAll, FileEvent FileAdded "test/FooSpec.hs", TriggerAll] `shouldReturn` ReloadAction "test/FooSpec.hs" FileAdded

          it "is overruled by Done" $ do
            processEvents [Done, FileEvent FileAdded "test/FooSpec.hs", Done] `shouldReturn` DoneAction

        context "when a Spec file is removed" $ do
          it "returns ReloadAction" $ do
            processEvents [FileEvent FileRemoved "test/FooSpec.hs"] `shouldReturn` ReloadAction "test/FooSpec.hs" FileRemoved

        context "when file is first removed and then added" $ do
          it "returns TriggerAction" $ do
            processEvents [FileEvent FileRemoved "test/FooSpec.hs", FileEvent FileAdded "test/FooSpec.hs"] `shouldReturn` TriggerAction ["test/FooSpec.hs"]

        context "when file is first added and then removed" $ do
          it "returns NoneAction" $ do
            processEvents [FileEvent FileAdded "test/FooSpec.hs", FileEvent FileRemoved "test/FooSpec.hs"] `shouldReturn` NoneAction

      context "with TriggerAll" $ do
        it "returns TriggerAllAction" $ do
          processEvents [TriggerAll] `shouldReturn` TriggerAllAction

        it "takes precedence over FileEvent" $ do
          processEvents [FileEvent FileModified "foo", TriggerAll, FileEvent FileModified "foo"] `shouldReturn` TriggerAllAction

      context "with Done" $ do
        it "returns DoneAction" $ do
          processEvents [Done] `shouldReturn` DoneAction

  describe "combineFileEvents" $ do
    it "combines removed/added to modified" $ do
      combineFileEvents [fileRemoved "foo", fileModified "bar", fileAdded "foo"] `shouldBe` [fileModified "foo", fileModified "bar"]

    it "does not combine events with different file names" $ do
      combineFileEvents [fileRemoved "foo", fileAdded "bar"] `shouldBe` [fileRemoved "foo", fileAdded "bar"]

  describe "groupFileEvents" $ do
    it "groups file event types by file name" $ do
      groupFileEvents [fileRemoved "foo", fileModified "bar", fileAdded "foo"] `shouldBe` [("foo", [FileRemoved, FileAdded]), ("bar", [FileModified])]

  where
    fileRemoved file = (file, FileRemoved)
    fileAdded file = (file, FileAdded)
    fileModified file = (file, FileModified)


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Reflections of a BLiu Mind</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link href="https://fonts.googleapis.com/css?family=Alegreya:700|Fira+Sans:400,400i,700,700i|Roboto+Slab:300,400" rel="stylesheet">
        <link rel="stylesheet" href="css/normalize.min.css">
        <link rel="stylesheet" href="css/main.css">

Reflections of a BLiu Mind

About

BLiu1.tk

Contact

Takeaway Journal and Career Plan

Now presenting, the takeaway journal, in which I droll along about what I learned in this course whilst simultaneously displaying mildly relevant images.

Quick Links

Home Page

Cool Fact!

Reading Reflections

Role-Model

TexTrade

Takeaway Journal

Website created with Initializr and ♥ by Brian Liu.


text:
package os

import (
	"sync"
	"syscall"
	"time"
)

// A fileStat is the implementation of FileInfo returned by Stat and Lstat.
type fileStat struct {
	name string
	sys  syscall.Win32FileAttributeData
	pipe bool

	// used to implement SameFile
	sync.Mutex
	path  string
	vol   uint32
	idxhi uint32
	idxlo uint32
}

func (fs *fileStat) Size() int64 {
	return int64(fs.sys.FileSizeHigh)<<32 + int64(fs.sys.FileSizeLow)
}

func (fs *fileStat) Mode() (m FileMode) {
	if fs == &devNullStat {
		return ModeDevice | ModeCharDevice | 0666
	}
	if fs.sys.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
		m |= ModeDir | 0111
	}
	if fs.sys.FileAttributes&syscall.FILE_ATTRIBUTE_READONLY != 0 {
		m |= 0444
	} else {
		m |= 0666
	}
	if fs.sys.FileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 {
		m |= ModeSymlink
	}
	if fs.pipe {
		m |= ModeNamedPipe
	}
	return m
}

func (fs *fileStat) ModTime() time.Time {
	return time.Unix(0, fs.sys.LastWriteTime.Nanoseconds())
}

// Sys returns syscall.Win32FileAttributeData for file fs.
func (fs *fileStat) Sys() interface{} { return &fs.sys }

func (fs *fileStat) loadFileId() error {
	fs.Lock()
	defer fs.Unlock()
	if fs.path == "" {
		// already done
		return nil
	}
	pathp, err := syscall.UTF16PtrFromString(fs.path)
	if err != nil {
		return err
	}
	h, err := syscall.CreateFile(pathp, 0, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
	if err != nil {
		return err
	}
	defer syscall.CloseHandle(h)
	var i syscall.ByHandleFileInformation
	err = syscall.GetFileInformationByHandle(syscall.Handle(h), &i)
	if err != nil {
		return err
	}
	fs.path = ""
	fs.vol = i.VolumeSerialNumber
	fs.idxhi = i.FileIndexHigh
	fs.idxlo = i.FileIndexLow
	return nil
}

// devNullStat is fileStat structure describing DevNull file ("NUL").
var devNullStat = fileStat{
	name: DevNull,
	// hopefully this will work for SameFile
	vol:   0,
	idxhi: 0,
	idxlo: 0,
}

func sameFile(fs1, fs2 *fileStat) bool {
	e := fs1.loadFileId()
	if e != nil {
		return false
	}
	e = fs2.loadFileId()
	if e != nil {
		return false
	}
	return fs1.vol == fs2.vol && fs1.idxhi == fs2.idxhi && fs1.idxlo == fs2.idxlo
}

// For testing.
func atime(fi FileInfo) time.Time {
	return time.Unix(0, fi.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds())
}


text:
import {Component, OnInit, OnDestroy, Input, Output, ViewChild} from '@angular/core';
import {NgForm} from '@angular/forms';
import {AuthService} from '../auth/auth.service';
import {TimelogService} from '../shared/services/timelog.service';
import {IUser} from '../../models/user';
import {Subscription} from 'rxjs/Subscription';

const styles: string = require('./entry.component.css').toString();

@Component({
    selector: 'tl-entry',
    templateUrl: 'entry.component.html',
    styles: [styles]
})

export class EntryComponent implements OnInit, OnDestroy {

    @Input()
    dt: string;  // format yyyy-mm-dd

    currentDate: string; // dt in fmt YYYYMMDD

    tasklist: string[];

    currentUser: IUser;

    loadSubscription: Subscription;
    copySubscription: Subscription;

    @ViewChild('f') manualForm: NgForm;

    @Output()
    hours: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
    @Output()
    mins: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
        19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
        36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
        52, 53, 54, 55, 56, 57, 58, 59];

    constructor(private authService: AuthService,
                private tlogService: TimelogService) {
    }

    ngOnInit(): void {
        this.dt = this.tlogService.getCurrentDt();
        this.currentDate = this.tlogService.getCurrentDate();
        this.currentUser = this.authService.getCurrentUser();
        this.tasklist = this.tlogService.getTasklist();
        this.loadSubscription = this.tlogService.daylogChanged.subscribe(() => {
            this.tasklist = this.tlogService.getTasklist();
        });
    }

    ngOnDestroy(): void {
        this.loadSubscription.unsubscribe();
        if (this.copySubscription) {
            this.copySubscription.unsubscribe();
        }
    }

    onCopyRecent(): void {
        // Subscription is required to make the query trigger
        this.copySubscription = this.tlogService.copyPreviousDays().subscribe((data) => {
            this.tasklist = this.tlogService.getTasklist();
        });
    }

    onDateChange(newDate: string): void {
        this.dt = newDate;
        this.currentDate = newDate.replace(/-/g, '');
        this.tlogService.setCurrentDate(this.currentDate); // sync with service that emits the event
    }

    onNewTask(): void {
        this.tlogService.addTask();
    }

    redrawAll(): void {
        this.tlogService.markUpdatedAll();
    }

    nextDay(): void {
        this.addDays(1);
    }

    previousDay(): void {
        this.addDays(-1);
    }

    addDays(increment: number): void {
        const newDate = this.tlogService.addDays(increment);
        const newDt = newDate.substring(0, 4) + '-' + newDate.substring(4, 6) + '-' + newDate.substring(6, 8);
        this.onDateChange(newDt);
    }

}


text:
'use strict';

function dashboardCtrl($scope/*, dashboardService*/) {
	console.log('something;');
	$scope.init = function () {
		$scope.CurrentPeriod = 'September';
		$scope.ExpensesValue = 100.556;
		$scope.IncomeValue = 600.45;
	}

	$scope.prevMonth = function() {
		console.log('Not implemented yet...');
	}

	$scope.nextMonth = function() {
		console.log('Not implemented yet...');
	}

	$scope.addTransaction = function(type) {
		console.log('addTransaction called......', type);
	}
}

angular
	.module('app.controllers')
	.controller('DashboardCtrl', ['$scope', /*'DashboardService',*/ dashboardCtrl]);


text:
Frequently asked questions
**************************

1. What is the difference between using Bibulous and using BibLatex+Biber?
==========================================================================

The biggest difference between these two is that Bibulous uses bibliography style template files that are intuitive and compact, whereas the Bibulous+Biber combination uses LaTeX code to generate styles, and these make them much more difficult to create and customize. A question posted on StackExchange [http://tex.stackexchange.com/questions/151628/bibtex-fields-for-doi-mr-zbl-and-arxiv/163628#163628] asked how one can build a reference list with hyperlinks to zbl, mr, doi, and eprint fields as defined in the database entries.

For Bibulous, we can create a template file, or modify an existing one, to have a ``link`` variable (you can call it almost anything you like), and add a definition for ``link`` in the ``SPECIAL-TEMPLATES`` section of the file::

    TEMPLATES:
    arxiv = <au>. <title>. <year>. arXiv: \href{http://arxiv.org/abs/<eprint>}{<eprint>}.
    article = <au>. <title>. <journal>, <volume>[(<number>)]:[<startpage>--<endpage>|<startpage>|<eid>|], <year>.[<link>]
    SPECIAL-TEMPLATES:
    link = [ doi: \href{http://dx.doi.org/<doi>}{<doi>}.][ MR: \href{http://www.ams.org/mathscinet-getitem?mr=MR<mr>}{<mr>}.][ Zbl: \href{http://zbmath.org/?q=an:<zbl>}{<zbl>}.]

The definition for ``link`` in the ``SPECIAL-TEMPLATES`` section creates a variable that can be used in the entrytype style templates. Thus, any template can use ``<link>`` to insert a hyperref to the quantities defined in the database. Adding the definition, and inserting ``<link>`` in each template where desired is all that needs to be done. The square brackets around ``<link>`` tell the template to ignore it if none of the four fields is defined inside the database entry.

For BibLatex+Biber, we can compare to Bibulous by using the answer provided on the same StackExchange page, given as follows. We add the following lines to the preamble of the main ``tex`` file::

    \DeclareDatamodelFields[type=field,datatype=verbatim]{arxiv,mr,zbl,jstor,hdl,pubmed,googlebooks,pmcid}
    \DeclareDatamodelEntryfields{arxiv,mr,zbl,jstor,hdl,pubmed,googlebooks,pmcid}
    \DeclareDatamodelFields[type=field,datatype=literal]{arxivclass}
    \DeclareDatamodelEntryfields{arxivclass}
    \DeclareSourcemap{
    \maps[datatype=bibtex]{
        \map{
        \step[fieldsource=pmid, fieldtarget=pubmed]
        }
    }
    }
    \makeatletter
    \DeclareFieldFormat{arxiv}{%
    arXiv\addcolon\space
    \ifhyperref
        {\href{http://arxiv.org/\abx@arxivpath/#1}{%
        \nolinkurl{#1}%
        \iffieldundef{arxivclass}
            {}
            {\addspace\texttt{\mkbibbrackets{\thefield{arxivclass}}}}}}
        {\nolinkurl{#1}
        \iffieldundef{arxivclass}
        {}
        {\addspace\texttt{\mkbibbrackets{\thefield{arxivclass}}}}}}
    \makeatother
    \DeclareFieldFormat{pmcid}{%
    PMCID\addcolon\space
    \ifhyperref
        {\href{http://www.ncbi.nlm.nih.gov/pmc/articles/#1}{\nolinkurl{#1}}}
        {\nolinkurl{#1}}}
    \DeclareFieldFormat{mr}{%
    MR\addcolon\space
    \ifhyperref
        {\href{http://www.ams.org/mathscinet-getitem?mr=MR#1}{\nolinkurl{#1}}}
        {\nolinkurl{#1}}}
    \DeclareFieldFormat{zbl}{%
    Zbl\addcolon\space
    \ifhyperref
        {\href{http://zbmath.org/?q=an:#1}{\nolinkurl{#1}}}
        {\nolinkurl{#1}}}
    \DeclareFieldAlias{jstor}{eprint:jstor}
    \DeclareFieldAlias{hdl}{eprint:hdl}
    \DeclareFieldAlias{pubmed}{eprint:pubmed}
    \DeclareFieldAlias{googlebooks}{eprint:googlebooks}
    \renewbibmacro*{eprint}{%
    \printfield{arxiv}%
    \newunit\newblock
    \printfield{jstor}%
    \newunit\newblock
    \printfield{mr}%
    \newunit\newblock
    \printfield{zbl}%
    \newunit\newblock
    \printfield{hdl}%
    \newunit\newblock
    \printfield{pubmed}%
    \newunit\newblock
    \printfield{pmcid}%
    \newunit\newblock
    \printfield{googlebooks}%
    \newunit\newblock
    \iffieldundef{eprinttype}
        {\printfield{eprint}}
        {\printfield[eprint:\strfield{eprinttype}]{eprint}}}

The template approach is clearly more compact, easier to read, and easier to customize.


text:
<img src="images/HTML5_Performance.png" width="256" height="256" class="invert"/>

# Performance

~~

## Worker

```js
var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();
```

~~

## Web Worker

```js
var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
    }
}

function stopWorker() {
    w.terminate();
    w = undefined;
}
```

http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webworker

~~

## Server Event Notification - Client Browser

```js
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("demo_sse.php");
    source.onmessage = function(event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
```

http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_sse

~~

## Server Event Notification - Server

```php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
```


text:
FROM ubuntu:18.10

# Dependencies to get the git sources and go binaries
RUN apt-get update && apt-get install -y  --no-install-recommends \
        ca-certificates \
        curl \
        git \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Get the git sources. If not cached, this takes O(5 minutes).
WORKDIR /git
RUN git config --global advice.detachedHead false
# Linux Kernel: Released 03 Mar 2019
RUN git clone --branch v5.0 --depth 1 https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux
# GNU C library: Released 01 Feb 2019 (we should try to get a secure way to clone this)
RUN git clone --branch release/2.29/master --depth 1 git://sourceware.org/git/glibc.git

# Get Go
ENV GOLANG_VERSION 1.12
ENV GOLANG_DOWNLOAD_URL https://golang.org/dl/go$GOLANG_VERSION.linux-amd64.tar.gz
ENV GOLANG_DOWNLOAD_SHA256 750a07fef8579ae4839458701f4df690e0b20b8bcce33b437e4df89c451b6f13

RUN curl -fsSL "$GOLANG_DOWNLOAD_URL" -o golang.tar.gz \
    && echo "$GOLANG_DOWNLOAD_SHA256  golang.tar.gz" | sha256sum -c - \
    && tar -C /usr/local -xzf golang.tar.gz \
    && rm golang.tar.gz

ENV PATH /usr/local/go/bin:$PATH

# Linux and Glibc build dependencies and emulator
RUN apt-get update && apt-get install -y  --no-install-recommends \
        bison gawk make python3 \
        gcc gcc-multilib \
        gettext texinfo \
        qemu-user \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*
# Cross compilers (install recommended packages to get cross libc-dev)
RUN apt-get update && apt-get install -y \
        gcc-aarch64-linux-gnu       gcc-arm-linux-gnueabi     \
        gcc-mips-linux-gnu          gcc-mips64-linux-gnuabi64 \
        gcc-mips64el-linux-gnuabi64 gcc-mipsel-linux-gnu      \
        gcc-powerpc64-linux-gnu     gcc-powerpc64le-linux-gnu \
	gcc-riscv64-linux-gnu                                 \
        gcc-s390x-linux-gnu         gcc-sparc64-linux-gnu     \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Let the scripts know they are in the docker environment
ENV GOLANG_SYS_BUILD docker
WORKDIR /build
ENTRYPOINT ["go", "run", "linux/mkall.go", "/git/linux", "/git/glibc"]