text:
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
//  NetCodeGroup.cs
//
// <OWNER>[....]</OWNER>
//
//  Representation for code groups used for the policy mechanism
//

namespace System.Security.Policy {

    using System;
    using System.Security.Util;
    using System.Security;
    using System.Collections;
    using System.Reflection;
    using System.Globalization;
    using System.Runtime.Serialization;
    using System.Runtime.Versioning;
    using System.Diagnostics.Contracts;

    //
    //This is a simple property bag used to describe connect back access.
    //
    [Serializable]
    [System.Runtime.InteropServices.ComVisible(true)]
    public class CodeConnectAccess {
        private string _LowerCaseScheme;
        private string _LowerCasePort;
        private int    _IntPort;

        private const  string  DefaultStr = "$default";     //must remain in lower case
        private const  string  OriginStr  = "$origin";  //must remain in lower case

        internal const  int     NoPort  = -1;
        internal const  int     AnyPort = -2; // This safely excludes -1 (if we decide to support "any" port later)

        //
        // public helper fields to deal with special scheme and port values.
        //
        public static readonly int     DefaultPort   = -3;
        public static readonly int     OriginPort    = -4;
        public static readonly string  OriginScheme  = OriginStr;
        public static readonly string  AnyScheme     = "*";

        //
        // A set of public static class factories
        //
        public CodeConnectAccess(string allowScheme, int allowPort)
        {
            if (!IsValidScheme(allowScheme))
                throw new ArgumentOutOfRangeException("allowScheme");

            SetCodeConnectAccess(allowScheme.ToLower(CultureInfo.InvariantCulture), allowPort);
        }
        //
        public static CodeConnectAccess CreateOriginSchemeAccess(int allowPort)
        {
            CodeConnectAccess access = new CodeConnectAccess();
            access.SetCodeConnectAccess(OriginScheme, allowPort);
            return access;
        }
        //
        public static CodeConnectAccess CreateAnySchemeAccess(int allowPort)
        {
            CodeConnectAccess access = new CodeConnectAccess();
            access.SetCodeConnectAccess(AnyScheme, allowPort);
            return access;
        }
        //
        private CodeConnectAccess()
        {
        }
        //
        private void SetCodeConnectAccess(string lowerCaseScheme, int allowPort)
        {
            _LowerCaseScheme = lowerCaseScheme;

            if (allowPort == DefaultPort)
                _LowerCasePort = DefaultStr;
            else if (allowPort == OriginPort)
                _LowerCasePort = OriginStr;
            else
            {
                if (allowPort < 0 || allowPort > 0xFFFF)
                    throw new ArgumentOutOfRangeException("allowPort");

                _LowerCasePort = allowPort.ToString(CultureInfo.InvariantCulture);
            }

            _IntPort = allowPort;
        }
        //
        public String   Scheme {
            get {return _LowerCaseScheme;}
        }
        //
        public int      Port {
            get {return _IntPort;}
        }
        //
        public override bool Equals(object o)
        {
            if ((object)this == (object)o)
                return true;

            CodeConnectAccess that = (o as CodeConnectAccess);

            if (that == null)
                return false;

            return this.Scheme == that.Scheme && this.Port == that.Port;
        }
        //
        public override int GetHashCode()
        {
            return Scheme.GetHashCode() + Port.GetHashCode();
        }
        //
        // internal stuff
        //
        //
        // The valid scheme values are: "*", "$origin", or a valid Uri scheme
        // The valid port valies are "$origin" "$default" or a valid Uri port
        //
        internal CodeConnectAccess(string allowScheme, string allowPort)
        {
            if (allowScheme == null || allowScheme.Length == 0)
                throw new ArgumentNullException("allowScheme");

            if (allowPort == null || allowPort.Length == 0)
                throw new ArgumentNullException("allowPort");
            Contract.EndContractBlock();

            _LowerCaseScheme = allowScheme.ToLower(CultureInfo.InvariantCulture);

            if (_LowerCaseScheme == OriginScheme)
                _LowerCaseScheme = OriginScheme;
            else if (_LowerCaseScheme == AnyScheme)
                _LowerCaseScheme = AnyScheme;
            else if (!IsValidScheme(_LowerCaseScheme))
                throw new ArgumentOutOfRangeException("allowScheme");

            _LowerCasePort = allowPort.ToLower(CultureInfo.InvariantCulture);

            if (_LowerCasePort == DefaultStr)
                _IntPort = DefaultPort;
            else if (_LowerCasePort == OriginStr)
                _IntPort = OriginPort;
            else
            {
                _IntPort = Int32.Parse(allowPort, CultureInfo.InvariantCulture);

                if (_IntPort < 0 || _IntPort > 0xFFFF)
                    throw new ArgumentOutOfRangeException("allowPort");

                _LowerCasePort = _IntPort.ToString(CultureInfo.InvariantCulture);
            }
        }
        //
        internal bool     IsOriginScheme {
            get {return (object)_LowerCaseScheme == (object)OriginScheme;}
        }
        //
        internal bool     IsAnyScheme {
            get {return (object)_LowerCaseScheme == (object)AnyScheme;}
        }
        //
        internal bool     IsDefaultPort {
            get {return Port == DefaultPort;}
        }
        //
        internal bool     IsOriginPort {
            get {return Port == OriginPort;}
        }
        //
        // More Internal stuff
        //
        internal string  StrPort {
            get { return _LowerCasePort;}
        }
        //
        [Pure]
        internal static bool IsValidScheme(string scheme)
        {
            if (((object)scheme == null) || (scheme.Length == 0) || !IsAsciiLetter(scheme[0]))
                return false;

            for (int i = scheme.Length - 1; i > 0; --i) {
                if (!(IsAsciiLetterOrDigit(scheme[i]) || (scheme[i] == '+') || (scheme[i] == '-') || (scheme[i] == '.')))
                    return false;
            }
            return true;
        }
        //
        [Pure]
        private static bool IsAsciiLetterOrDigit(char character) {
            return IsAsciiLetter(character) || (character >= '0' && character <= '9');
        }
        //
        [Pure]
        private static bool IsAsciiLetter(char character) {
            return (character >= 'a' && character <= 'z') ||
                   (character >= 'A' && character <= 'Z');
        }
    }

    [Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
    sealed public class NetCodeGroup : CodeGroup, IUnionSemanticCodeGroup
    {
        [System.Security.SecurityCritical]  // auto-generated
        [System.Diagnostics.Conditional( "_DEBUG" )]
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
        private static void DEBUG_OUT( String str )
        {
#if _DEBUG
            if (debug)
            {
                if (to_file)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append( str );
                    sb.Append ((char)13) ;
                    sb.Append ((char)10) ;
                    PolicyManager.DebugOut( file, sb.ToString() );
                }
                else
                    Console.WriteLine( str );
             }
#endif
        }

#if _DEBUG
        private static bool debug;
        private static readonly bool to_file;
        private const String file = "c:\\com99\\src\\bcl\\debug.txt";
#endif

        [OptionalField(VersionAdded = 2)]
        private ArrayList           m_schemesList;
        [OptionalField(VersionAdded = 2)]
        private ArrayList           m_accessList;

        [OnDeserializing]
        private void OnDeserializing(StreamingContext ctx)
        {
            m_schemesList = null;
            m_accessList = null;

        }

        private const string c_IgnoreUserInfo = ""; // don't need anymore since WebPermission will ignore userinfo anyway. was: @"([^\\/?#]*@)?";
        // not exactly correct syntax but should work fine assuming System.Uri will not accept bogus Uri schemes
        private const string c_AnyScheme = @"([0-9a-z+\-\.]+)://";

        private static readonly char[] c_SomeRegexChars = new char[] {'.', '-', '+', '[', ']', /* rest are unc-only*/ '{', '$', '^', '#', ')', '(', ' '};

        public static readonly string  AnyOtherOriginScheme= CodeConnectAccess.AnyScheme;
        public static readonly string  AbsentOriginScheme  = string.Empty;

        internal NetCodeGroup()
            : base()
        {
            SetDefaults();
        }

        public NetCodeGroup( IMembershipCondition membershipCondition )
            : base( membershipCondition, (PolicyStatement)null )
        {
            SetDefaults();
        }

        //
        // Reset the talkback access to nothing.
        // When a new instance of NetCodeGroup is created it's populated with default talkback rules
        //
        public void ResetConnectAccess()
        {
            m_schemesList = null;
            m_accessList = null;
        }
        //
        // Added public stuff for programmatic support of the talkback access
        // The connectAccess can be null means an empty access (no access) is added
        //
        public void AddConnectAccess(string originScheme, CodeConnectAccess connectAccess)
        {
            if (originScheme == null)
                throw new ArgumentNullException("originScheme");
            Contract.EndContractBlock();

            if (originScheme != AbsentOriginScheme && originScheme != AnyOtherOriginScheme && !CodeConnectAccess.IsValidScheme(originScheme))
                throw new ArgumentOutOfRangeException("originScheme");

            if (originScheme == AbsentOriginScheme && connectAccess.IsOriginScheme)
                throw new ArgumentOutOfRangeException("connectAccess");

            if (m_schemesList == null)
            {
                m_schemesList = new ArrayList();
                m_accessList = new ArrayList();
            }

            originScheme = originScheme.ToLower(CultureInfo.InvariantCulture);

            for (int i=0; i < m_schemesList.Count; ++i)
            {
                if ((string)m_schemesList[i] == originScheme)
                {
                    // originScheme entry is found and we may want to add nothing to it.
                    if (connectAccess == null)
                        return;

                    ArrayList list = (ArrayList)m_accessList[i];
                    for (i = 0; i < list.Count; ++i)
                    {
                        if (((CodeConnectAccess)list[i]).Equals(connectAccess))
                            return;
                    }
                    list.Add(connectAccess);
                    return;
                }
            }

            // originScheme entry is not found, create a new one.
            m_schemesList.Add(originScheme);
            ArrayList newOriginSchemeList = new ArrayList();
            m_accessList.Add(newOriginSchemeList);

            // we may want to keep it empty.
            if (connectAccess != null)
                newOriginSchemeList.Add(connectAccess);

        }
        //
        // Each DictionaryEntry will contain
        // Key=originScheme and Value=CodeConnectAccess[] array
        //
        public DictionaryEntry[] GetConnectAccessRules()
        {
            if (m_schemesList == null)
                return null;

            DictionaryEntry[] result = new DictionaryEntry[m_schemesList.Count];
            for (int i = 0; i < result.Length; ++i)
            {
                result[i].Key = m_schemesList[i];
                result[i].Value = ((ArrayList)m_accessList[i]).ToArray(typeof(CodeConnectAccess));
            }
            return result;
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public override PolicyStatement Resolve( Evidence evidence )
        {
            if (evidence == null)
                throw new ArgumentNullException("evidence");
            Contract.EndContractBlock();

            object usedEvidence = null;
            if (PolicyManager.CheckMembershipCondition(MembershipCondition,
                                                       evidence,
                                                       out usedEvidence))
            {
                PolicyStatement thisPolicy = CalculateAssemblyPolicy( evidence );

                // If any delay-evidence was used to generate this grant set, then we need to keep track of
                // that for potentially later forcing it to be verified.
                IDelayEvaluatedEvidence delayEvidence = usedEvidence as IDelayEvaluatedEvidence;
                bool delayEvidenceNeedsVerification = delayEvidence != null && !delayEvidence.IsVerified;
                if (delayEvidenceNeedsVerification)
                {
                    thisPolicy.AddDependentEvidence(delayEvidence);
                }

                bool foundExclusiveChild = false;
                IEnumerator enumerator = this.Children.GetEnumerator();
                while (enumerator.MoveNext() && !foundExclusiveChild)
                {
                    PolicyStatement childPolicy = PolicyManager.ResolveCodeGroup(enumerator.Current as CodeGroup,
                                                                                evidence);
                    if (childPolicy != null)
                    {
                        thisPolicy.InplaceUnion(childPolicy);

                        if ((childPolicy.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive)
                        {
                            foundExclusiveChild = true;
                        }
                    }
                }

                return thisPolicy;
            }
            else
            {
                return null;
            }
        }

        /// <internalonly/>
        PolicyStatement IUnionSemanticCodeGroup.InternalResolve( Evidence evidence )
        {
            if (evidence == null)
                throw new ArgumentNullException("evidence");

            Contract.EndContractBlock();

            if (this.MembershipCondition.Check( evidence ))
            {
                return CalculateAssemblyPolicy( evidence );
            }

            return null;
        }

        public override CodeGroup ResolveMatchingCodeGroups( Evidence evidence )
        {
            if (evidence == null)
                throw new ArgumentNullException("evidence");
            Contract.EndContractBlock();

            if (this.MembershipCondition.Check( evidence ))
            {
                CodeGroup retGroup = this.Copy();

                retGroup.Children = new ArrayList();

                IEnumerator enumerator = this.Children.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    CodeGroup matchingGroups = ((CodeGroup)enumerator.Current).ResolveMatchingCodeGroups( evidence );

                    // If the child has a policy, we are done.

                    if (matchingGroups != null)
                    {
                        retGroup.AddChild( matchingGroups );
                    }
                }

                return retGroup;

            }
            else
            {
                return null;
            }
        }
        //
        private string EscapeStringForRegex( string str )
        {
            int start = 0;
            int idx;
            System.Text.StringBuilder sb = null;

            while (start < str.Length && (idx = str.IndexOfAny(c_SomeRegexChars, start)) != -1)
            {
                if (sb == null) sb = new System.Text.StringBuilder(str.Length*2);
                sb.Append(str, start, idx - start).Append('\\').Append(str[idx]);
                start = idx+1;
            }
            if (sb == null)
                return str;

            if (start < str.Length)
                sb.Append(str, start, str.Length - start);

            return sb.ToString();
        }

        internal SecurityElement CreateWebPermission(string host,
                                                     string scheme,
                                                     string port,
                                                     string assemblyOverride)
        {
            if (scheme == null)
                scheme = string.Empty;

            // If there is no OriginScheme host string, no talk back access is possible
            if (host == null || host.Length == 0)
                return null;

            host = host.ToLower(CultureInfo.InvariantCulture);
            scheme = scheme.ToLower(CultureInfo.InvariantCulture);

            int intPort = CodeConnectAccess.NoPort;
            if (port != null && port.Length != 0)
                intPort = Int32.Parse(port, CultureInfo.InvariantCulture );
            else
                port = string.Empty;

            CodeConnectAccess[] access = FindAccessRulesForScheme(scheme);
            if (access == null || access.Length == 0)
                return null;

            SecurityElement root = new SecurityElement( "IPermission" );

            // If we were given a specific assembly to find the WebPermission type in use that, otherwise use
            // the current version of System.dll.  This enables us to build WebPermissions targeting older
            // runtimes for ClickOnce trust decisions that need to target the older runtime.
            string permissionAssembly = assemblyOverride == null ?
                "System, Version=" + ThisAssembly.Version + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken :
                assemblyOverride;

            root.AddAttribute( "class", "System.Net.WebPermission, " + permissionAssembly);
            root.AddAttribute( "version", "1" );

            SecurityElement connectAccess = new SecurityElement( "ConnectAccess" );

            host = EscapeStringForRegex(host);
            scheme = EscapeStringForRegex(scheme);
            string uriStr = TryPermissionAsOneString(access, scheme, host, intPort);

            if (uriStr != null)
            {
                SecurityElement uri = new SecurityElement( "URI" );
                uri.AddAttribute( "uri", uriStr );
                connectAccess.AddChild( uri );
            }
            else
            {
                if (port.Length != 0)
                    port = ":" + port;

                for (int i = 0; i < access.Length; ++i)
                {
                    uriStr = GetPermissionAccessElementString(access[i], scheme, host, port);
                    SecurityElement uri = new SecurityElement( "URI" );
                    uri.AddAttribute( "uri", uriStr );
                    connectAccess.AddChild( uri );
                }
            }

            root.AddChild( connectAccess );
            return root;
        }
        //
        //
        //
        private CodeConnectAccess[] FindAccessRulesForScheme(string lowerCaseScheme)
        {
            if (m_schemesList == null)
                return null;

            int i = m_schemesList.IndexOf(lowerCaseScheme);
            if (i == -1)
            {
                // Trying default rule but only if the passed string is not about "no scheme case"
                if (lowerCaseScheme == AbsentOriginScheme || (i = m_schemesList.IndexOf(AnyOtherOriginScheme)) == -1)
                    return null;
            }

            ArrayList accessList = (ArrayList)m_accessList[i];
            return (CodeConnectAccess[])accessList.ToArray(typeof(CodeConnectAccess));
        }
        //
        // This is an attempt to optimize resulting regex if the rules can be combined into one expression string
        //
        private string TryPermissionAsOneString(CodeConnectAccess[] access, string escapedScheme, string escapedHost, int intPort)
        {
            bool noPort = true;
            bool originPort = true;
            bool anyScheme = false;
            int  sameCustomPort = CodeConnectAccess.AnyPort;

            //
            // We can compact rules in one regex if the destination port is the same for all granted accesses.
            // We may have three cases (order is significant)
            // - No port (empty) in the resulting rule
            // - Origin server port that is intPort parameter
            // - Some custom port that is the same for all accesses
            //
            for (int i = 0; i < access.Length; ++i)
            {
                noPort    &= (access[i].IsDefaultPort || (access[i].IsOriginPort && intPort == CodeConnectAccess.NoPort));
                originPort&= (access[i].IsOriginPort  || access[i].Port == intPort);

                if (access[i].Port >= 0)
                {

                    if (sameCustomPort == CodeConnectAccess.AnyPort)
                    {
                        sameCustomPort = access[i].Port;
                    }
                    else if (access[i].Port != sameCustomPort)
                    {
                        // found conflicting ports
                        sameCustomPort = CodeConnectAccess.NoPort;
                    }
                }
                else
                {
                    // Cannot compress Regex if saw at least one "default port" access rule and another one with exact port.
                    sameCustomPort = CodeConnectAccess.NoPort;
                }

                if (access[i].IsAnyScheme)
                    anyScheme = true;
            }

            if (!noPort && !originPort && sameCustomPort == CodeConnectAccess.NoPort)
                return null;

            // We can produce the resulting expression as one string
            System.Text.StringBuilder sb = new System.Text.StringBuilder(c_AnyScheme.Length * access.Length + c_IgnoreUserInfo.Length*2 + escapedHost.Length);
            if (anyScheme)
                sb.Append(c_AnyScheme);
            else
            {
                sb.Append('(');
                int i = 0;
                for (; i < access.Length; ++i)
                {
                    // This is  to avoid output like (http|http|http)
                    int k = 0;
                    for (; k < i; ++k)
                    {
                        if (access[i].Scheme == access[k].Scheme)
                            break;
                    }
                    if (k == i)
                    {
                        if (i != 0)
                            sb.Append('|');
                        sb.Append(access[i].IsOriginScheme? escapedScheme: EscapeStringForRegex(access[i].Scheme));
                    }
                }
                sb.Append(")://");;
            }

            sb.Append(c_IgnoreUserInfo).Append(escapedHost);

            if (noPort) {;}
            else if (originPort) sb.Append(':').Append(intPort);
            else sb.Append(':').Append(sameCustomPort);

            sb.Append("/.*");
            return sb.ToString();
        }
        //
        // This tries to return a single element to be added into resulting WebPermission
        // Returns Null if there is nothing to add.
        //
        private string GetPermissionAccessElementString(CodeConnectAccess access, string escapedScheme, string escapedHost, string strPort)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(c_AnyScheme.Length*2 + c_IgnoreUserInfo.Length + escapedHost.Length);

            if (access.IsAnyScheme)
                sb.Append(c_AnyScheme);
            else if (access.IsOriginScheme)
                sb.Append(escapedScheme).Append("://");
            else
                sb.Append(EscapeStringForRegex(access.Scheme)).Append("://");

            sb.Append(c_IgnoreUserInfo).Append(escapedHost);

            if (access.IsDefaultPort) {;}
            else if (access.IsOriginPort)
                 sb.Append(strPort);
            else sb.Append(':').Append(access.StrPort);

            sb.Append("/.*");
            return sb.ToString();
        }

        internal PolicyStatement CalculatePolicy( String host, String scheme, String port )
        {
            SecurityElement webPerm = CreateWebPermission( host, scheme, port, null );

            SecurityElement root = new SecurityElement( "PolicyStatement" );
            SecurityElement permSet = new SecurityElement( "PermissionSet" );
            permSet.AddAttribute( "class", "System.Security.PermissionSet" );
            permSet.AddAttribute( "version", "1" );

            if (webPerm != null)
                permSet.AddChild( webPerm );

            root.AddChild( permSet );

            PolicyStatement policy = new PolicyStatement();
            policy.FromXml( root );
            return policy;
        }

        private PolicyStatement CalculateAssemblyPolicy( Evidence evidence )
        {

            PolicyStatement thisPolicy = null;

            Url url = evidence.GetHostEvidence<Url>();
            if (url != null)
            {
                thisPolicy = CalculatePolicy( url.GetURLString().Host, url.GetURLString().Scheme, url.GetURLString().Port );
            }

            if (thisPolicy == null)
            {
                Site site = evidence.GetHostEvidence<Site>();
                if (site != null)
                {
                    thisPolicy = CalculatePolicy(site.Name, null, null);
                }
            }

            if (thisPolicy == null)
                thisPolicy = new PolicyStatement( new PermissionSet( false ), PolicyStatementAttribute.Nothing );

            return thisPolicy;
        }

        public override CodeGroup Copy()
        {
            NetCodeGroup group = new NetCodeGroup( this.MembershipCondition );

            group.Name = this.Name;
            group.Description = this.Description;
            if (m_schemesList != null)
            {
                group.m_schemesList = (ArrayList)this.m_schemesList.Clone();
                group.m_accessList = new ArrayList(this.m_accessList.Count);
                for (int i = 0; i < this.m_accessList.Count; ++i)
                    group.m_accessList.Add(((ArrayList)this.m_accessList[i]).Clone());
            }

            IEnumerator enumerator = this.Children.GetEnumerator();

            while (enumerator.MoveNext())
            {
                group.AddChild( (CodeGroup)enumerator.Current );
            }

            return group;
        }

        public override String MergeLogic
        {
            get
            {
                return Environment.GetResourceString( "MergeLogic_Union" );
            }
        }

        public override String PermissionSetName
        {
            get
            {
                return Environment.GetResourceString( "NetCodeGroup_PermissionSet" );
            }
        }

        public override String AttributeString
        {
            get
            {
                return null;
            }
        }
        //
        public override bool Equals( Object o)
        {
            if ((object)this == (object)o)
                return true;

            NetCodeGroup that = (o as NetCodeGroup);

            if (that == null || !base.Equals(that))
                return false;

            if ((this.m_schemesList == null) != (that.m_schemesList == null))
                return false;

            if (this.m_schemesList == null)
                return true;

            if (this.m_schemesList.Count != that.m_schemesList.Count)
                return false;

            for (int i = 0; i < this.m_schemesList.Count; ++i)
            {
                int idx = that.m_schemesList.IndexOf(this.m_schemesList[i]);
                if (idx == -1)
                    return false;

                ArrayList thisList = (ArrayList)this.m_accessList[i];
                ArrayList thatList = (ArrayList)that.m_accessList[idx];
                if (thisList.Count != thatList.Count)
                    return false;

                for (int k = 0; k < thisList.Count; ++k)
                {
                    if (!thatList.Contains(thisList[k]))
                        return false;
                }
            }

            return true;
        }
        //
        //
        public override int GetHashCode()
        {
            return base.GetHashCode() + GetRulesHashCode();
        }
        private int GetRulesHashCode()
        {
            if (m_schemesList == null)
                return 0;

            int result = 0;
            for(int i = 0; i < m_schemesList.Count; ++i)
                result += ((string)m_schemesList[i]).GetHashCode();

            foreach (ArrayList accessList in m_accessList)
                for(int i = 0; i < accessList.Count; ++i)
                    result += ((CodeConnectAccess)accessList[i]).GetHashCode();

            return result;
        }
        //
        protected override void CreateXml( SecurityElement element, PolicyLevel level )
        {
            DictionaryEntry[] rules = GetConnectAccessRules();
            if (rules == null)
                return;

            SecurityElement rulesElement = new SecurityElement("connectAccessRules");

            foreach (DictionaryEntry rule in rules)
            {
                SecurityElement codeOriginElement = new SecurityElement("codeOrigin");
                codeOriginElement.AddAttribute("scheme", (string) rule.Key);
                foreach (CodeConnectAccess access in (CodeConnectAccess[])rule.Value)
                {
                    SecurityElement accessElem = new SecurityElement("connectAccess");
                    accessElem.AddAttribute("scheme", access.Scheme);
                    accessElem.AddAttribute("port", access.StrPort);
                    codeOriginElement.AddChild(accessElem);
                }
                rulesElement.AddChild(codeOriginElement);
            }
            element.AddChild(rulesElement);
        }

        protected override void ParseXml( SecurityElement e, PolicyLevel level )
        {
            //Reset the exiting content
            ResetConnectAccess();

            SecurityElement et = e.SearchForChildByTag("connectAccessRules");

            if (et == null || et.Children == null)
            {
                // Everett behavior, same as calling a default ctor.
                SetDefaults();
                return;
            }

            foreach(SecurityElement codeOriginElem in et.Children)
            {
                if (codeOriginElem.Tag.Equals("codeOrigin"))
                {
                    string originScheme = codeOriginElem.Attribute("scheme");
                    bool oneAdded = false;

                    if (codeOriginElem.Children != null)
                    {
                        foreach(SecurityElement accessElem in codeOriginElem.Children)
                        {
                            if (accessElem.Tag.Equals("connectAccess"))
                            {
                                string connectScheme = accessElem.Attribute("scheme");
                                string connectPort   = accessElem.Attribute("port");
                                AddConnectAccess(originScheme, new CodeConnectAccess(connectScheme, connectPort));
                                oneAdded = true;
                            }
                            else {
                                // improper tag found, just ignore
                            }
                        }
                    }

                    if (!oneAdded)
                    {
                        //special case as to no talkback access for a given scheme
                        AddConnectAccess(originScheme, null);
                    }

                }
                else {
                    // improper tag found, just ignore
                }
            }
        }

        internal override String GetTypeName()
        {
            return "System.Security.Policy.NetCodeGroup";
        }
        //
        // This method is called at the ctor time to populate default accesses (V1.1 compat)
        //
        private void SetDefaults()
        {
            // No access for file://
            AddConnectAccess("file", null);

            // access fot http://
            AddConnectAccess("http", new CodeConnectAccess("http", CodeConnectAccess.OriginPort));
            AddConnectAccess("http", new CodeConnectAccess("https", CodeConnectAccess.OriginPort));
            /*

*/

            // access fot https://
            AddConnectAccess("https", new CodeConnectAccess("https", CodeConnectAccess.OriginPort));
            /*

*/

            // access fot ftp://
            /*

*/

            // access for no scheme and for any other scheme
            AddConnectAccess(NetCodeGroup.AbsentOriginScheme, CodeConnectAccess.CreateAnySchemeAccess(CodeConnectAccess.OriginPort));
            AddConnectAccess(NetCodeGroup.AnyOtherOriginScheme, CodeConnectAccess.CreateOriginSchemeAccess(CodeConnectAccess.OriginPort));
        }

    }

}


text:
Library frontend is represented with **[PaynetEasy\PaynetEasyApi\PaymentProcessor](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php)** class. Class provides the following methods:
* **[executeQuery()](#executeQuery)**: execute PaynetEasy request
* **[processCustomerReturn()](#processCustomerReturn)**: process data received from PaynetEasy when user was returned from the payment gateway
* **[processPaynetEasyCallback()](#processPaynetEasyCallback)**: process data received from PaynetEasy in a callback
* **[setHandlers()](#setHandlers)**: set handlers for various events which occur while processing the payment transaction

### executeQuery(): execute PaynetEasy request

Some payment processing scenarios have asynchronous nature and consist of several requests. For instance, certain requests do not return payment result right away and require to poll **status**, after which client may be redirected to PaynetEasy gateway to perform additional authorization steps. After client has returned to merchant service, processing of data received from the gateway is necessary.
Asynchronous requests list:
* sale
* preauth
* capture
* return
* make-rebill
* transfer-by-ref

Following files contain examples of processing of such requests:
* [Example of sale request execution](../../../example/sale.php)
* [Example of preauth request execution](../../../example/preauth.php)
* [Example of capture request execution](../../../example/capture.php)
* [Example of return request execution](../../../example/return.php)
* [Example of make-rebill request execution](../../../example/make-rebill.php)
* [Example of transfer-by-ref request execution](../../../example/transfer-by-ref.php)

A processing scenario is required for payment form integration as well. Response from a gateway returns a URL pointing to payment form to which the client must be redirected. After filling and submission of data gateway processes the payment form and returns the client to merchant service. After the client has been returned to merchant service, processing of data received from the gateway is required.
List of requests for payment form integration:
* sale-form
* preauth-form
* transfer-form

Following files contain examples of processing of such requests:
* [Example of sale-form request execution](../../../example/sale-form.php)
* [Example of preauth-form request execution](../../../example/preauth-form.php)
* [Example of transfer-form request execution](../../../example/transfer-form.php)

Some payment operations do not require complex processing scenarios and are performed in one request.
List of simple payment operations:
* create-card-ref
* get-card-info
* status

Following files contain examples of processing of such requests:
* [Example of create-card-ref request execution](../../../example/create-card-ref.php)
* [Example of get-card-info request execution](../../../example/get-card-info.php)
* [Example of status request execution](../../../example/status.php)

For convenient PaynetEasy request execution, **[executeQuery()](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php#L114)** method is implemented in **PaymentProcessor**.
Method accepts two parameters:
* Request name
* Payment transaction for processing

### processCustomerReturn(): processing of the data received from PaynetEasy when returning the client

Every [asynchronous request](#async_queries_list) may finish with customer redirect to the payment gateway to fulfill additional actions, and every [payment form integration request](#form_queries_list) necessarily contains such a redirection. Every time, when a customer is returned, processing result data is transmitted to merchant service. Also, if [initial request configuration](../00-basic-tutorial.md#stage_1_step_3) has **server_callback_url** key defined, then after payment processing has been finished, PaynetEasy will call that URL and send to it data described in PaynetEasy documentation in [Merchant Callbacks](http://doc.payneteasy.com/doc/merchant-callbacks.htm) section. For convenient processing of that data, **PaymentProcessor** has **[processCustomerReturn()](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php#L144)** method.
Method accepts two parameters:
* Object with data received when customer has returned from PaynetEasy via redirect
* Payment transaction for processing

Following files contain examples of processing of such requests:
* [Basic library usage example](../00-basic-tutorial.md#stage_2)
* [Example of sale request execution](../../../example/sale.php#L96)
* [Example of preauth request execution](../../../example/preauth.php#L96)
* [Example of sale-form request execution](../../../example/sale-form.php#L75)
* [Example of preauth-form request execution](../../../example/preauth-form.php#L75)
* [Example of transfer-form request execution](../../../example/transfer-form.php#L75)

### processPaynetEasyCallback(): processing PaynetEasy callback

After an [asynchronous request](#async_queries_list) or [payment form integration request](#form_queries_list) has been executed, if an [initial request configuration](../00-basic-tutorial.md#stage_1_step_3) contains **server_callback_url** key defined, then after some time PaynetEasy will call that URL and send to it data described in PaynetEasy documentation in section [Merchant Callbacks](http://doc.payneteasy.com/doc/merchant-callbacks.htm). For convenient processing of that data **PaymentProcessor** has **[processPaynetEasyCallback()](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php#L159)** method.
Method accepts two parameters:
* Object with data received when customer was redirected from PaynetEasy
* Payment transaction for processing

Following files contain examples of processing of such requests:
* [Example of sale request execution](../../../example/sale.php#L107)
* [Example of preauth request execution](../../../example/preauth.php#L107)
* [Example of sale-form request execution](../../../example/sale-form.php#L86)
* [Example of preauth-form request execution](../../../example/preauth-form.php#L86)
* [Example of transfer-form request execution](../../../example/transfer-form.php#L86)

###  setHandlers(): setting handlers for various events occurring during order processing

**PaymentProcessor** hides the order processing algorithm from the end user in **[executeQuery()](#executeQuery)**, **[processCustomerReturn()](#processCustomerReturn)** and **[processPaynetEasyCallback()](#processPaynetEasyCallback)** methods. During order processing situations arise, which must be handled at merchant service side. To handle such situations, **PaymentProcessor** has event handling system. Handlers may be installed using three ways:
* Pass handlers array to [**PaymentProcessor** class constructor](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php#L101)
* Pass handlers array to [**setHandlers()**](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php#L250) method
* Install handlers one by one using **[setHandler()](../../../source/PaynetEasy/PaynetEasyApi/PaymentProcessor.php#L226)** method

Event handlers list:
* **HANDLER_SAVE_CHANGES** - handler to save payment transaction. It is called when payment transaction data is changed. It must save the payment transaction to a storage. Accepts the following parameters:
    * Payment transaction
    * PaynetEasy response (optional; not available, if an error at early stage of request execution has occurred)
* **HANDLER_STATUS_UPDATE** - handler to update payment transaction status. It is called, if payment transaction status did not changed since the last check. It must initiate payment transaction status check. Accepts the following parameters:
    * PaynetEasy response
    * Payment transaction
* **HANDLER_SHOW_HTML** - handler to output HTML code received from PaynetEasy. Called when user 3D Authorization is required. Must output HTML code from PaynetEasy response to client's browser. Accepts the following parameters:
    * PaynetEasy response
    * Payment transaction
* **HANDLER_REDIRECT** - handler to redirect a client to PaynetEasy payment form. Called after executing [sale-form, preauth-form or transfer-form](../payment-scenarios/05-payment-form-integration.md). Must redirect a user to URL from PaynetEasy response. Accepts the following parameters:
    * PaynetEasy response
    * Payment transaction
* **HANDLER_FINISH_PROCESSING** - handler to proceed payment transaction processing after it has been processed by the library. Called if there is no need of further transaction processing. Accepts the following parameters:
    * Payment transaction
    * PaynetEasy response (optional; not available, if payment transaction processing has already been finished earlier)
* **HANDLER_CATCH_EXCEPTION** - exception handler. Called if an exception occurres while processing. **Warning!** If this handler is not installed, then the exception will be thrown from the library to merchant service code. Accepts the following parameters:
    * Exception
    * Payment transaction
    * PaynetEasy response (optional; not available, if an error at early stage of request execution has occurred)

Method accepts one parameter:
* Event handlers array. Handler names (defined in class constants) are array keys. Values are any values of [callable](http://php.net/manual/en/language.types.callable.php) type

An example of method invocation with simple handlers:

```php
use PaynetEasy\PaynetEasyApi\PaymentProcessor;
use PaynetEasy\PaynetEasyApi\PaymentData\PaymentTransaction;
use PaynetEasy\PaynetEasyApi\Transport\Response;
use Exception;

$paymentProcessor = new PaymentProcessor;
$paymentProcessor->setHandlers(array
(
    PaymentProcessor::HANDLER_SAVE_CHANGES      => function(PaymentTransaction $paymentTransaction)
    {
        session_start();
        $_SESSION['payment_transaction'] = serialize($paymentTransaction);
    },
    PaymentProcessor::HANDLER_STATUS_UPDATE     => function()
    {
        header("Location: http://{$_SERVER['HTTP_HOST']}{$_SERVER['SCRIPT_NAME']}?stage=updateStatus");
        exit;
    },
    PaymentProcessor::HANDLER_SHOW_HTML         => function(Response $response)
    {
        print $response->getHtml();
        exit;
    },
    PaymentProcessor::HANDLER_REDIRECT          => function(Response $response)
    {
        header("Location: {$response->getRedirectUrl()}");
        exit;
    },
    PaymentProcessor::HANDLER_FINISH_PROCESSING => function(PaymentTransaction $paymentTransaction)
    {
        print "<pre>";
        print "Payment processing finished.\n";
        print "Payment status: '{$paymentTransaction->getPayment()->getStatus()}'.\n";
        print "Payment transaction status: '{$paymentTransaction->getStatus()}'.\n";
        print "</pre>";
    },
    PaymentProcessor::HANDLER_CATCH_EXCEPTION   => function(Exception $exception)
    {
        print "<pre>";
        print "Exception catched.\n";
        print "Exception message: '{$exception->getMessage()}'.\n";
        print "Exception traceback: \n{$exception->getTraceAsString()}\n";
        print "</pre>";
    }
));
```

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
                      "../../../docbook/docbook-dtd/docbookx.dtd"
[
<!ENTITY introduction SYSTEM "introduction.xml">
<!ENTITY architecture SYSTEM "architecture.xml">
<!ENTITY working SYSTEM "working.xml">
<!ENTITY dotnet SYSTEM "dotnet.xml">
<!ENTITY xsdConfig SYSTEM "xsd-config.xml">
<!ENTITY xsdSqlMap SYSTEM "xsd-sqlMap.xml">

]>
<book>
<bookinfo>
    <title>iBATIS.NET - DataMapper Application Framework</title>
    <subtitle>DataMapper Developer Guide</subtitle>
    <releaseinfo>Version 1.3.0</releaseinfo>
    <pubdate>3 October 2005</pubdate>
    <authorgroup>
      <author>
        <firstname>Ted</firstname>
        <surname>Husted</surname>
      </author>
      <author>
        <firstname>Gilles</firstname>
        <surname>Bayon</surname>
      </author>
      <author>
        <firstname>Clinton</firstname>
        <surname>Begin</surname>
      </author>
      <author>
        <firstname>Roberto</firstname>
        <surname>Rabe</surname>
      </author>
    </authorgroup>
    <legalnotice>
      <para>
        Copies of this document may be made for your own use and for
        distribution to others, provided that you do not charge any fee for such
        copies and further provided that each copy contains this Copyright
        Notice, whether distributed in print or electronically.
        </para>
    </legalnotice>
  </bookinfo>
  <toc/>
      &introduction;
      &architecture;
      &working;
      &dotnet;
	  &xsdConfig;
	  &xsdSqlMap;
</book>


text:
package cmd

import (
	"fmt"
	"os"

	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "parsec-ec2",
	Short: "Start and stop Parsec EC2 instances with a single command",
	Long:  ``,
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

var installPath, region, cfgFile, goPath, instanceType, projectPath, amiName string
var volumeSize int

func init() {
	cobra.OnInitialize(initConfig)

	RootCmd.PersistentFlags().StringVarP(&region, "region", "r", "", "aws region")
	RootCmd.PersistentFlags().StringVarP(&instanceType, "instance-type", "i", "", "ec2 instance type")
	RootCmd.PersistentFlags().StringVarP(&amiName, "ami-name", "a", "", "AMI Name to create ec2 instance")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		goPath = os.Getenv("GOPATH")

		projectPath = fmt.Sprintf("%s/src/github.com/tereshkin/parsec-ec2", goPath)
		installPath = fmt.Sprintf("%s/.parsec-ec2", home)

		// Search config in home directory with name ".parsec-ec2" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".parsec-ec2")
	}

	viper.SetEnvPrefix("parsec_ec2")
	viper.AutomaticEnv() // read in environment variables that match
	serverKey = viper.GetString("server_key")

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}


text:
<?php

namespace Falc\Robo\Service\CommandBuilder;

/**
 * SysVinit command builder.
 */
abstract class SysVinitCommandBuilder implements CommandBuilderInterface
{
    /**
     * Command name.
     *
     * @var string
     */
    protected $cmd;

    /**
     * Command action.
     *
     * @var string
     */
    protected $action;

    /**
     * Whether the command should be quiet or not.
     *
     * @var boolean
     */
    protected $quiet = false;

    /**
     * Service.
     *
     * @var string
     */
    protected $service;

    /**
     * Option list.
     *
     * @var string[]
     */
    protected $options = [];

    /**
     * {@inheritdoc}
     */
    public function start($service)
    {
        if (empty($service)) {
            throw new \InvalidArgumentException('No service selected to be started');
        }

        $this->cmd = '/etc/init.d';
        $this->service = $service;
        $this->action = 'start';

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function stop($service)
    {
        if (empty($service)) {
            throw new \InvalidArgumentException('No service selected to be stopped');
        }

        $this->cmd = '/etc/init.d';
        $this->service = $service;
        $this->action = 'stop';

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function restart($service)
    {
        if (empty($service)) {
            throw new \InvalidArgumentException('No service selected to be restarted');
        }

        $this->cmd = '/etc/init.d';
        $this->service = $service;
        $this->action = 'restart';

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function reload($service)
    {
        if (empty($service)) {
            throw new \InvalidArgumentException('No service selected to be reloaded');
        }

        $this->cmd = '/etc/init.d';
        $this->service = $service;
        $this->action = 'reload';

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    abstract public function enable($service);

    /**
     * {@inheritdoc}
     */
    abstract public function disable($service);

    /**
     * {@inheritdoc}
     *
     * @throws \BadMethodCallException
     */
    public function daemonReload()
    {
        throw new \BadMethodCallException('Action "daemon-reload" not supported for SysVinit');
    }

    /**
     * {@inheritdoc}
     */
    public function quiet()
    {
        $this->quiet = true;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getCommand()
    {
        $options = implode(' ', array_unique($this->options));

        $command = "{$this->cmd}/{$this->service} {$this->action} {$options}";

        if (!in_array($this->action, ['start', 'stop', 'restart', 'reload'])) {
            $command = "{$this->cmd} {$options} {$this->service} {$this->action}";
        }

        if ($this->quiet === true) {
            $command = "{$command} > /dev/null";
        }

        // Remove extra whitespaces
        $command = preg_replace('/\s+/', ' ', trim($command));

        return $command;
    }
}


text:
namespace Microsoft.Live
{
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    using Windows.UI.Core;
    using Windows.UI.Xaml;

    internal class SynchronizationContextWrapper
    {
        private readonly CoreDispatcher syncContext;

        public SynchronizationContextWrapper(CoreDispatcher syncContext)
        {
            this.syncContext = syncContext;
        }

        static public SynchronizationContextWrapper Current
        {
            get
            {
                try
                {
                    if (Window.Current != null && Window.Current.Dispatcher != null)
                    {
                        return new SynchronizationContextWrapper(Window.Current.Dispatcher);
                    }
                }
                catch (COMException)
                {
                }

                return new SynchronizationContextWrapper(null);
            }
        }

        public async void Post(Action callback)
        {
            Debug.Assert(callback != null);

            if (this.syncContext != null)
            {
                await this.syncContext.RunAsync(
                    CoreDispatcherPriority.Normal,
                    delegate()
                    {
                        callback();
                    });
            }
            else
            {
                callback();
            }
        }
    }
}


text:
class DevToolsNetworkProtocolHandler;

class DevToolsManagerDelegateAndroid :
    public content::DevToolsManagerDelegate,
    public content::DevToolsAgentHostObserver {
 public:
  DevToolsManagerDelegateAndroid();
  ~DevToolsManagerDelegateAndroid() override;

 private:
  // content::DevToolsManagerDelegate implementation.
  base::DictionaryValue* HandleCommand(
      content::DevToolsAgentHost* agent_host,
      base::DictionaryValue* command_dict) override;
  std::string GetTargetType(content::RenderFrameHost* host) override;
  std::string GetTargetTitle(content::RenderFrameHost* host) override;
  bool DiscoverTargets(
      const content::DevToolsAgentHost::DiscoveryCallback& callback) override;
  scoped_refptr<content::DevToolsAgentHost> CreateNewTarget(
      const GURL& url) override;
  std::string GetDiscoveryPageHTML() override;

  // content::DevToolsAgentHostObserver overrides.
  void DevToolsAgentHostAttached(
      content::DevToolsAgentHost* agent_host) override;
  void DevToolsAgentHostDetached(
      content::DevToolsAgentHost* agent_host) override;

  std::unique_ptr<DevToolsNetworkProtocolHandler> network_protocol_handler_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsManagerDelegateAndroid);
};

#endif  // CHROME_BROWSER_ANDROID_DEVTOOLS_MANAGER_DELEGATE_ANDROID_H_


text:
import test_base

class TestA10Openstack(test_base.UnitTestBase):

    def test_sanity(self):
        pass

    def test_verify(self):
        self.a._verify_appliances()


text:
The framework currently uses [mocha](http://visionmedia.github.com/mocha/) for
its testing. This enables node.js-based super-fast unit tests as well as
browser-based tests.

## Running Tests

Ensure your deps are up to date (only required when changing goog.requires):

    anvil build :deps

To run from the command-line, use the `run-tests.sh` script in the root:

    # Run all tests
    ./run-tests.sh

    # Run just zf.io tests
    ./run-tests.sh zf.io

To run the tests in the browser, navigate to the main test runner page:

    http://localhost:8080/src/zf/testing/test.html

This will run all tests. You can click on a test suite to narrow down to running
just those tests. You can also pass `?tests=some,tests` in the URL to run suites
by test namespace name (for example `?tests=zf.io` will run the
`src/zf/io/io_test.js` tests).

## Authoring Tests

Each piece of testable functionality (namespace, types, etc) should have a
corresponding _test.js file. The test file should provide a namespace that
is the name of the namespace or type being tested with a '_test' suffix.

### Example

    goog.provide('zf.MyType_test');

    zf.MyType_test = suite('zf.MyType', function() {
      setup(function() {
        // Test suite setup code.
      });
      teardown(function() {
        // Test suite teardown code.
      });
      suite('#someFunction', function() {
        // Tests related to MyType.someFunction.
        assert.isTrue(true);
      });
    });

### Assertions

Currently the project is using the mocha TDD UI along with the assertions from
the [Chai Assertion Library](http://chaijs.com/api/assert/). See the reference
for more information.

### Note on Side-effects

Since many tests can run in the same context (unsandboxed) you should ensure
that any changes made to global state are reverted when the tests are torn down.


text:
package base

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"runtime/debug"
	"strings"
	"sync"
	"time"

	"github.com/natefinch/lumberjack"
	"github.com/pkg/errors"
)

var (
	ErrInvalidLogFilePath = errors.New("invalid log file path")

	maxAgeLimit                            = 9999 // days
	defaultMaxSize                         = 100  // 100 MB
	defaultMaxAgeMultiplier                = 2    // e.g. 90 minimum == 180 default maxAge
	defaultCumulativeMaxSizeBeforeDeletion = 1024 // 1 GB
	minRotatedLogsSizeLimit                = 10   // 10 MB
	rotatedLogsLowWatermarkMultiplier      = 0.8  // eg. 100 minRotatedLogsSizeLimit == 80 low watermark

	logFilePrefix = "sg_"

	belowMinValueFmt = "%s for %v was set to %d which is below the minimum of %d"
	aboveMaxValueFmt = "%s for %v was set to %d which is above the maximum of %d"
)

type FileLogger struct {
	Enabled bool

	// collateBuffer is used to store log entries to batch up multiple logs.
	collateBuffer   chan string
	collateBufferWg *sync.WaitGroup
	flushChan       chan struct{}
	level           LogLevel
	name            string
	output          io.Writer
	logger          *log.Logger
	buffer          strings.Builder
}

type FileLoggerConfig struct {
	Enabled  *bool             `json:"enabled,omitempty"`  // Toggle for this log output
	Rotation logRotationConfig `json:"rotation,omitempty"` // Log rotation settings

	CollationBufferSize *int      `json:"collation_buffer_size,omitempty"` // The size of the log collation buffer.
	Output              io.Writer `json:"-"`                               // Logger output. Defaults to os.Stderr. Can be overridden for testing purposes.
}

type logRotationConfig struct {
	MaxSize              *int `json:"max_size,omitempty"`                // The maximum size in MB of the log file before it gets rotated.
	MaxAge               *int `json:"max_age,omitempty"`                 // The maximum number of days to retain old log files.
	LocalTime            bool `json:"localtime,omitempty"`               // If true, it uses the computer's local time to format the backup timestamp.
	RotatedLogsSizeLimit *int `json:"rotated_logs_size_limit,omitempty"` // Max Size of log files before deletion
}

// NewFileLogger returns a new FileLogger from a config.
func NewFileLogger(config *FileLoggerConfig, level LogLevel, name string, logFilePath string, minAge int, buffer *strings.Builder) (*FileLogger, error) {

	if config == nil {
		config = &FileLoggerConfig{}
	}

	// validate and set defaults
	if err := config.init(level, name, logFilePath, minAge); err != nil {
		return nil, err
	}

	logger := &FileLogger{
		Enabled: *config.Enabled,
		level:   level,
		name:    name,
		output:  config.Output,
		logger:  log.New(config.Output, "", 0),
	}

	if buffer != nil {
		logger.buffer = *buffer
	}

	// Only create the collateBuffer channel and worker if required.
	if *config.CollationBufferSize > 1 {
		logger.collateBuffer = make(chan string, *config.CollationBufferSize)
		logger.flushChan = make(chan struct{}, 1)
		logger.collateBufferWg = &sync.WaitGroup{}

		// Start up a single worker to consume messages from the buffer
		go logCollationWorker(logger.collateBuffer, logger.flushChan, logger.collateBufferWg, logger.logger, *config.CollationBufferSize, fileLoggerCollateFlushTimeout)
	}

	return logger, nil
}

func (l *FileLogger) FlushBufferToLog() {
	// Need to clear hanging new line to avoid empty line
	logString := strings.TrimSuffix(l.buffer.String(), "\n")
	l.logf(logString)
}

// Rotate will rotate the active log file.
func (l *FileLogger) Rotate() error {
	if l == nil {
		return errors.New("nil FileLogger")
	}

	if logger, ok := l.output.(*lumberjack.Logger); ok {
		return logger.Rotate()
	}

	return errors.New("can't rotate non-lumberjack log output")
}

func (l *FileLogger) String() string {
	return "FileLogger(" + l.level.String() + ")"
}

// logf will put the given message into the collation buffer if it exists,
// otherwise will log the message directly.
func (l *FileLogger) logf(format string, args ...interface{}) {
	if l.collateBuffer != nil {
		l.collateBufferWg.Add(1)
		l.collateBuffer <- fmt.Sprintf(format, args...)
	} else {
		l.logger.Printf(format, args...)
	}
}

// shouldLog returns true if we can log.
func (l *FileLogger) shouldLog(logLevel LogLevel) bool {
	return l != nil && l.logger != nil &&
		// Check the log file is enabled
		l.Enabled &&
		// Check the log level is enabled
		l.level >= logLevel
}

func (lfc *FileLoggerConfig) init(level LogLevel, name string, logFilePath string, minAge int) error {
	if lfc == nil {
		return errors.New("nil LogFileConfig")
	}

	if lfc.Enabled == nil {
		// enable for all levels less verbose than debug by default
		lfc.Enabled = BoolPtr(level < LevelDebug)
	}

	if err := lfc.initRotationConfig(name, defaultMaxSize, minAge); err != nil {
		return err
	}

	if lfc.Output == nil {
		lfc.Output = newLumberjackOutput(
			filepath.Join(filepath.FromSlash(logFilePath), logFilePrefix+name+".log"),
			*lfc.Rotation.MaxSize,
			*lfc.Rotation.MaxAge,
		)
	}

	if lfc.CollationBufferSize == nil {
		bufferSize := 0
		// Set a default CollationBufferSize for verbose logs.
		if level >= LevelInfo {
			bufferSize = defaultFileLoggerCollateBufferSize
		}
		lfc.CollationBufferSize = &bufferSize
	}

	ticker := time.NewTicker(time.Hour)
	go func() {
		defer func() {
			if panicked := recover(); panicked != nil {
				Warnf("Panic when deleting rotated log files: \n %s", panicked, debug.Stack())
			}
		}()
		for {
			select {
			case <-ticker.C:
				err := runLogDeletion(logFilePath, level.String(), int(float64(*lfc.Rotation.RotatedLogsSizeLimit)*rotatedLogsLowWatermarkMultiplier), *lfc.Rotation.RotatedLogsSizeLimit)
				if err != nil {
					Warnf("%s", err)
				}
			}
		}
	}()

	return nil
}

func (lfc *FileLoggerConfig) initRotationConfig(name string, defaultMaxSize, minAge int) error {
	if lfc.Rotation.MaxSize == nil {
		lfc.Rotation.MaxSize = &defaultMaxSize
	} else if *lfc.Rotation.MaxSize == 0 {
		// A value of zero disables the log file rotation in Lumberjack.
	} else if *lfc.Rotation.MaxSize < 0 {
		return fmt.Errorf(belowMinValueFmt, "MaxSize", name, *lfc.Rotation.MaxSize, 0)
	}

	if lfc.Rotation.MaxAge == nil {
		defaultMaxAge := minAge * defaultMaxAgeMultiplier
		lfc.Rotation.MaxAge = &defaultMaxAge
	} else if *lfc.Rotation.MaxAge == 0 {
		// A value of zero disables the age-based log cleanup in Lumberjack.
	} else if *lfc.Rotation.MaxAge < minAge {
		return fmt.Errorf(belowMinValueFmt, "MaxAge", name, *lfc.Rotation.MaxAge, minAge)
	} else if *lfc.Rotation.MaxAge > maxAgeLimit {
		return fmt.Errorf(aboveMaxValueFmt, "MaxAge", name, *lfc.Rotation.MaxAge, maxAgeLimit)
	}

	if lfc.Rotation.RotatedLogsSizeLimit == nil {
		lfc.Rotation.RotatedLogsSizeLimit = &defaultCumulativeMaxSizeBeforeDeletion
	} else if *lfc.Rotation.RotatedLogsSizeLimit < minRotatedLogsSizeLimit {
		return fmt.Errorf(belowMinValueFmt, "RotatedLogsSizeLimit", name, *lfc.Rotation.RotatedLogsSizeLimit, minRotatedLogsSizeLimit)
	}

	return nil
}

func newLumberjackOutput(filename string, maxSize, maxAge int) *lumberjack.Logger {
	return &lumberjack.Logger{
		Filename: filename,
		MaxSize:  maxSize,
		MaxAge:   maxAge,
		Compress: true,
	}
}

// runLogDeletion will delete rotated logs for the supplied logLevel. It will only perform these deletions when the
// cumulative size of the logs are above the supplied sizeLimitMB.
// logDirectory is the supplied directory where the logs are stored.
func runLogDeletion(logDirectory string, logLevel string, sizeLimitMBLowWatermark int, sizeLimitMBHighWatermark int) (err error) {

	sizeLimitMBLowWatermark = sizeLimitMBLowWatermark * 1024 * 1024   //Convert MB input to bytes
	sizeLimitMBHighWatermark = sizeLimitMBHighWatermark * 1024 * 1024 //Convert MB input to bytes

	files, err := ioutil.ReadDir(logDirectory)

	if err != nil {
		return errors.New(fmt.Sprintf("Error reading log directory: %v", err))
	}

	// Traverse backwards through sorted log filenames. When low watermark is reached we record the point at which this
	// was passed. Once we also pass the high watermark we loop through from the low watermark and remove.
	totalSize := 0
	indexDeletePoint := -1
	willDelete := false
	for i := len(files) - 1; i >= 0; i-- {
		file := files[i]
		if strings.HasPrefix(file.Name(), logFilePrefix+logLevel) && strings.HasSuffix(file.Name(), ".log.gz") {
			totalSize += int(file.Size())
			if totalSize > sizeLimitMBLowWatermark && indexDeletePoint == -1 {
				indexDeletePoint = i
			}
			if totalSize > sizeLimitMBHighWatermark {
				willDelete = true
				break
			}
		}
	}

	if willDelete {
		for j := indexDeletePoint; j >= 0; j-- {
			file := files[j]
			if strings.HasPrefix(file.Name(), logFilePrefix+logLevel) && strings.HasSuffix(file.Name(), ".log.gz") {
				err = os.Remove(filepath.Join(logDirectory, file.Name()))
				if err != nil {
					return errors.New(fmt.Sprintf("Error deleting stale log file: %v", err))
				}
			}
		}
	}

	return nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Op. bot. 103: 80 (1991)

#### Original name
null

### Remarks
null


text:
"""
Django settings for web_games project.

Generated by 'django-admin startproject' using Django 1.8.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.utils.translation import ugettext_lazy as _

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x+2(&9(k))e+*)(hm+o)ht-ry_s@)_zz31^y9u#)t(lv)9u5iw'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admindocs',
    'game_console',
    'million',
    'jeopardy'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'web_games.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'web_games.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-US'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

LANGUAGES = (
    ('it', 'Italiano'),
    ('en', 'English'),
)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'www', 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'www', 'static')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)


text:
;(function($n2){
"use strict";

// Localization
var _loc = function(str,args){ return $n2.loc(str,'nunaliit2',args); }
,DH = 'n2.error'
;

// *******************************************************
var Error = $n2.Class({

	msg: undefined,

	cause: undefined,

	conditions: undefined,

	initialize: function(opts_){
		var opts = $n2.extend({
			msg: undefined
			,cause: undefined
			,conditions: undefined
		},opts_);

		this.msg = opts.msg;
		this.cause = opts.cause;

		if( $n2.isArray(opts.conditions) ){
			for(var i=0,e=opts.conditions.length; i<e; ++i){
				var condition = opts.conditions[i];
				this.setCondition(condition);
			};
		};
	},

	getMessage: function(){
		if( typeof this.msg === 'string' ){
			return this.msg;
		};
		return _loc('<error>');
	},

	setCondition: function(condition){
		if( typeof condition === 'string' ){
			if( !this.conditions ){
				this.conditions = {};
			};
			this.conditions[condition] = true;
		};
	},

	isConditionSet: function(condition){
		if( typeof condition === 'string' ){
			if( this.conditions
			 && this.conditions[condition] ){
				return true;
			};

			if( this.cause
			 && typeof this.cause.isConditionSet === 'function' ){
				return this.cause.isConditionSet(condition);
			};
		};

		return false;
	},

	getCause: function(){
		return this.cause;
	},

	setCause: function(cause){
		this.cause = cause;
	},

	toString: function(){
		var messages = [];
		var cause = this;
		while( cause ){
			if( cause.msg ){
				messages.push(cause.msg);
			};
			cause = cause.cause;
		};
		if( messages.length < 1 ){
			messages.push( _loc('<error>') );
		};
		return messages.join(': ');
	}
});

//*******************************************************
function fromString(str,cause){
	var err = new Error({
		msg: str
		,cause: cause
	});

	return err;
};

//*******************************************************
function checkErrorCondition(err, condition){
	if( typeof err === 'object'
	 && typeof err.isConditionSet === 'function' ){
		return err.isConditionSet(condition);
	};
	return false;
};

//*******************************************************
$n2.error = {
	Error: Error
	,fromString: fromString
	,checkErrorCondition: checkErrorCondition
};

})(nunaliit2);


text:
'use strict';

exports.__esModule = true;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _kapow = require('kapow');

var _kapow2 = _interopRequireDefault(_kapow);

var EXPECTED_TYPE = 'application/vnd.api+json';

exports['default'] = function (request) {
  var err;

  var contentType = request.headers['content-type'];

  var isValidContentType = contentType && contentType.toLowerCase().indexOf(EXPECTED_TYPE) === 0;

  if (!isValidContentType) {
    err = _kapow2['default'](415, 'Content-Type must be "' + EXPECTED_TYPE + '"');
  }

  return err;
};

module.exports = exports['default'];


text:
var Delta = require('../../lib/delta');

describe('diff()', function () {
  it('insert', function () {
    var a = new Delta().insert('A');
    var b = new Delta().insert('AB');
    var expected = new Delta().retain(1).insert('B');
    expect(a.diff(b)).toEqual(expected);
  });

  it('delete', function () {
    var a = new Delta().insert('AB');
    var b = new Delta().insert('A');
    var expected = new Delta().retain(1).delete(1);
    expect(a.diff(b)).toEqual(expected);
  });

  it('retain', function () {
    var a = new Delta().insert('A');
    var b = new Delta().insert('A');
    var expected = new Delta();
    expect(a.diff(b)).toEqual(expected);
  });

  it('format', function () {
    var a = new Delta().insert('A');
    var b = new Delta().insert('A', { bold: true });
    var expected = new Delta().retain(1, { bold: true });
    expect(a.diff(b)).toEqual(expected);
  });

  it('object attributes', function () {
    var a = new Delta().insert('A', { font: { family: 'Helvetica', size: '15px' } });
    var b = new Delta().insert('A', { font: { family: 'Helvetica', size: '15px' } });
    var expected = new Delta();
    expect(a.diff(b)).toEqual(expected);
  });

  it('embed integer match', function () {
    var a = new Delta().insert(1);
    var b = new Delta().insert(1);
    var expected = new Delta();
    expect(a.diff(b)).toEqual(expected);
  });

  it('embed integer mismatch', function () {
    var a = new Delta().insert(1);
    var b = new Delta().insert(2);
    var expected = new Delta().delete(1).insert(2);
    expect(a.diff(b)).toEqual(expected);
  });

  it('embed object match', function () {
    var a = new Delta().insert({ image: 'http://quilljs.com' });
    var b = new Delta().insert({ image: 'http://quilljs.com' });
    var expected = new Delta();
    expect(a.diff(b)).toEqual(expected);
  });

  it('embed object mismatch', function () {
    var a = new Delta().insert({ image: 'http://quilljs.com', alt: 'Overwrite' });
    var b = new Delta().insert({ image: 'http://quilljs.com' });
    var expected = new Delta().insert({ image: 'http://quilljs.com' }).delete(1);
    expect(a.diff(b)).toEqual(expected);
  });

  it('embed object change', function () {
    var embed = { image: 'http://quilljs.com' };
    var a = new Delta().insert(embed);
    embed.image = 'http://github.com';
    var b = new Delta().insert(embed);
    var expected = new Delta().insert({ image: 'http://github.com' }).delete(1);
    expect(a.diff(b)).toEqual(expected);
  });

  it('embed false positive', function () {
    var a = new Delta().insert(1);
    var b = new Delta().insert(String.fromCharCode(0)); // Placeholder char for embed in diff()
    var expected = new Delta().insert(String.fromCharCode(0)).delete(1);
    expect(a.diff(b)).toEqual(expected);
  });

  it('error on non-documents', function () {
    var a = new Delta().insert('A');
    var b = new Delta().retain(1).insert('B');
    expect(function () {
      a.diff(b);
    }).toThrow();
    expect(function () {
      b.diff(a);
    }).toThrow();
  });

  it('inconvenient indexes', function () {
    var a = new Delta().insert('12', { bold: true }).insert('34', { italic: true });
    var b = new Delta().insert('123', { color: 'red' });
    var expected = new Delta().retain(2, { bold: null, color: 'red' }).retain(1, { italic: null, color: 'red' }).delete(1);
    expect(a.diff(b)).toEqual(expected);
  });

  it('combination', function () {
    var a = new Delta().insert('Bad', { color: 'red' }).insert('cat', { color: 'blue' });
    var b = new Delta().insert('Good', { bold: true }).insert('dog', { italic: true });
    var expected = new Delta().insert('Good', { bold: true }).delete(2).retain(1, { italic: true, color: null }).delete(3).insert('og', { italic: true });
    expect(a.diff(b)).toEqual(expected);
  });

  it('same document', function () {
    var a = new Delta().insert('A').insert('B', { bold: true });
    expected = new Delta();
    expect(a.diff(a)).toEqual(expected);
  });

  it('immutability', function () {
    var attr1 = { color: 'red' };
    var attr2 = { color: 'red' };
    var a1 = new Delta().insert('A', attr1);
    var a2 = new Delta().insert('A', attr1);
    var b1 = new Delta().insert('A', { bold: true }).insert('B');
    var b2 = new Delta().insert('A', { bold: true }).insert('B');
    var expected = new Delta().retain(1, { bold: true, color: null }).insert('B');
    expect(a1.diff(b1)).toEqual(expected);
    expect(a1).toEqual(a2);
    expect(b2).toEqual(b2);
    expect(attr1).toEqual(attr2);
  });

  it('non-document', function () {
    var a = new Delta().insert('Test');
    var b = new Delta().delete(4);
    expect(function() {
      a.diff(b);
    }).toThrow(new Error('diff() called on non-document'));
  });
});


text:
package gull

type Down struct {
	MigrationTarget MigrationTarget
	Migrations      *Migrations
}

func NewDown(target MigrationTarget) *Down {
	return &Down{
		MigrationTarget: target,
	}
}

func (d *Down) Migrate() error {
	status, err := d.MigrationTarget.GetStatus()
	if err != nil {
		return err
	}
	d.Migrations = status.Migrations
	_, err = status.Migrations.Pop()
	if err != nil {
		return err
	}
	_ = d.MigrationTarget.DeleteEnvironment()
	return status.Migrations.Apply(d.MigrationTarget)
}


text:
/***********************************************************************************************************************************
Harness for Loading Test Configurations
***********************************************************************************************************************************/
#include "build.auto.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

#include "common/io/io.h"
#include "config/config.intern.h"
#include "config/load.h"
#include "config/parse.h"
#include "storage/helper.h"
#include "version.h"

#include "common/harnessConfig.h"
#include "common/harnessDebug.h"
#include "common/harnessLog.h"
#include "common/harnessTest.h"

/**********************************************************************************************************************************/
void
hrnCfgLoad(ConfigCommand commandId, const StringList *argListParam, const HrnCfgLoadParam param)
{
    FUNCTION_HARNESS_BEGIN();
        FUNCTION_HARNESS_PARAM(ENUM, commandId);
        FUNCTION_HARNESS_PARAM(STRING_LIST, argListParam);
        FUNCTION_HARNESS_PARAM(ENUM, param.role);
        FUNCTION_HARNESS_PARAM(BOOL, param.exeBogus);
        FUNCTION_HARNESS_PARAM(BOOL, param.noStd);
        FUNCTION_HARNESS_PARAM(BOOL, param.log);
        FUNCTION_HARNESS_PARAM(UINT, param.jobRetry);
        FUNCTION_HARNESS_PARAM(STRINGZ, param.comment);
    FUNCTION_HARNESS_END();

    // Make a copy of the arg list that we can modify
    StringList *argList = strLstDup(argListParam);

    // Add standard options needed in most cases
    if (!param.noStd)
    {
        // Set job retry to 0 if it is valid
        if (cfgParseOptionValid(commandId, param.role, cfgOptJobRetry))
            strLstInsert(argList, 0, strNewFmt("--" CFGOPT_JOB_RETRY "=%u", param.jobRetry));

        // Set log path if valid
        if (cfgParseOptionValid(commandId, param.role, cfgOptLogPath))
            strLstInsert(argList, 0, strNewFmt("--" CFGOPT_LOG_PATH "=%s", hrnPath()));

        // Set lock path if valid
        if (cfgParseOptionValid(commandId, param.role, cfgOptLockPath))
            strLstInsert(argList, 0, strNewFmt("--" CFGOPT_LOCK_PATH "=%s/lock", hrnPath()));
    }

    // Insert the command so it does not interfere with parameters
    if (commandId != cfgCmdNone)
        strLstInsert(argList, 0, cfgParseCommandRoleName(commandId, param.role));

    // Insert the project exe
    strLstInsert(argList, 0, param.exeBogus ? STRDEF("pgbackrest-bogus") : STRDEF(testProjectExe()));

    // Log parameters
    if (param.log)
    {
        printf("config load:");

        for (unsigned int argIdx = 0; argIdx < strLstSize(argList); argIdx++)
            printf(" %s", strZ(strLstGet(argList, argIdx)));

        hrnTestResultComment(param.comment);
    }

    // Free objects in storage helper
    storageHelperFree();

    // Parse config
    configParse(storageLocal(), strLstSize(argList), strLstPtr(argList), false);

    // Set dry-run mode for storage and logging
    harnessLogDryRunSet(cfgOptionValid(cfgOptDryRun) && cfgOptionBool(cfgOptDryRun));
    storageHelperDryRunInit(cfgOptionValid(cfgOptDryRun) && cfgOptionBool(cfgOptDryRun));

    // Apply special option rules
    cfgLoadUpdateOption();

    // Set buffer size when it is specified explicitly -- otherwise the module default will be used. Note that this is *not* the
    // configuration default, which is much larger.
    if (cfgOptionTest(cfgOptBufferSize))
        ioBufferSizeSet(cfgOptionUInt(cfgOptBufferSize));

    // Use a static exec-id for testing if it is not set explicitly
    if (cfgOptionValid(cfgOptExecId) && !cfgOptionTest(cfgOptExecId))
        cfgOptionSet(cfgOptExecId, cfgSourceParam, VARSTRDEF("1-test"));

    FUNCTION_HARNESS_RETURN_VOID();
}

/**********************************************************************************************************************************/
void
hrnCfgArgRaw(StringList *argList, ConfigOption optionId, const String *value)
{
    hrnCfgArgKeyRawZ(argList, optionId, 1, strZ(value));
}

void
hrnCfgArgKeyRaw(StringList *argList, ConfigOption optionId, unsigned optionKey, const String *value)
{
    hrnCfgArgKeyRawZ(argList, optionId, optionKey, strZ(value));
}

void
hrnCfgArgRawFmt(StringList *argList, ConfigOption optionId, const char *format, ...)
{
    char buffer[256];

    va_list argument;
    va_start(argument, format);
    vsnprintf(buffer, sizeof(buffer) - 1, format, argument);
    va_end(argument);

    hrnCfgArgKeyRawZ(argList, optionId, 1, buffer);
}

void
hrnCfgArgKeyRawFmt(StringList *argList, ConfigOption optionId, unsigned optionKey, const char *format, ...)
{
    char buffer[256];

    va_list argument;
    va_start(argument, format);
    vsnprintf(buffer, sizeof(buffer) - 1, format, argument);
    va_end(argument);

    hrnCfgArgKeyRawZ(argList, optionId, optionKey, buffer);
}

void
hrnCfgArgRawZ(StringList *argList, ConfigOption optionId, const char *value)
{
    hrnCfgArgKeyRawZ(argList, optionId, 1, value);
}

void
hrnCfgArgKeyRawZ(StringList *argList, ConfigOption optionId, unsigned optionKey, const char *value)
{
    strLstAddFmt(argList, "--%s=%s", cfgParseOptionKeyIdxName(optionId, optionKey - 1), value);
}

void
hrnCfgArgRawStrId(StringList *argList, ConfigOption optionId, StringId value)
{
    hrnCfgArgKeyRawStrId(argList, optionId, 1, value);
}

void
hrnCfgArgKeyRawStrId(StringList *argList, ConfigOption optionId, unsigned optionKey, StringId value)
{
    char buffer[STRID_MAX + 1];
    strIdToZ(value, buffer);

    hrnCfgArgKeyRawZ(argList, optionId, optionKey, buffer);
}

void
hrnCfgArgRawBool(StringList *argList, ConfigOption optionId, bool value)
{
    hrnCfgArgKeyRawBool(argList, optionId, 1, value);
}

void
hrnCfgArgKeyRawBool(StringList *argList, ConfigOption optionId, unsigned optionKey, bool value)
{
    strLstAddFmt(argList, "--%s%s", value ? "" : "no-", cfgParseOptionKeyIdxName(optionId, optionKey - 1));
}

void
hrnCfgArgRawNegate(StringList *argList, ConfigOption optionId)
{
    hrnCfgArgKeyRawNegate(argList, optionId, 1);
}

void
hrnCfgArgKeyRawNegate(StringList *argList, ConfigOption optionId, unsigned optionKey)
{
    strLstAddFmt(argList, "--no-%s", cfgParseOptionKeyIdxName(optionId, optionKey - 1));
}

void
hrnCfgArgRawReset(StringList *argList, ConfigOption optionId)
{
    hrnCfgArgKeyRawReset(argList, optionId, 1);
}

void
hrnCfgArgKeyRawReset(StringList *argList, ConfigOption optionId, unsigned optionKey)
{
    strLstAddFmt(argList, "--reset-%s", cfgParseOptionKeyIdxName(optionId, optionKey - 1));
}

/**********************************************************************************************************************************/
FN_INLINE_ALWAYS const char *
hrnCfgEnvName(const ConfigOption optionId, const unsigned optionKey)
{
    return strZ(
        strReplaceChr(strUpper(strNewFmt(HRN_PGBACKREST_ENV "%s", cfgParseOptionKeyIdxName(optionId, optionKey - 1))), '-', '_'));
}

void
hrnCfgEnvRaw(ConfigOption optionId, const String *value)
{
    hrnCfgEnvKeyRawZ(optionId, 1, strZ(value));
}

void
hrnCfgEnvKeyRaw(ConfigOption optionId, unsigned optionKey, const String *value)
{
    hrnCfgEnvKeyRawZ(optionId, optionKey, strZ(value));
}

void
hrnCfgEnvRawZ(ConfigOption optionId, const char *value)
{
    hrnCfgEnvKeyRawZ(optionId, 1, value);
}

void
hrnCfgEnvKeyRawZ(ConfigOption optionId, unsigned optionKey, const char *value)
{
    setenv(hrnCfgEnvName(optionId, optionKey), value, true);
}

void
hrnCfgEnvRemoveRaw(ConfigOption optionId)
{
    hrnCfgEnvKeyRemoveRaw(optionId, 1);
}

void
hrnCfgEnvKeyRemoveRaw(ConfigOption optionId, unsigned optionKey)
{
    unsetenv(hrnCfgEnvName(optionId, optionKey));
}


text:
Clean up user-entered phone numbers so that they can be sent SMS messages.

The **North American Numbering Plan (NANP)** is a telephone numbering system used by many countries in North America like the United States, Canada or Bermuda. All NANP-countries share the same international country code: `1`.

NANP numbers are ten-digit numbers consisting of a three-digit Numbering Plan Area code, commonly known as *area code*, followed by a seven-digit local number. The first three digits of the local number represent the *exchange code*, followed by the unique four-digit number which is the *subscriber number*.

The format is usually represented as

```text
(NXX)-NXX-XXXX
```

where `N` is any digit from 2 through 9 and `X` is any digit from 0 through 9.

Your task is to clean up differently formatted telephone numbers by removing punctuation and the country code (1) if present.

For example, the inputs
- `+1 (613)-995-0253`
- `613-995-0253`
- `1 613 995 0253`
- `613.995.0253`

should all produce the output

`6139950253`

**Note:** As this exercise only deals with telephone numbers used in NANP-countries, only 1 is considered a valid country code.

## Running tests

Execute the tests with:

```bash
$ elixir phone_number_test.exs
```

### Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by
commenting out the relevant `@tag :pending` with a `#` symbol.

For example:

```elixir
# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```

Or, you can enable all the tests by commenting out the
`ExUnit.configure` line in the test suite.

```elixir
# ExUnit.configure exclude: :pending, trace: true
```

For more detailed information about the Elixir track, please
see the [help page](http://exercism.io/languages/elixir).

## Source

Event Manager by JumpstartLab [http://tutorials.jumpstartlab.com/projects/eventmanager.html](http://tutorials.jumpstartlab.com/projects/eventmanager.html)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function(grunt) {

    grunt.initConfig({
        pkg: require('./package'),
        // watson: require('./watson'),
        composer: require('./composer'),
        directories: {
            test: 'test',
            source: 'src'
        },
        files: {
            js: [
                'Gruntfile.js',
                'grunt/{,*/}*.js'

            ],
            php: [
                '<%= directories.source %>/**/*.php',
            ],
            json: [
                '*.json',
                'grunt/hooks/data/*.json'
            ],
            packages: ['package.json', 'composer.json']
        }
    });

    // show elapsed time at the end
    require('time-grunt')(grunt);
    // load grunt tasks "just in time"
    require('jit-grunt')(grunt);
    grunt.loadTasks('grunt/tasks');
};


text:
@implementation ARPostFeedItem

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return [super.JSONKeyPathsByPropertyKey mtl_dictionaryByAddingEntriesFromDictionary:@{
        @"postID" : @"id",
        @"bodyHTML" : @"body",
        @"title" : @"title",
        @"type" : @"layout",
        @"profile" : @"profile",
        @"artworks" : @"artworks",
        @"contentLinks" : @"content_links",
        @"postImages" : @"post_images",
        @"feedTimestamp" : @"created_at",
        @"shareableImageURL" : @"shareable_image_url"
    }];
}

+ (NSValueTransformer *)profileJSONTransformer
{
    return [MTLValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[Profile class]];
}

+ (NSValueTransformer *)artworksJSONTransformer
{
    return [MTLValueTransformer mtl_JSONArrayTransformerWithModelClass:[Artwork class]];
}

+ (NSValueTransformer *)postImagesJSONTransformer
{
    return [MTLValueTransformer mtl_JSONArrayTransformerWithModelClass:[PostImage class]];
}

+ (NSValueTransformer *)contentLinksJSONTransformer
{
    return [MTLValueTransformer mtl_JSONArrayTransformerWithModelClass:[ContentLink class]];
}

+ (NSValueTransformer *)bodyJSONTransformer
{
    return [MTLValueTransformer transformerWithBlock:^id(id str) {
        return [[str stringByReplacingOccurrencesOfString:@"\n" withString:@" "]
                stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }];
}

+ (NSValueTransformer *)typeJSONTransformer
{
    NSDictionary *types = @{
        @"singlecolumn" : @(ARPostTypeSingleColumn),
        @"twocolumn" : @(ARPostTypeTwoColumn),
        @"textonly" : @(ARPostTypeTextOnly)
    };

    return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) {
        return types[str];
    } reverseBlock:^(NSNumber *type) {
        return [types allKeysForObject:type].lastObject;
    }];
}

+ (NSString *)cellIdentifier
{
    return @"PostCellIdentifier";
}

- (NSInteger)attachmentCount
{
    //TODO: write fold for primitives
    NSInteger count = 0;
    for (NSArray *arr in @[ self.artworks, self.postImages, self.contentLinks ]) {
        if (arr) {
            count += arr.count;
        }
    }
    return count;
}

- (NSArray *)allAttachments
{
    NSMutableArray *ret = [[NSMutableArray alloc] init];
    for (NSArray *arr in @[ self.artworks, self.postImages, self.contentLinks ]) {
        if (arr) {
            [ret addObjectsFromArray:arr];
        }
    }
    return ret;
}

- (NSString *)publicURL
{
    return [NSString stringWithFormat:@"http://art.sy/%@/post/%@", self.profile.profileID, self.postID];
}

- (NSArray *)dataForActivities
{
    return @[ self ];
}

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType
{
    if (self.profile && self.title && ![self.title isEqualToString:@""]) {
        return [NSString stringWithFormat:@"%@: %@ via @artsy %@", self.profile.profileName, self.title, self.publicURL];

    } else if (self.profile) {
        return [NSString stringWithFormat:@"%@ on @artsy %@", self.profile.profileName, self.publicURL];

    } else {
        //TODO: this case exists in Gravity's code, but is there any way to
        // generate a link to an authorless post? Gravity would choke here
        return @"";
    }
}

- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController
{
    return @"";
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"FeedItem - Post ( %@ by %@ ) ", _title, self.profile.profileID];
}

- (NSString *)localizedStringForActivity
{
    return NSLocalizedString(@"Posted", @"Posted a post header text for Feed Item");
}

- (BOOL)hasTitle
{
    return (_title && ![_title isEqualToString:@""]);
}

- (void)updatePost:(void (^)(BOOL updateSuccessful))success
{
    [ArtsyAPI getPostForPostID:_postID success:^(id post) {
        [self mergeValuesForKeysFromModel:post];
        success(YES);

    } failure:^(NSError *error) {
        success(NO);
    }];
}

- (NSString *)imageURL
{
    NSString *imageURL = self.shareableImageURL;
    if (!imageURL && self.profile) {
        imageURL = self.profile.iconURL;
    }
    return imageURL;
}

@end