text:
namespace Appccelerate.IO.Access
{
    using System;

    /// <summary>
    /// Base extension for path extensions.
    /// </summary>
    public class PathExtensionBase : IPathExtension
    {
        public virtual void BeginGetDirectoryName(string path)
        {
        }

        public virtual void EndGetDirectoryName(string result, string path)
        {
        }

        public virtual void FailGetDirectoryName(ref Exception exception, string path)
        {
        }

        public virtual void BeginGetFileName(string path)
        {
        }

        public virtual void EndGetFileName(string result, string path)
        {
        }

        public virtual void FailGetFileName(ref Exception exception, string path)
        {
        }

        public virtual void BeginGetFileNameWithoutExtension(string path)
        {
        }

        public virtual void EndGetFileNameWithoutExtension(string result, string path)
        {
        }

        public virtual void FailGetFileNameWithoutExtension(ref Exception exception, string path)
        {
        }

        public virtual void BeginCombine(string path1, string path2)
        {
        }

        public virtual void EndCombine(string result, string path1, string path2)
        {
        }

        public virtual void FailCombine(ref Exception exception, string path1, string path2)
        {
        }

        public virtual void BeginGetRandomFileName()
        {
        }

        public virtual void EndGetRandomFileName(string result)
        {
        }

        public virtual void FailGetRandomFileName(ref Exception exception)
        {
        }

        public virtual void BeginChangeExtension(string path, string extension)
        {
        }

        public virtual void EndChangeExtension(string result, string path, string extension)
        {
        }

        public virtual void FailChangeExtension(ref Exception exception, string path, string extension)
        {
        }

        public virtual void BeginGetExtension(string path)
        {
        }

        public virtual void EndGetExtension(string result, string path)
        {
        }

        public virtual void FailGetExtension(ref Exception exception, string path)
        {
        }

        public virtual void BeginGetFullPath(string path)
        {
        }

        public virtual void EndGetFullPath(string result, string path)
        {
        }

        public virtual void FailGetFullPath(ref Exception exception, string path)
        {
        }

        public virtual void BeginGetInvalidFileNameChars()
        {
        }

        public virtual void EndGetInvalidFileNameChars(char[] result)
        {
        }

        public virtual void FailGetInvalidFileNameChars(ref Exception exception)
        {
        }

        public virtual void BeginGetInvalidPathChars()
        {
        }

        public virtual void EndGetInvalidPathChars(char[] result)
        {
        }

        public virtual void FailGetInvalidPathChars(ref Exception exception)
        {
        }

        public virtual void BeginGetPathRoot(string path)
        {
        }

        public virtual void EndGetPathRoot(string result, string path)
        {
        }

        public virtual void FailGetPathRoot(ref Exception exception, string path)
        {
        }

        public virtual void BeginGetTempFileName()
        {
        }

        public virtual void EndGetTempFileName(string result)
        {
        }

        public virtual void FailGetTempFileName(ref Exception exception)
        {
        }

        public virtual void BeginGetTempPath()
        {
        }

        public virtual void EndGetTempPath(string result)
        {
        }

        public virtual void FailGetTempPath(ref Exception exception)
        {
        }

        public virtual void BeginHasExtension(string path)
        {
        }

        public virtual void EndHasExtension(bool result, string path)
        {
        }

        public virtual void FailHasExtension(ref Exception exception, string path)
        {
        }

        public virtual void BeginIsPathRooted(string path)
        {
        }

        public virtual void EndIsPathRooted(bool result, string path)
        {
        }

        public virtual void FailIsPathRooted(ref Exception exception, string path)
        {
        }
    }
}


text:
namespace System.Security.Cryptography.Xml {
    using System;
    using System.Xml;
    using System.IO;
    using System.Text;
    using System.Collections;

    // the current rendering position in document
    internal enum DocPosition {
        BeforeRootElement,
        InRootElement,
        AfterRootElement
    }

    // the interface to be implemented by all subclasses of XmlNode
    // that have to provide node subsetting and canonicalization features.
    internal interface ICanonicalizableNode {
        bool IsInNodeSet {
            get;
            set;
        }

        void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc);
        void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc);
    }

    // the central dispatcher for canonicalization writes. not all node classes
    // implement ICanonicalizableNode; so a manual dispatch is sometimes necessary.
    internal class CanonicalizationDispatcher {
        private CanonicalizationDispatcher() {}

        public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (node is ICanonicalizableNode) {
                ((ICanonicalizableNode) node).Write(strBuilder, docPos, anc);
            } else {
                WriteGenericNode(node, strBuilder, docPos, anc);
            }
        }

        public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (node == null)
                throw new ArgumentNullException("node");

            XmlNodeList childNodes = node.ChildNodes;
            foreach (XmlNode childNode in childNodes) {
                Write(childNode, strBuilder, docPos, anc);
            }
        }

        public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (node is ICanonicalizableNode) {
                ((ICanonicalizableNode) node).WriteHash(hash, docPos, anc);
            } else {
                WriteHashGenericNode(node, hash, docPos, anc);
            }
        }

        public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (node == null)
                throw new ArgumentNullException("node");

            XmlNodeList childNodes = node.ChildNodes;
            foreach (XmlNode childNode in childNodes) {
                WriteHash(childNode, hash, docPos, anc);
            }
        }
    }

    // all input types eventually lead to the creation of an XmlDocument document
    // of this type. it maintains the node subset state and performs output rendering during canonicalization
    internal class CanonicalXmlDocument : XmlDocument, ICanonicalizableNode {
        bool m_defaultNodeSetInclusionState;
        bool m_includeComments;
        bool m_isInNodeSet;

        public CanonicalXmlDocument(bool defaultNodeSetInclusionState, bool includeComments) : base() {
            this.PreserveWhitespace = true;
            m_includeComments = includeComments;
            m_isInNodeSet = m_defaultNodeSetInclusionState = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            docPos = DocPosition.BeforeRootElement;
            foreach (XmlNode childNode in this.ChildNodes) {
                if (childNode.NodeType == XmlNodeType.Element) {
                    CanonicalizationDispatcher.Write(childNode, strBuilder, DocPosition.InRootElement, anc);
                    docPos = DocPosition.AfterRootElement;
                } else {
                    CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc);
                }
            }
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            docPos = DocPosition.BeforeRootElement;
            foreach (XmlNode childNode in this.ChildNodes) {
                if (childNode.NodeType == XmlNodeType.Element) {
                    CanonicalizationDispatcher.WriteHash(childNode, hash, DocPosition.InRootElement, anc);
                    docPos = DocPosition.AfterRootElement;
                } else {
                    CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc);
                }
            }
        }

        public override XmlElement CreateElement(string prefix, string localName, string namespaceURI) {
            return new CanonicalXmlElement(prefix, localName, namespaceURI, this, m_defaultNodeSetInclusionState);
        }

        public override XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) {
            return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, m_defaultNodeSetInclusionState);
        }

        protected override XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) {
            return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, m_defaultNodeSetInclusionState);
        }

        public override XmlText CreateTextNode(string text) {
            return new CanonicalXmlText(text, this, m_defaultNodeSetInclusionState);
        }

        public override XmlWhitespace CreateWhitespace(string prefix) {
            return new CanonicalXmlWhitespace(prefix, this, m_defaultNodeSetInclusionState);
        }

        public override XmlSignificantWhitespace CreateSignificantWhitespace(string text) {
            return new CanonicalXmlSignificantWhitespace(text, this, m_defaultNodeSetInclusionState);
        }

        public override XmlProcessingInstruction CreateProcessingInstruction(string target, string data) {
            return new CanonicalXmlProcessingInstruction(target, data, this, m_defaultNodeSetInclusionState);
        }

        public override XmlComment CreateComment(string data) {
            return new CanonicalXmlComment(data, this, m_defaultNodeSetInclusionState, m_includeComments);
        }

        public override XmlEntityReference CreateEntityReference(string name) {
            return new CanonicalXmlEntityReference(name, this, m_defaultNodeSetInclusionState);
        }

        public override XmlCDataSection CreateCDataSection(string data) {
            return new CanonicalXmlCDataSection(data, this, m_defaultNodeSetInclusionState);
        }
    }

    // the class that provides node subset state and canonicalization function to XmlElement
    internal class CanonicalXmlElement : XmlElement, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(prefix, localName, namespaceURI, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            Hashtable nsLocallyDeclared = new Hashtable();
            SortedList nsListToRender = new SortedList(new NamespaceSortOrder());
            SortedList attrListToRender = new SortedList(new AttributeSortOrder());

            XmlAttributeCollection attrList = this.Attributes;
            if (attrList != null) {
                foreach (XmlAttribute attr in attrList) {
                    if (((CanonicalXmlAttribute) attr).IsInNodeSet || Utils.IsNamespaceNode(attr) || Utils.IsXmlNamespaceNode(attr)) {
                        if (Utils.IsNamespaceNode(attr)) {
                            anc.TrackNamespaceNode(attr, nsListToRender, nsLocallyDeclared);
                        }
                        else if (Utils.IsXmlNamespaceNode(attr)) {
                            anc.TrackXmlNamespaceNode(attr, nsListToRender, attrListToRender, nsLocallyDeclared);
                        }
                        else if (IsInNodeSet) {
                            attrListToRender.Add(attr, null);
                        }
                    }
                }
            }

            if (!Utils.IsCommittedNamespace(this, this.Prefix, this.NamespaceURI)) {
                string name = ((this.Prefix.Length > 0) ? "xmlns" + ":" + this.Prefix : "xmlns");
                XmlAttribute nsattrib = (XmlAttribute) this.OwnerDocument.CreateAttribute(name);
                nsattrib.Value = this.NamespaceURI;
                anc.TrackNamespaceNode(nsattrib, nsListToRender, nsLocallyDeclared);
            }

            if (IsInNodeSet) {
                anc.GetNamespacesToRender(this, attrListToRender, nsListToRender, nsLocallyDeclared);

                strBuilder.Append("<" + this.Name);
                foreach (object attr in nsListToRender.GetKeyList()) {
                    (attr as CanonicalXmlAttribute).Write(strBuilder, docPos, anc);
                }
                foreach (object attr in attrListToRender.GetKeyList()) {
                    (attr as CanonicalXmlAttribute).Write(strBuilder, docPos, anc);
                }
                strBuilder.Append(">");
            }

            anc.EnterElementContext();
            anc.LoadUnrenderedNamespaces(nsLocallyDeclared);
            anc.LoadRenderedNamespaces(nsListToRender);

            XmlNodeList childNodes = this.ChildNodes;
            foreach (XmlNode childNode in childNodes) {
                CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc);
            }

            anc.ExitElementContext();

            if (IsInNodeSet) {
                strBuilder.Append("</" + this.Name + ">");
            }
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            Hashtable nsLocallyDeclared = new Hashtable();
            SortedList nsListToRender = new SortedList(new NamespaceSortOrder());
            SortedList attrListToRender = new SortedList(new AttributeSortOrder());
            UTF8Encoding utf8 = new UTF8Encoding(false);
            byte[] rgbData;

            XmlAttributeCollection attrList = this.Attributes;
            if (attrList != null) {
                foreach (XmlAttribute attr in attrList) {
                    if (((CanonicalXmlAttribute) attr).IsInNodeSet || Utils.IsNamespaceNode(attr) || Utils.IsXmlNamespaceNode(attr)) {
                        if (Utils.IsNamespaceNode(attr)) {
                            anc.TrackNamespaceNode(attr, nsListToRender, nsLocallyDeclared);
                        }
                        else if (Utils.IsXmlNamespaceNode(attr)) {
                            anc.TrackXmlNamespaceNode(attr, nsListToRender, attrListToRender, nsLocallyDeclared);
                        }
                        else if(IsInNodeSet) {
                            attrListToRender.Add(attr, null);
                        }
                    }
                }
            }

            if (!Utils.IsCommittedNamespace(this, this.Prefix, this.NamespaceURI)) {
                string name = ((this.Prefix.Length > 0) ? "xmlns" + ":" + this.Prefix : "xmlns");
                XmlAttribute nsattrib = (XmlAttribute) this.OwnerDocument.CreateAttribute(name);
                nsattrib.Value = this.NamespaceURI;
                anc.TrackNamespaceNode(nsattrib, nsListToRender, nsLocallyDeclared);
            }

            if (IsInNodeSet) {
                anc.GetNamespacesToRender(this, attrListToRender, nsListToRender, nsLocallyDeclared);
                rgbData = utf8.GetBytes("<" + this.Name);
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
                foreach (object attr in nsListToRender.GetKeyList()) {
                    (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc);
                }
                foreach (object attr in attrListToRender.GetKeyList()) {
                    (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc);
                }
                rgbData = utf8.GetBytes(">");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }

            anc.EnterElementContext();
            anc.LoadUnrenderedNamespaces(nsLocallyDeclared);
            anc.LoadRenderedNamespaces(nsListToRender);

            XmlNodeList childNodes = this.ChildNodes;
            foreach (XmlNode childNode in childNodes) {
                CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc);
            }

            anc.ExitElementContext();

            if (IsInNodeSet) {
                rgbData = utf8.GetBytes("</" + this.Name + ">");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    // the class that provides node subset state and canonicalization function to XmlAttribute
    internal class CanonicalXmlAttribute : XmlAttribute, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(prefix, localName, namespaceURI, doc) {
            IsInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            strBuilder.Append(" " + this.Name + "=\"");
            strBuilder.Append(Utils.EscapeAttributeValue(this.Value));
            strBuilder.Append("\"");
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            UTF8Encoding utf8 = new UTF8Encoding(false);
            byte[] rgbData = utf8.GetBytes(" " + this.Name + "=\"");
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            rgbData = utf8.GetBytes(Utils.EscapeAttributeValue(this.Value));
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            rgbData = utf8.GetBytes("\"");
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
        }
    }

    // the class that provides node subset state and canonicalization function to XmlText
    internal class CanonicalXmlText : XmlText, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlText(string strData, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(strData, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet)
                strBuilder.Append(Utils.EscapeTextData(this.Value));
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet) {
                UTF8Encoding utf8 = new UTF8Encoding(false);
                byte[] rgbData = utf8.GetBytes(Utils.EscapeTextData(this.Value));
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    // the class that provides node subset state and canonicalization function to XmlWhitespace
    internal class CanonicalXmlWhitespace : XmlWhitespace, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(strData, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet && docPos == DocPosition.InRootElement)
                strBuilder.Append(Utils.EscapeWhitespaceData(this.Value));
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet && docPos == DocPosition.InRootElement) {
                UTF8Encoding utf8 = new UTF8Encoding(false);
                byte[] rgbData = utf8.GetBytes(Utils.EscapeWhitespaceData(this.Value));
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    // the class that provides node subset state and canonicalization function to XmlSignificantWhitespace
    internal class CanonicalXmlSignificantWhitespace : XmlSignificantWhitespace, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlSignificantWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(strData, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet && docPos == DocPosition.InRootElement)
                strBuilder.Append(Utils.EscapeWhitespaceData(this.Value));
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet && docPos == DocPosition.InRootElement) {
                UTF8Encoding utf8 = new UTF8Encoding(false);
                byte[] rgbData = utf8.GetBytes(Utils.EscapeWhitespaceData(this.Value));
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    // the class that provides node subset state and canonicalization function to XmlComment
    internal class CanonicalXmlComment : XmlComment, ICanonicalizableNode {
        private bool m_isInNodeSet;
        private bool m_includeComments;

        public CanonicalXmlComment(string comment, XmlDocument doc, bool defaultNodeSetInclusionState, bool includeComments)
            : base(comment, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
            m_includeComments = includeComments;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public bool IncludeComments {
            get { return m_includeComments; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (!IsInNodeSet || !IncludeComments)
                return;

            if (docPos == DocPosition.AfterRootElement)
                strBuilder.Append((char) 10);
            strBuilder.Append("<!--");
            strBuilder.Append(this.Value);
            strBuilder.Append("-->");
            if (docPos == DocPosition.BeforeRootElement)
                strBuilder.Append((char) 10);
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (!IsInNodeSet || !IncludeComments)
                return;

            UTF8Encoding utf8 = new UTF8Encoding(false);
            byte[] rgbData = utf8.GetBytes("(char) 10");
            if (docPos == DocPosition.AfterRootElement)
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            rgbData = utf8.GetBytes("<!--");
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            rgbData = utf8.GetBytes(this.Value);
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            rgbData = utf8.GetBytes("-->");
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            if (docPos == DocPosition.BeforeRootElement) {
                rgbData = utf8.GetBytes("(char) 10");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    // the class that provides node subset state and canonicalization function to XmlProcessingInstruction
    internal class CanonicalXmlProcessingInstruction : XmlProcessingInstruction, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlProcessingInstruction(string target, string data, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(target, data, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (!IsInNodeSet)
                return;

            if (docPos == DocPosition.AfterRootElement)
                strBuilder.Append((char) 10);
            strBuilder.Append("<?");
            strBuilder.Append(this.Name);
            if ((this.Value != null) && (this.Value.Length > 0))
                strBuilder.Append(" " + this.Value);
            strBuilder.Append("?>");
            if (docPos == DocPosition.BeforeRootElement)
                strBuilder.Append((char) 10);
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (!IsInNodeSet)
                return;

            UTF8Encoding utf8 = new UTF8Encoding(false);
            byte[] rgbData;
            if (docPos == DocPosition.AfterRootElement) {
                rgbData = utf8.GetBytes("(char) 10");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
            rgbData = utf8.GetBytes("<?");
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            rgbData = utf8.GetBytes((this.Name));
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            if ((this.Value != null) && (this.Value.Length > 0)) {
                rgbData = utf8.GetBytes(" " + this.Value);
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
            rgbData = utf8.GetBytes("?>");
            hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            if (docPos == DocPosition.BeforeRootElement) {
                rgbData = utf8.GetBytes("(char) 10");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    // the class that provides node subset state and canonicalization function to XmlEntityReference
    internal class CanonicalXmlEntityReference : XmlEntityReference, ICanonicalizableNode {
        private bool m_isInNodeSet;

        public CanonicalXmlEntityReference(string name, XmlDocument doc, bool defaultNodeSetInclusionState)
            : base(name, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet)
                CanonicalizationDispatcher.WriteGenericNode(this, strBuilder, docPos, anc);
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet)
                CanonicalizationDispatcher.WriteHashGenericNode(this, hash, docPos, anc);
        }
    }

    // the class that provides node subset state and canonicalization function to XmlCDataSection
    internal class CanonicalXmlCDataSection: XmlCDataSection, ICanonicalizableNode {
        private bool m_isInNodeSet;
        public CanonicalXmlCDataSection(string data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(data, doc) {
            m_isInNodeSet = defaultNodeSetInclusionState;
        }

        public bool IsInNodeSet {
            get { return m_isInNodeSet; }
            set { m_isInNodeSet = value; }
        }

        public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet)
                strBuilder.Append(Utils.EscapeCData(this.Data));
        }

        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) {
            if (IsInNodeSet) {
                UTF8Encoding utf8 = new UTF8Encoding(false);
                byte[] rgbData = utf8.GetBytes(Utils.EscapeCData(this.Data));
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
    }

    internal class CanonicalXmlNodeList : XmlNodeList, IList {
        private ArrayList m_nodeArray;

        internal CanonicalXmlNodeList() {
            m_nodeArray = new ArrayList();
        }

        public override XmlNode Item(int index) {
            return (XmlNode) m_nodeArray[index];
        }

        public override IEnumerator GetEnumerator() {
            return m_nodeArray.GetEnumerator();
        }

        public override int Count {
            get { return m_nodeArray.Count; }
        }

        // IList methods
        public int Add(Object value) {
            if (!(value is XmlNode))
                throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "node");
            return m_nodeArray.Add(value);
        }

        public void Clear() {
            m_nodeArray.Clear();
        }

        public bool Contains(Object value) {
            return m_nodeArray.Contains(value);
        }

        public int IndexOf(Object value) {
            return m_nodeArray.IndexOf(value);
        }

        public void Insert(int index, Object value) {
            if (!(value is XmlNode))
                throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value");
            m_nodeArray.Insert(index,value);
        }

        public void Remove(Object value) {
            m_nodeArray.Remove(value);
        }

        public void RemoveAt(int index) {
            m_nodeArray.RemoveAt(index);
        }

        public Boolean IsFixedSize {
            get { return m_nodeArray.IsFixedSize; }
        }

        public Boolean IsReadOnly {
            get { return m_nodeArray.IsReadOnly; }
        }

        Object IList.this[int index] {
            get { return m_nodeArray[index]; }
            set {
                if (!(value is XmlNode))
                    throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value");
                m_nodeArray[index] = value;
            }
        }

        public void CopyTo(Array array, int index) {
            m_nodeArray.CopyTo(array, index);
        }

        public Object SyncRoot {
            get { return m_nodeArray.SyncRoot; }
        }

        public bool IsSynchronized {
            get { return m_nodeArray.IsSynchronized; }
        }
    }

    // This class does lexicographic sorting by NamespaceURI first and then by LocalName.
    internal class AttributeSortOrder : IComparer {
        internal AttributeSortOrder() {}

        public int Compare(Object a, Object b) {
            XmlNode nodeA = a as XmlNode;
            XmlNode nodeB = b as XmlNode;
            if ((a == null) || (b == null))
                throw new ArgumentException();
            int namespaceCompare = String.CompareOrdinal(nodeA.NamespaceURI, nodeB.NamespaceURI);
            if (namespaceCompare != 0) return namespaceCompare;
            return String.CompareOrdinal(nodeA.LocalName, nodeB.LocalName);
        }
    }

    internal class NamespaceSortOrder : IComparer {
        internal NamespaceSortOrder() {}

        public int Compare(Object a, Object b) {
            XmlNode nodeA = a as XmlNode;
            XmlNode nodeB = b as XmlNode;
            if ((a == null) || (b == null))
                throw new ArgumentException();
            bool nodeAdefault = Utils.IsDefaultNamespaceNode(nodeA);
            bool nodeBdefault = Utils.IsDefaultNamespaceNode(nodeB);
            if (nodeAdefault && nodeBdefault) return 0;
            if (nodeAdefault) return -1;
            if (nodeBdefault) return 1;
            return String.CompareOrdinal(nodeA.LocalName, nodeB.LocalName);
        }
    }

    // the namespaces context corresponding to one XmlElement. the rendered list contains the namespace nodes that are actually
    // rendered to the canonicalized output. the unrendered list contains the namespace nodes that are in the node set and have
    // the XmlElement as the owner, but are not rendered.
    internal class NamespaceFrame {
        private Hashtable m_rendered = new Hashtable();
        private Hashtable m_unrendered = new Hashtable();

        internal NamespaceFrame() {}

        internal void AddRendered(XmlAttribute attr) {
            m_rendered.Add(Utils.GetNamespacePrefix(attr), attr);
        }

        internal XmlAttribute GetRendered(string nsPrefix) {
            return (XmlAttribute) m_rendered[nsPrefix];
        }

        internal void AddUnrendered(XmlAttribute attr) {
            m_unrendered.Add(Utils.GetNamespacePrefix(attr), attr);
        }

        internal XmlAttribute GetUnrendered(string nsPrefix) {
            return (XmlAttribute) m_unrendered[nsPrefix];
        }

        internal Hashtable GetUnrendered() {
            return m_unrendered;
        }
    }

    abstract internal class AncestralNamespaceContextManager {
        internal ArrayList m_ancestorStack = new ArrayList();

        internal NamespaceFrame GetScopeAt(int i) {
            return (NamespaceFrame) m_ancestorStack[i];
        }

        internal NamespaceFrame GetCurrentScope() {
            return GetScopeAt(m_ancestorStack.Count - 1);
        }

        protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) {
            XmlAttribute attr = null;
            depth = -1;
            for (int i = m_ancestorStack.Count - 1; i >= 0; i--) {
                if ((attr = GetScopeAt(i).GetRendered(nsPrefix)) != null) {
                    depth = i;
                    return attr;
                }
            }
            return null;
        }

        protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) {
            XmlAttribute attr = null;
            depth = -1;
            for (int i = m_ancestorStack.Count - 1; i >= 0; i--) {
                if ((attr = GetScopeAt(i).GetUnrendered(nsPrefix)) != null) {
                    depth = i;
                    return attr;
                }
            }
            return null;
        }

        internal void EnterElementContext() {
            m_ancestorStack.Add(new NamespaceFrame());
        }

        internal void ExitElementContext() {
            m_ancestorStack.RemoveAt(m_ancestorStack.Count - 1);
        }

        internal abstract void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared);
        internal abstract void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared);
        internal abstract void GetNamespacesToRender (XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared);

        internal void LoadUnrenderedNamespaces(Hashtable nsLocallyDeclared) {
            object[] attrs = new object[nsLocallyDeclared.Count];
            nsLocallyDeclared.Values.CopyTo(attrs, 0);
            foreach (object attr in attrs) {
                AddUnrendered((XmlAttribute) attr);
            }
        }

        internal void LoadRenderedNamespaces(SortedList nsRenderedList) {
            foreach (object attr in nsRenderedList.GetKeyList()) {
                AddRendered((XmlAttribute) attr);
            }
        }

        internal void AddRendered(XmlAttribute attr) {
            GetCurrentScope().AddRendered(attr);
        }

        internal void AddUnrendered(XmlAttribute attr) {
            GetCurrentScope().AddUnrendered(attr);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

?>

	<?php $this->BcBaser->link(''.$favorite['Favorite']['name'], $favorite['Favorite']['url'], array('title' => Router::url($favorite['Favorite']['url'], true))) ?>
	<?php echo $this->BcForm->input('Favorite.id.' . $favorite['Favorite']['id'], array('type' => 'hidden', 'value' => $favorite['Favorite']['id'], 'class' => 'favorite-id')) ?>
	<?php echo $this->BcForm->input('Favorite.name.' . $favorite['Favorite']['id'], array('type' => 'hidden', 'value' => $favorite['Favorite']['name'], 'class' => 'favorite-name')) ?>
	<?php echo $this->BcForm->input('Favorite.url.' . $favorite['Favorite']['id'], array('type' => 'hidden', 'value' => $favorite['Favorite']['url'], 'class' => 'favorite-url')) ?>


text:
class Program : IThemeable
{
    static int _I = 1;
    delegate void DoSomething();

    // <summary>
    // The quick brown fox jumps over the lazy dog
    // THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
    // </summary>
    static void Main(string[] args)
    {
        string normalStr = "The time now is approximately " + DateTime.Now;
        Uri Illegal1Uri = new Uri("http://packmyboxwith/jugs.html?q=five-dozen&t=liquor");
        Regex OperatorRegex = new Regex(@"\S#$", RegexOptions.IgnorePatternWhitespace);

        for (int O = 0; O < 123456789; O++)
        {
            _I += (O % 3) * ((O / 1) ^ 2) - 5;
            if (!OperatorRegex.IsMatch(Illegal1Uri.ToString()))
            {
                // no idea what this does!?
                Console.WriteLine(Illegal1Uri + normalStr);
            }
        }
    }
}
#endregion


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;

namespace Xamarin.Forms
{
	internal class ToolbarTracker
	{
		int _masterDetails;
		Page _target;

		public IEnumerable<Page> AdditionalTargets { get; set; }

		public bool HaveMasterDetail
		{
			get { return _masterDetails > 0; }
		}

		public bool SeparateMasterDetail { get; set; }

		public Page Target
		{
			get { return _target; }
			set
			{
				if (_target == value)
					return;

				UntrackTarget(_target);
				_target = value;

				if (_target != null)
					TrackTarget(_target);
				EmitCollectionChanged();
			}
		}

		public IEnumerable<ToolbarItem> ToolbarItems
		{
			get
			{
				if (Target == null)
					return Enumerable.Empty<ToolbarItem>();
				IEnumerable<ToolbarItem> items = GetCurrentToolbarItems(Target);
				if (AdditionalTargets != null)
					items = items.Concat(AdditionalTargets.SelectMany(t => t.ToolbarItems));

				return items.OrderBy(ti => ti.Priority);
			}
		}

		public event EventHandler CollectionChanged;

		void EmitCollectionChanged()
		{
			if (CollectionChanged != null)
				CollectionChanged(this, EventArgs.Empty);
		}

		IEnumerable<ToolbarItem> GetCurrentToolbarItems(Page page)
		{
			var result = new List<ToolbarItem>();
			result.AddRange(page.ToolbarItems);

			if (page is MasterDetailPage)
			{
				var masterDetail = (MasterDetailPage)page;
				if (SeparateMasterDetail)
				{
					if (masterDetail.IsPresented)
					{
						if (masterDetail.Master != null)
							result.AddRange(GetCurrentToolbarItems(masterDetail.Master));
					}
					else
					{
						if (masterDetail.Detail != null)
							result.AddRange(GetCurrentToolbarItems(masterDetail.Detail));
					}
				}
				else
				{
					if (masterDetail.Master != null)
						result.AddRange(GetCurrentToolbarItems(masterDetail.Master));
					if (masterDetail.Detail != null)
						result.AddRange(GetCurrentToolbarItems(masterDetail.Detail));
				}
			}
			else if (page is IPageContainer<Page>)
			{
				var container = (IPageContainer<Page>)page;
				if (container.CurrentPage != null)
					result.AddRange(GetCurrentToolbarItems(container.CurrentPage));
			}

			return result;
		}

		void OnChildAdded(object sender, ElementEventArgs eventArgs)
		{
			var page = eventArgs.Element as Page;
			if (page == null)
				return;

			RegisterChildPage(page);
		}

		void OnChildRemoved(object sender, ElementEventArgs eventArgs)
		{
			var page = eventArgs.Element as Page;
			if (page == null)
				return;

			UnregisterChildPage(page);
		}

		void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
		{
			EmitCollectionChanged();
		}

		void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
		{
			if (propertyChangedEventArgs.PropertyName == NavigationPage.CurrentPageProperty.PropertyName || propertyChangedEventArgs.PropertyName == MasterDetailPage.IsPresentedProperty.PropertyName ||
				propertyChangedEventArgs.PropertyName == "Detail" || propertyChangedEventArgs.PropertyName == "Master")
			{
				EmitCollectionChanged();
			}
		}

		void RegisterChildPage(Page page)
		{
			if (page is MasterDetailPage)
				_masterDetails++;

			((ObservableCollection<ToolbarItem>)page.ToolbarItems).CollectionChanged += OnCollectionChanged;
			page.PropertyChanged += OnPropertyChanged;
		}

		void TrackTarget(Page page)
		{
			if (page == null)
				return;

			if (page is MasterDetailPage)
				_masterDetails++;

			((ObservableCollection<ToolbarItem>)page.ToolbarItems).CollectionChanged += OnCollectionChanged;
			page.Descendants().OfType<Page>().ForEach(RegisterChildPage);

			page.DescendantAdded += OnChildAdded;
			page.DescendantRemoved += OnChildRemoved;
			page.PropertyChanged += OnPropertyChanged;
		}

		void UnregisterChildPage(Page page)
		{
			if (page is MasterDetailPage)
				_masterDetails--;

			((ObservableCollection<ToolbarItem>)page.ToolbarItems).CollectionChanged -= OnCollectionChanged;
			page.PropertyChanged -= OnPropertyChanged;
		}

		void UntrackTarget(Page page)
		{
			if (page == null)
				return;

			if (page is MasterDetailPage)
				_masterDetails--;

			((ObservableCollection<ToolbarItem>)page.ToolbarItems).CollectionChanged -= OnCollectionChanged;
			page.Descendants().OfType<Page>().ForEach(UnregisterChildPage);

			page.DescendantAdded -= OnChildAdded;
			page.DescendantRemoved -= OnChildRemoved;
			page.PropertyChanged -= OnPropertyChanged;
		}
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal sealed partial class LocalRewriter
    {
        public override BoundNode VisitBreakStatement(BoundBreakStatement node)
        {
            BoundStatement result = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors);
            if (this.Instrument && !node.WasCompilerGenerated)
            {
                result = _instrumenter.InstrumentBreakStatement(node, result);
            }

            return result;
        }
    }
}


text:
import React from "react"
import { graphql } from "gatsby"

export default ({ data }) => {
  if (!data?.allTest?.nodes) {
    throw new Error("Wrong data: " + JSON.stringify(data))
  }
  return <div>{JSON.stringify(data)}</div>
}

export const query = graphql`
  query(
    $pageNum: Int
    $pageNumPlus1000: Int
    $sort: TestSortInput
    $count: Boolean!
  ) {
    allTest(
      filter: { randomPage: { gt: $pageNum, lt: $pageNumPlus1000 } }
      sort: $sort
      limit: 100
    ) {
      nodes {
        nodeNum
        text
      }
      totalCount @include(if: $count)
    }
  }
`


text:
r"""
Modeling and inversion of temperature residuals measured in wells due to
temperature perturbations in the surface.

Perturbations can be of two kinds: **abrupt** or **linear**.

Forward modeling of these types of changes is done with functions:

* :func:`~fatiando.geothermal.climsig.abrupt`
* :func:`~fatiando.geothermal.climsig.linear`

Assumeing that the temperature perturbation was abrupt. The residual
temperature at a depth :math:`z_i` in the well at a time :math:`t` after the
perturbation is given by

.. math::

    T_i(z_i) = A \left[1 - \mathrm{erf}\left(
    \frac{z_i}{\sqrt{4\lambda t}}\right)\right]

where :math:`A` is the amplitude of the perturbation, :math:`\lambda` is the
thermal diffusivity of the medium, and :math:`\mathrm{erf}` is the error
function.

For the case of a linear change, the temperature is

.. math::

    T_i(z_i) = A \left[
    \left(1 + 2\frac{z_i^2}{4\lambda t}\right)
    \mathrm{erfc}\left(\frac{z_i}{\sqrt{4\lambda t}}\right) -
    \frac{2}{\sqrt{\pi}}\left(\frac{z_i}{\sqrt{4\lambda t}}\right)
    \mathrm{exp}\left(-\frac{z_i^2}{4\lambda t}\right)
    \right]

Given the temperature measured at different depths, we can **invert** for the
amplitude and age of the change. The available inversion solvers are:

* :class:`~fatiando.geothermal.climsig.SingleChange`: inverts for the
  parameters of a single temperature change. Can use both abrupt and linear
  models.

----

"""
from __future__ import division
import numpy
import scipy.special

from ..inversion.base import Misfit
from ..constants import THERMAL_DIFFUSIVITY_YEAR

def linear(amp, age, zp, diffus=THERMAL_DIFFUSIVITY_YEAR):
    """
    Calculate the residual temperature profile in depth due to a linear
    temperature perturbation.

    Parameters:

    * amp : float
        Amplitude of the perturbation (in C)
    * age : float
        Time since the perturbation occured (in years)
    * zp : array
        The depths of computation points along the well (in meters)
    * diffus : float
        Thermal diffusivity of the medium (in m^2/year)

    See the default values for the thermal diffusivity in
    :mod:`fatiando.constants`.

    Returns

    * temp : array
        The residual temperatures measured along the well

    """
    tmp = zp / numpy.sqrt(4. * diffus * age)
    res = amp * ((1. + 2 * tmp ** 2) * scipy.special.erfc(tmp)
                 - 2. / numpy.sqrt(numpy.pi) * tmp * numpy.exp(-tmp ** 2))
    return res

def abrupt(amp, age, zp, diffus=THERMAL_DIFFUSIVITY_YEAR):
    """
    Calculate the residual temperature profile in depth due to an abrupt
    temperature perturbation.

    Parameters:

    * amp : float
        Amplitude of the perturbation (in C)
    * age : float
        Time since the perturbation occured (in years)
    * zp : array
        Arry with the depths of computation points along the well (in meters)
    * diffus : float
        Thermal diffusivity of the medium (in m^2/year)

    See the default values for the thermal diffusivity in
    :mod:`fatiando.constants`.

    Returns

    * temp : array
        The residual temperatures measured along the well

    """
    return amp * (1. - scipy.special.erf(zp / numpy.sqrt(4. * diffus * age)))

class SingleChange(Misfit):

    r"""
    Invert the well temperature data for a single change in temperature.

    The parameters of the change are its amplitude and age.

    See the docstring of :mod:`fatiando.geothermal.climsig` for more
    information and examples.

    Parameters:

    * temp : array
        The temperature profile
    * zp : array
        Depths along the profile
    * mode : string
        The type of change: ``'abrupt'`` for an abrupt change, ``'linear'`` for
        a linear change.
    * diffus : float
        Thermal diffusivity of the medium (in m^2/year)

    .. note::

        The recommended solver for this inverse problem is the
        Levemberg-Marquardt method. Since this is a non-linear problem, set the
        desired method and initial solution using the
        :meth:`~fatiando.inversion.base.FitMixin.config` method.
        See the example bellow.

    Example with synthetic data:

        >>> import numpy
        >>> zp = numpy.arange(0, 100, 1)
        >>> # For an ABRUPT change
        >>> amp = 2
        >>> age = 100 # Uses years to avoid overflows
        >>> temp = abrupt(amp, age, zp)
        >>> # Run the inversion for the amplitude and time
        >>> # This is a non-linear problem, so use the Levemberg-Marquardt
        >>> # algorithm with an initial estimate
        >>> solver = SingleChange(temp, zp, mode='abrupt').config(
        ...             'levmarq', initial=[1, 1])
        >>> amp_, age_ = solver.fit().estimate_
        >>> print "amp: %.2f  age: %.2f" % (amp_, age_)
        amp: 2.00  age: 100.00
        >>> # For a LINEAR change
        >>> amp = 3.45
        >>> age = 52.5
        >>> temp = linear(amp, age, zp)
        >>> solver = SingleChange(temp, zp, mode='linear').config(
        ...             'levmarq', initial=[1, 1])
        >>> amp_, age_ = solver.fit().estimate_
        >>> print "amp: %.2f  age: %.2f" % (amp_, age_)
        amp: 3.45  age: 52.50

    Notes:

    For **abrupt** changes, derivatives with respect to the amplitude and age
    are calculated using the formula

    .. math::

        \frac{\partial T_i}{\partial A} = 1 - \mathrm{erf}\left(
        \frac{z_i}{\sqrt{4\lambda t}}\right)

    and

    .. math::

        \frac{\partial T_i}{\partial t} = \frac{A}{t\sqrt{\pi}}
        \left(\frac{z_i}{\sqrt{4\lambda t}}\right)
        \exp\left[-\left(\frac{z_i}{\sqrt{4\lambda t}}\right)^2\right]

    respectively.

    For **linear** changes, derivatives with respect to the age are calculated
    using a 2-point finite difference approximation. Derivatives with respect
    to amplitude are calculate using the formula

    .. math::

        \frac{\partial T_i}{\partial A} =
        \left(1 + 2\frac{z_i^2}{4\lambda t}\right)
        \mathrm{erfc}\left(\frac{z_i}{\sqrt{4\lambda t}}\right) -
        \frac{2}{\sqrt{\pi}}\left(\frac{z_i}{\sqrt{4\lambda t}}\right)
        \mathrm{exp}\left(-\frac{z_i^2}{4\lambda t}\right)

    """

    def __init__(self, temp, zp, mode, diffus=THERMAL_DIFFUSIVITY_YEAR):
        if len(temp) != len(zp):
            raise ValueError("temp and zp must be of same length")
        if mode not in ['abrupt', 'linear']:
            raise ValueError("Invalid mode: %s. Must be 'abrupt' or 'linear'"
                             % (mode))
        super(SingleChange, self).__init__(
            data=temp,
            positional=dict(zp=zp),
            model=dict(diffus=float(diffus), mode=mode),
            nparams=2, islinear=False)

    def _get_predicted(self, p):
        amp, age = p
        zp = self.positional['zp']
        diffus = self.model['diffus']
        if self.model['mode'] == 'abrupt':
            return abrupt(amp, age, zp, diffus)
        if self.model['mode'] == 'linear':
            return linear(amp, age, zp, diffus)

    def _get_jacobian(self, p):
        amp, age = p
        zp = self.positional['zp']
        diffus = self.model['diffus']
        mode = self.model['mode']
        if mode == 'abrupt':
            tmp = zp / numpy.sqrt(4. * diffus * age)
            jac = numpy.transpose([
                abrupt(1., age, zp, diffus),
                (amp * tmp * numpy.exp(-(tmp ** 2)) /
                 (numpy.sqrt(numpy.pi) * age))])
        if mode == 'linear':
            delta = 0.5
            at_p = linear(amp, age, zp, diffus)
            jac = numpy.transpose([
                linear(1., age, zp, diffus),
                (linear(amp, age + delta, zp, diffus) -
                 linear(amp, age - delta, zp, diffus)) / (2 * delta)])
        return jac


text:
import { observable } from 'mobx'

class DomStore {
  @observable data = {};
  @observable params = {};

  /**
  * Update DomStore function.
  *
  * @param {string} name
  * @param {Object} block
  * @param {*} params
  *
  * @return {Object} block
  */
  update = ({name, block}, params) => {
    this.data[name] = block;

    if (params) {
      this.params[name] = params;
    }

    return block;
  }
}

export default new DomStore;


text:
var clone = require('clone');

function SessionStore(options) {
  options = options || {};
  this._key = options.key || 'state';
}

SessionStore.prototype.all = function(req, cb) {
  var key = this._key;
  if (!req.session || !req.session[key]) {
    return cb();
  }

  var arr = []
    , handles = Object.keys(req.session[key])
    , state, h, i, len;
  for (i = 0, len = handles.length; i < len; ++i) {
    h = handles[i];
    state = clone(req.session[key][h]);
    if (typeof state.expires === 'string') {
      // convert expires to a Date object
      state.expires = new Date(state.expires);
    }
    state.handle = h;
    arr.push(state);
  }

  return cb(null, arr);
}

SessionStore.prototype.get = function(req, h, cb) {
  var key = this._key;
  if (!req.session || !req.session[key] || !req.session[key][h]) {
    return cb();
  }

  var state = clone(req.session[key][h]);
  if (typeof state.expires === 'string') {
    // convert expires to a Date object
    state.expires = new Date(state.expires);
  }
  return cb(null, state);
}

SessionStore.prototype.set = function(req, h, state, cb) {
  var key = this._key;
  req.session[key] = req.session[key] || {};
  req.session[key][h] = clone(state);
  return cb(null);
}

SessionStore.prototype.destroy = function(req, h, cb) {
  var key = this._key;
  if (!req.session || !req.session[key] || !req.session[key][h]) {
    return cb();
  }

  delete req.session[key][h];
  if (Object.keys(req.session[key]).length == 0) {
    delete req.session[key];
  }
  return cb();
}

module.exports = SessionStore;


text:
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
//     Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors.
//     Contributors can be discovered using the 'git log' command.
//     All rights reserved.
// </copyright>
// <license>
//     The software is licensed under the Apache 2.0 License (the "License")
//     You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------

namespace ClrPlus.Windows.Api.Structures {
    using System;
    using System.Runtime.InteropServices;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public class FocusInputRecord {
        public Int16 EventType;
        public bool bSetFocus;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
        public String wszTitle = new String(' ', 256);
    }
}


text:
package hudson.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import com.thoughtworks.xstream.mapper.Mapper;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import static java.util.logging.Level.FINE;

import java.util.logging.Logger;

/**
 * {@link CollectionConverter} that ignores {@link CannotResolveClassException}.
 *
 * <p> This allows Hudson to load XML files that contain non-existent classes
 * (the expected scenario is that those classes belong to plugins that were
 * unloaded.)
 *
 * @author Kohsuke Kawaguchi
 */
public class RobustCollectionConverter extends CollectionConverter {

    private final SerializableConverter sc;

    public RobustCollectionConverter(XStream xs) {
        this(xs.getMapper(), xs.getReflectionProvider());
    }

    public RobustCollectionConverter(Mapper mapper, ReflectionProvider reflectionProvider) {
        super(mapper);
        sc = new SerializableConverter(mapper, reflectionProvider);
    }

    @Override
    public boolean canConvert(Class type) {
        return super.canConvert(type) || type == CopyOnWriteArrayList.class || type == CopyOnWriteArraySet.class;
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        // CopyOnWriteArrayList used to serialize as custom serialization,
        // so read it in a compatible fashion.
        String s = reader.getAttribute("serialization");
        if (s != null && s.equals("custom")) {
            return sc.unmarshal(reader, context);
        } else {
            return super.unmarshal(reader, context);
        }
    }

    @Override
    protected void populateCollection(HierarchicalStreamReader reader, UnmarshallingContext context, Collection collection) {
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            try {
                Object item = readItem(reader, context, collection);
                collection.add(item);
            } catch (CannotResolveClassException e) {
                LOGGER.log(FINE, "Failed to resolve class " + e.getMessage());
                RobustReflectionConverter.addErrorInContext(context, e);
            } catch (LinkageError e) {
                LOGGER.log(FINE, "Failed to resolve class " + e.getMessage());
                RobustReflectionConverter.addErrorInContext(context, e);
            }
            reader.moveUp();
        }
    }
    private static final Logger LOGGER = Logger.getLogger(RobustCollectionConverter.class.getName());
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=500" />
	<meta name="keywords" content="ScrollMagic, example, scrolling, attaching, scrollbar, tween, tweenmax" />
	<meta name="author"	content="Jan Paepke (www.janpaepke.de)" />
	<title>Animating with GSAP - Examples - ScrollMagic</title>

	<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,400italic|Josefin+Slab:400,700italic' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="../../css/normalize.css" type="text/css">
	<link rel="stylesheet" href="../../css/style.css" type="text/css">
	<link rel="stylesheet" href="../../css/examples.css" type="text/css">
	<link rel="shortcut icon" href="../../img/favicon.ico" type="image/x-icon">

Simple Tweening

Two examples of basic animation.

When no duration is defined for the scene, the tween will simply start playing when the scroll reaches the trigger position.

If the scene has a duration the progress of the tween will directly correspond to the scroll position.

							This example uses the shorthand version of Scene.setTween() to add TweenMax.to() animations.

							To see how to build more advanced tweens check out the Advanced Tweening Example.

						view source

You wouldn't like me, when I'm angry!

						view source

Smurf me!

						view source


text:
fw_depends mongodb java maven

mvn -P mongo clean package

java -jar target/hello-world-0.0.1-SNAPSHOT.jar server hello-world-mongo.yml &


text:
var PinView = Backbone.View.extend({

  events: {
    'click': 'changeState'
  },

  // renderin a pin means creating an SVG rectangle with a color
  render: function() {
    var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute('x', 14);
    rect.setAttribute('y', 14);
    rect.setAttribute('width',  30);
    rect.setAttribute('height', 40);
    rect.setAttribute('style', 'fill:' + this.model.getColor() + ';stroke:pink');
    this.$el.html(rect);
  },

  changeState: function(e) {
    this.model.toggleState();
  },

  initialize: function() {
    this.listenTo(this.model, 'change:state', this.render);
  }

});

// This view shows that status of a pin
var StatusView = Backbone.View.extend({

  render: function() {
    this.$el.html('LED is ' + this.model.getStatus());
  },

  initialize: function() {
    this.listenTo(this.model, 'change:state', this.render);
  }

});

// The model "remembers" the state of the pin
var LEDModel = Backbone.Model.extend({
  defaults: {
    state: 0
  },

  getColor: function() {
    return (this.get('state') ? 'red' : 'black');
  },

  toggleState: function() {
    var current = this.get('state');
    this.set('state', !current);
  },

  getStatus: function() {
    return (this.get('state') ? 'ON' : 'OFF');
  }

});
var ledModel = new LEDModel();

document.addEventListener('DOMContentLoaded', function () {

  var led = new PinView({el: '#schematic', model: ledModel });
  led.render();

  var status = new StatusView({el: '.status', model: ledModel });
  status.render();

});


text:
using System;
using System.Runtime.CompilerServices;

[assembly: ScriptAssembly("test")]

namespace ExpressionTests {

    public class App {

        private const string ScriptTemplate = "alert({0} + {1})";

        public void Test(int arg) {
            Script.Literal("arg + 1");

            int i = (int)Script.Literal("arg + 1");
            int j = (int)Script.Literal("{0} + 1", arg);
            int k = (int)Script.Literal("{0} + {1}", arg, 1);

            int a = 10;

            Script.Literal(ScriptTemplate, a, a);
        }
    }
}


text:
package com.orientechnologies.orient.core.sql;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.ORecordLazyList;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.intent.OIntentMassiveInsert;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.ODatabaseSecurityResources;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;

/**
 * SQL CREATE LINK command: Transform a JOIN relationship to a physical LINK
 *
 * @author Luca Garulli
 *
 */
@SuppressWarnings("unchecked")
public class OCommandExecutorSQLCreateLink extends OCommandExecutorSQLAbstract {
  public static final String  KEYWORD_CREATE = "CREATE";
  public static final String  KEYWORD_LINK   = "LINK";
  private static final String KEYWORD_FROM   = "FROM";
  private static final String KEYWORD_TO     = "TO";
  private static final String KEYWORD_TYPE   = "TYPE";

  private String              destClassName;
  private String              destField;
  private String              sourceClassName;
  private String              sourceField;
  private String              linkName;
  private OType               linkType;
  private boolean             inverse        = false;

  public OCommandExecutorSQLCreateLink parse(final OCommandRequest iRequest) {
    getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);

    init(((OCommandRequestText) iRequest).getText());

    StringBuilder word = new StringBuilder();

    int oldPos = 0;
    int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
    if (pos == -1 || !word.toString().equals(KEYWORD_CREATE))
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_CREATE + " not found. Use " + getSyntax(), parserText, oldPos);

    oldPos = pos;
    pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
    if (pos == -1 || !word.toString().equals(KEYWORD_LINK))
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_LINK + " not found. Use " + getSyntax(), parserText, oldPos);

    oldPos = pos;
    pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false);
    if (pos == -1)
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_FROM + " not found. Use " + getSyntax(), parserText, oldPos);

    if (!word.toString().equalsIgnoreCase(KEYWORD_FROM)) {
      // GET THE LINK NAME
      linkName = word.toString();

      if (OStringSerializerHelper.contains(linkName, ' '))
        throw new OCommandSQLParsingException("Link name '" + linkName + "' contains not valid characters", parserText, oldPos);

      oldPos = pos;
      pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
    }

    if (word.toString().equalsIgnoreCase(KEYWORD_TYPE)) {
      oldPos = pos;
      pos = nextWord(parserText, parserTextUpperCase, pos, word, true);

      if (pos == -1)
        throw new OCommandSQLParsingException("Link type missed. Use " + getSyntax(), parserText, oldPos);

      linkType = OType.valueOf(word.toString().toUpperCase(Locale.ENGLISH));

      oldPos = pos;
      pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
    }

    if (pos == -1 || !word.toString().equals(KEYWORD_FROM))
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_FROM + " not found. Use " + getSyntax(), parserText, oldPos);

    pos = nextWord(parserText, parserTextUpperCase, pos, word, false);
    if (pos == -1)
      throw new OCommandSQLParsingException("Expected <class>.<property>. Use " + getSyntax(), parserText, pos);

    String[] parts = word.toString().split("\\.");
    if (parts.length != 2)
      throw new OCommandSQLParsingException("Expected <class>.<property>. Use " + getSyntax(), parserText, pos);

    sourceClassName = parts[0];
    if (sourceClassName == null)
      throw new OCommandSQLParsingException("Class not found", parserText, pos);
    sourceField = parts[1];

    pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
    if (pos == -1 || !word.toString().equals(KEYWORD_TO))
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_TO + " not found. Use " + getSyntax(), parserText, oldPos);

    pos = nextWord(parserText, parserTextUpperCase, pos, word, false);
    if (pos == -1)
      throw new OCommandSQLParsingException("Expected <class>.<property>. Use " + getSyntax(), parserText, pos);

    parts = word.toString().split("\\.");
    if (parts.length != 2)
      throw new OCommandSQLParsingException("Expected <class>.<property>. Use " + getSyntax(), parserText, pos);

    destClassName = parts[0];
    if (destClassName == null)
      throw new OCommandSQLParsingException("Class not found", parserText, pos);
    destField = parts[1];

    pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
    if (pos == -1)
      return this;

    if (!word.toString().equalsIgnoreCase("INVERSE"))
      throw new OCommandSQLParsingException("Missed 'INVERSE'. Use " + getSyntax(), parserText, pos);

    inverse = true;

    return this;
  }

  /**
   * Execute the CREATE LINK.
   */
  public Object execute(final Map<Object, Object> iArgs) {
    if (destField == null)
      throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");

    final ODatabaseRecord database = getDatabase();
    if (!(database.getDatabaseOwner() instanceof ODatabaseDocumentTx))
      throw new OCommandSQLParsingException("This command supports only the database type ODatabaseDocumentTx and type '"
          + database.getClass() + "' was found");

    final ODatabaseDocumentTx db = (ODatabaseDocumentTx) database.getDatabaseOwner();

    final OClass sourceClass = database.getMetadata().getSchema().getClass(sourceClassName);
    if (sourceClass == null)
      throw new OCommandExecutionException("Source class '" + sourceClassName + "' not found");

    final OClass destClass = database.getMetadata().getSchema().getClass(destClassName);
    if (destClass == null)
      throw new OCommandExecutionException("Destination class '" + destClassName + "' not found");

    Object value;
    String cmd = "select from " + destClassName + " where " + destField + " = ";
    List<ODocument> result;
    ODocument target;
    Object oldValue;
    long total = 0;

    if (linkName == null)
      // NO LINK NAME EXPRESSED: OVERWRITE THE SOURCE FIELD
      linkName = sourceField;

    boolean multipleRelationship;
    if (linkType != null)
      // DETERMINE BASED ON FORCED TYPE
      multipleRelationship = linkType == OType.LINKSET || linkType == OType.LINKLIST;
    else
      multipleRelationship = false;

    long totRecords = db.countClass(sourceClass.getName());
    long currRecord = 0;

    if (progressListener != null)
      progressListener.onBegin(this, totRecords);

    database.declareIntent(new OIntentMassiveInsert());
    try {
      // BROWSE ALL THE RECORDS OF THE SOURCE CLASS
      for (ODocument doc : db.browseClass(sourceClass.getName())) {
        doc.unpin();

        value = doc.field(sourceField);

        if (value != null) {
          if (value instanceof ODocument || value instanceof ORID) {
            // ALREADY CONVERTED
          } else if (value instanceof Collection<?>) {
            // TODO
          } else {
            // SEARCH THE DESTINATION RECORD
            target = null;

            if (value instanceof String)
              if (((String) value).length() == 0)
                value = null;
              else
                value = "'" + value + "'";

            result = database.<OCommandRequest> command(new OSQLSynchQuery<ODocument>(cmd + value)).execute();

            if (result == null || result.size() == 0)
              value = null;
            else if (result.size() > 1)
              throw new OCommandExecutionException("Cannot create link because multiple records was found in class '"
                  + destClass.getName() + "' with value " + value + " in field '" + destField + "'");
            else {
              target = result.get(0);
              value = target;
            }

            if (target != null && inverse) {
              // INVERSE RELATIONSHIP
              oldValue = target.field(linkName);

              if (oldValue != null) {
                if (!multipleRelationship)
                  multipleRelationship = true;

                Collection<ODocument> coll;
                if (oldValue instanceof Collection) {
                  // ADD IT IN THE EXISTENT COLLECTION
                  coll = (Collection<ODocument>) oldValue;
                  target.setDirty();
                } else {
                  // CREATE A NEW COLLECTION FOR BOTH
                  coll = new ArrayList<ODocument>(2);
                  target.field(linkName, coll);
                  coll.add((ODocument) oldValue);
                }
                coll.add(doc);
              } else {
                if (linkType != null)
                  if (linkType == OType.LINKSET) {
                    value = new OMVRBTreeRIDSet(target);
                    ((OMVRBTreeRIDSet) value).add(doc);
                  } else if (linkType == OType.LINKLIST) {
                    value = new ORecordLazyList(target);
                    ((ORecordLazyList) value).add(doc);
                  } else
                    // IGNORE THE TYPE, SET IT AS LINK
                    value = doc;
                else
                  value = doc;

                target.field(linkName, value);
              }
              target.save();

            } else {
              // SET THE REFERENCE
              doc.field(linkName, value);
              doc.save();
            }

            total++;
          }
        }

        if (progressListener != null)
          progressListener.onProgress(this, currRecord, currRecord * 100f / totRecords);
      }

      if (total > 0) {
        if (inverse) {
          // REMOVE THE OLD PROPERTY IF ANY
          OProperty prop = destClass.getProperty(linkName);
          if (prop != null)
            destClass.dropProperty(linkName);

          if (linkType == null)
            linkType = multipleRelationship ? OType.LINKSET : OType.LINK;

          // CREATE THE PROPERTY
          destClass.createProperty(linkName, linkType, sourceClass);

        } else {

          // REMOVE THE OLD PROPERTY IF ANY
          OProperty prop = sourceClass.getProperty(linkName);
          if (prop != null)
            sourceClass.dropProperty(linkName);

          // CREATE THE PROPERTY
          sourceClass.createProperty(linkName, OType.LINK, destClass);
        }
      }

      if (progressListener != null)
        progressListener.onCompletition(this, true);

    } catch (Exception e) {
      if (progressListener != null)
        progressListener.onCompletition(this, false);

      throw new OCommandExecutionException("Error on creation of links", e);

    } finally {
      database.declareIntent(null);
    }

    return total;
  }

  @Override
  public String getSyntax() {
    return "CREATE LINK <link-name> [TYPE <link-type>] FROM <source-class>.<source-property> TO <destination-class>.<destination-property> [INVERSE]";
  }
}


text:
package dotty.tools.dotc
package transform

import TreeTransforms._
import core.DenotTransformers._
import core.Symbols._
import core.Contexts._
import core.Types._
import core.Flags._
import core.Decorators._
import core.StdNames.nme
import ast.Trees._
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Constants._

/** This phase rewrites idempotent expressions with constant types to Literals.
 *  The constant types are eliminated by erasure, so we need to keep
 *  the info about constantness in the trees.
 *
 *  The phase also makes sure that the constant of a literal is the same as the constant
 *  in the type of the literal.
 */
class Literalize extends MiniPhaseTransform { thisTransform =>
  import ast.tpd._

  override def phaseName: String = "literalize"

  /** Note: Demanding idempotency instead of purity is strictly speaking too loose.
   *  Example
   *
   *    object O { final val x = 42; println("43") }
   *    O.x
   *
   *  Strictly speaking we can't replace `O.x` with `42`.  But this would make
   *  most expressions non-constant. Maybe we can change the spec to accept this
   *  kind of eliding behavior. Or else enforce true purity in the compiler.
   *  The choice will be affected by what we will do with `inline` and with
   *  Singleton type bounds (see SIP 23). Presumably
   *
   *     object O1 { val x: Singleton = 42; println("43") }
   *     object O2 { inline val x = 42; println("43") }
   *
   *  should behave differently.
   *
   *     O1.x  should have the same effect as   { println("43"; 42 }
   *
   *  whereas
   *
   *     O2.x = 42
   *
   *  Revisit this issue once we have implemented `inline`. Then we can demand
   *  purity of the prefix unless the selection goes to an inline val.
   */
  def literalize(tree: Tree)(implicit ctx: Context): Tree = tree.tpe match {
    case ConstantType(value) if isIdempotentExpr(tree) => Literal(value)
    case _ => tree
  }

  override def transformIdent(tree: Ident)(implicit ctx: Context, info: TransformerInfo): Tree =
    literalize(tree)

  override def transformSelect(tree: Select)(implicit ctx: Context, info: TransformerInfo): Tree =
    literalize(tree)

  override def transformApply(tree: Apply)(implicit ctx: Context, info: TransformerInfo): Tree =
    literalize(tree)

  override def transformTypeApply(tree: TypeApply)(implicit ctx: Context, info: TransformerInfo): Tree =
    literalize(tree)

  override def transformLiteral(tree: Literal)(implicit ctx: Context, info: TransformerInfo): Tree = tree.tpe match {
    case ConstantType(const) if tree.const.value != const.value || (tree.const.tag != const.tag) => Literal(const)
    case _ => tree
  }

  /** Check that all literals have types match underlying constants
    */
  override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = {
    tree match {
      case Literal(c @ Constant(treeValue)) =>
        tree.tpe match {
          case ConstantType(c2 @ Constant(typeValue)) =>
            assert(treeValue == typeValue && c2.tag == c.tag,
              i"Type of Literal $tree is inconsistent with underlying constant")
          case tpe =>
            assert(c.tpe =:= tpe, i"Type of Literal $tree is inconsistent with underlying constant type ${c.tpe}")
        }
      case _ =>
    }
  }
}


text:
/* @flow strict-local */
import React, { PureComponent } from 'react';
import { Switch } from 'react-native';
import { BRAND_COLOR } from '../styles';

type Props = $ReadOnly<{|
  disabled: boolean,
  value: boolean,
  onValueChange: (arg: boolean) => void,
|}>;

/**
 * An on/off component, provides consistent styling of the
 * built-in Switch component.
 *
 * @prop [disabled] - If set the component is not switchable and visually looks disabled.
 * @prop value - value of the switch.
 * @prop onValueChange - Event called on switch.
 */
export default class ZulipSwitch extends PureComponent<Props> {
  static defaultProps = {
    disabled: false,
  };

  render() {
    const { disabled, onValueChange, value } = this.props;

    return (
      <Switch
        value={value}
        trackColor={{
          false: 'hsl(0, 0%, 86%)',
          true: BRAND_COLOR,
        }}
        onValueChange={onValueChange}
        disabled={disabled}
      />
    );
  }
}


text:
require 'minitest_helper'

class TestHyperloop < Minitest::Test
  def test_that_it_has_a_version_number
    refute_nil ::Hyperloop::VERSION
  end

  def test_it_does_something_useful
    assert false
  end

  def test_extension_methods_are_present
    ["test"].each do |method_name|
        assert Hyperloop.respond_to?(method_name)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Humour on Readers' Advisory blog</title>
    <link>https://StackSquirrel.github.io/tags/humour/</link>
    <description>Recent content in Humour on Readers' Advisory blog</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 14 Aug 2017 00:00:00 +0000</lastBuildDate>

	<atom:link href="https://StackSquirrel.github.io/tags/humour/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Flavia de Luce books by Alan Bradley</title>
      <link>https://StackSquirrel.github.io/posts/flavia-de-luce-books-by-alan-bradley/</link>
      <pubDate>Mon, 14 Aug 2017 00:00:00 +0000</pubDate>

      <guid>https://StackSquirrel.github.io/posts/flavia-de-luce-books-by-alan-bradley/</guid>
      <description>About the book Author: Bradley, Alan C., 1938-
Title: The sweetness at the bottom of the pie.
Publication: New York : Bantam, 2009. ISBN 9780553840766.
DAISY audio format narrated by Annabel Bates. CELA library call number DA38056. 292 pages in the paper edition; 11 hrs., 9 mins. as a recorded book.
About the story If you have never read the Flavia de Luce (that&rsquo;s Flavia with an eh) books, you are in for a wildly hilarious treat.</description>
    </item>

    <item>
      <title>Let's explore diabetes with owls by David Sedaris</title>
      <link>https://StackSquirrel.github.io/posts/lets-explore-diabetes-with-owls-by-david-sedaris/</link>
      <pubDate>Sat, 29 Jul 2017 00:00:00 +0000</pubDate>

      <guid>https://StackSquirrel.github.io/posts/lets-explore-diabetes-with-owls-by-david-sedaris/</guid>
      <description>About the book Author: Sedaris, David.
Title: Let&rsquo;s explore diabetes with owls: Essays, etc.
Publication: New York, NY : Little, Brown and Company, 2013. ISBN 9780316154697.
DAISY audio format narrated by David Sedaris. CELA library call number DA53190. 275 pages in the paper edition; 6 hrs., 26 mins. as a recorded book.
About the story This is a series of essays, read by the author and recorded at various times, some recorded live, some in studio.</description>
    </item>

    <item>
      <title>Peace pipe dreams by Darrell Dennis</title>
      <link>https://StackSquirrel.github.io/posts/peace-pipe-dreams-by-darrell-dennis/</link>
      <pubDate>Wed, 26 Jul 2017 00:00:00 +0000</pubDate>

      <guid>https://StackSquirrel.github.io/posts/peace-pipe-dreams-by-darrell-dennis/</guid>
      <description>About the book Author: Dennis, Darrell (Darrell Michael).
Title: Peace pipe dreams : The truth about lies about Indians.
Publication: Madeira Park, British Columbia : Douglas &amp; McIntyre, 2014. ISBN 9781771000406.
DAISY audio format narrated by Bruce McLeod. CELA library call number DA50486. 240 pages in the paper edition; 9 hrs., 8 mins. as a recorded book.
About the story Everyone should read this book.
Winner of First Nation Communities Read 2015-2016, Shushwap writer Darrel Dennis starts out with some &ldquo;myth-busting&rdquo;, humourously debunking some popularly-held mainstream stereotypes about indigenous people in Canada: drunken Indians, lazy Indians, no taxes, free schooling and housing, that they get a free ride&hellip; there are so very many.</description>
    </item>

    <item>
      <title>The Penguin anthology of Canadian humour by Will Ferguson</title>
      <link>https://StackSquirrel.github.io/posts/the-penguin-anthology-of-canadian-humour/</link>
      <pubDate>Mon, 09 Jan 2017 00:00:00 +0000</pubDate>

      <guid>https://StackSquirrel.github.io/posts/the-penguin-anthology-of-canadian-humour/</guid>
      <description>About the book Author: Ferguson, Will
Title: The Penguin anthology of Canadian humour
Publication: Toronto : Viking Canada, 2006. ISBN 9780670064434.
DAISY audio format narrated by Barbara Lord and Chris Caughey. CELA library call number DA28565. 496 pages in the print edition; 16 hrs., 45 mins. as a recorded book.
About the story This anthology, compiled by Will Ferguson and originally published in 2006, is a veritable Who's Who of Canadian humour.</description>
    </item>

    <item>
      <title>The Woefield Farm books by Susan Juby</title>
      <link>https://StackSquirrel.github.io/posts/the-woefield-farm-books-by-susan-juby/</link>
      <pubDate>Wed, 04 Jan 2017 00:00:00 +0000</pubDate>

      <guid>https://StackSquirrel.github.io/posts/the-woefield-farm-books-by-susan-juby/</guid>
      <description>About the book Author: Juby, Susan (1969-)
Title: The Woefield poultry collective. Publication: New York : HarperCollins Canada, 2011. ISBN 9781554687442. DAISY audio format narrated by Jennifer Coffey. CELA library call number DA39138. 306 pages; 9hrs., 13mins. as a recorded book.
Title: Republic of Dirt: a return to Woefield Farm. Publication: Toronto : HarperAvenue 2015. ISBN 9781443423960. DAISY audio format narrated by Taina Makinen and Henry LaCroix. CELA library call number DA52124.</description>
    </item>

    <item>
      <title>Thomas Cathcart's greek philosopher joke books</title>
      <link>https://StackSquirrel.github.io/posts/thomas-cathcarts-greek-philosopher-joke-books/</link>
      <pubDate>Wed, 02 Nov 2016 00:00:00 +0000</pubDate>

      <guid>https://StackSquirrel.github.io/posts/thomas-cathcarts-greek-philosopher-joke-books/</guid>
      <description>About the book Author: Cathcart, Thomas (1940- ) and Daniel Klein.
Title: Plato and a platypus walk into a bar&hellip;: Understanding philosophy through jokes. (2006)
Publication: New York : Abrams Image, 2006. ISBN 9781456102821.
DAISY audio format narrated by Johnny Heller. CELA library call number DC46041. 224 pages in the paperback edition; 4 hrs., 9 min. as a recorded book.
Title: Aristotle and an aardvark go to Washington: Understanding political doublespeak through philosophy and jokes.</description>
    </item>

  </channel>
</rss>


text:
<?php
namespace Mevdschee\PhpCrudApi\Tests;

class SqlServerTest extends Tests
{
    /**
     * Gets the name of the database engine
     *
     * @return string Name of the database engine
     */
    public function getEngineName()
    {
        return 'SQLServer';
    }

    /**
     * Connects to the Database
     *
     * @return object Database connection
     */
    public function connect($config)
    {
        $connectionInfo = array(
            'UID' => $config['username'],
            'PWD' => $config['password'],
            'Database' => $config['database'],
            'CharacterSet' => 'UTF-8',
        );

        $db = sqlsrv_connect($config['hostname'], $connectionInfo);

        if (!$db) {
            die("Connect failed: ".print_r(sqlsrv_errors(), true));
        }

        return $db;
    }

    /**
     * Disconnects from the Database
     *
     * @return boolean Success
     */
    public function disconnect($db)
    {
        return sqlsrv_close($db);
    }

    /**
     * Checks the version of the Database
     *
     * @return void
     */
    public function checkVersion($db)
    {
        $major = 11;
        $minor = 0;
        $build = 3000;
        $version = sqlsrv_server_info($db);
        $v = explode('.', $version['SQLServerVersion']);
        if ($v[0]<$major || ($v[0]==$major && $v[1]<$minor) || ($v[0]==$major && $v[1]==$minor && $v[2]<$build)) {
            die("Detected SQL Server $v[0].$v[1].$v[2], but only $major.$minor.$build and up are supported\n");
        }
    }

    /**
     * Gets the capabilities of the Database
     *
     * @return int Capabilites
     */
    public function getCapabilities($db)
    {
        $capabilities = 0;
        $capabilities |= self::JSON;
        $capabilities |= self::GIS;
        return $capabilities;
    }

    /**
     * Seeds the database for this connection
     *
     * @return void
     */
    public function seedDatabase($db, $capabilities)
    {
        $fixture = __DIR__.'/data/blog_sqlserver.sql';
        $contents = file_get_contents($fixture);

        $queries = preg_split('/\n\s*GO\s*\n/', $contents);
        array_pop($queries);

        foreach ($queries as $i=>$query) {
            if (!sqlsrv_query($db, $query)) {
                $i++;
                die("Loading '$fixture' failed on statemement #$i with error:\n".print_r(sqlsrv_errors(), true)."\n");
            }
        }
    }
}


text:
package models.Skill.SneakSkill;
import models.Entity.*;

public class Creep extends SneakSkill {

    public Creep() {
        super("Creep", 5.0);
    }

    public void activate(Entity entity) {
        if (entity != null) {

        }
    }

    public void createSignal(models.Map.Map map, Entity entity) {

    }

}


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Nov, 2009
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  vhaiswlouthj
  Description: DICOM Study cache manager. Maintains the cache of study instances
  			   and expires old studies after 15 minutes.

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */

package gov.va.med.imaging.vistaimagingdatasource.dicom.storage;

import gov.va.med.imaging.exchange.business.dicom.DicomCorrectEntry;
import gov.va.med.imaging.exchange.business.storage.exceptions.DeletionException;
import gov.va.med.imaging.url.vista.StringUtils;
import gov.va.med.imaging.url.vista.VistaQuery;
import gov.va.med.imaging.vistaimagingdatasource.common.EntityDAO;
import gov.va.med.imaging.vistaimagingdatasource.common.VistaSessionFactory;

import java.util.ArrayList;
import java.util.List;

@Deprecated
public class DicomCorrectEntryDAO extends EntityDAO<DicomCorrectEntry> {
//	//
//	// RPC Names
//	//
//	private String RPC_FIND_ALL = "MAGV GET DICOM FAILED IMAGE";
//	private String RPC_DELETE = "MAGV DELETE DICOM FAILED IMAGE";
//
//	private String FILEPATH = "FILEPATH";
//	private String GATEWAY_LOCATION = "GATEWAY LOCATION";
//	private String IMAGE_UID = "IMAGE UID";
//	private String STUDY_UID = "STUDY UID";
//	private String SERVICE_TYPE = "SERVICE TYPE";
//	private String MACHINE_ID = "MACHINE ID";
//	private String INSTRUMENT_NAME = "INSTRUMENT NAME";
//	private String CORRECTED_NAME = "NEWNME";
//	private String CORRECTED_SSN = "NEWSSN";
//	private String CORRECTED_CASE_NO = "NEWCASE NO";
//	private String CORRECTED_PROCEDURE_IEN = "NEW PROC IEN";
//	private String CORRECTED_PROCEDURE_DESCRIPTION = "NEW PROCEDURE";
//	private String CORRECTED_DOB = "DATE OF BIRTH";
//	private String CORRECTED_SEX = "SEX";
//	private String CORRECTED_DFN = "DFN";
//	private String CORRECTED_ICN = "INTEGRATION CONTROL NUMBER";
//	private String FILEDELETE = "DELETE FLAG";
//
//	// Constructor
//	public DicomCorrectEntryDAO(VistaSessionFactory sessionFactory) {
//		this.setSessionFactory(sessionFactory);
//	}
//
//	//
//	// Find All methods
//	//
//	@Override
//	public VistaQuery generateFindByExampleQuery(DicomCorrectEntry dicomCorrectEntry) {
//		VistaQuery vm = new VistaQuery(RPC_FIND_ALL);
//		String host = dicomCorrectEntry.getHostname();
//		vm.addParameter(VistaQuery.LITERAL, host);
//		logger.debug(this.getClass().getName()+": RPC Request "
//				+RPC_FIND_ALL+"\n"+host);
//		return vm;
//	}
//
//	@Override
//	public List<DicomCorrectEntry> translateFindByExample(DicomCorrectEntry dicomCorrectEntry, String returnValue) {
//		List<DicomCorrectEntry> entries = new ArrayList<DicomCorrectEntry>();
//
//		logger.debug(this.getClass().getName()+": RPC Results:\n"+StringUtils.displayEncodedChars(returnValue));
//		String[] resultLines = StringUtils.Split(returnValue,
//				StringUtils.NEW_LINE);
//
//		// Check that the first line starts with zero
//		String resultCode = StringUtils.Split(resultLines[0],
//				StringUtils.BACKTICK)[0];
//		if ("0".equals(resultCode)) {
//			DicomCorrectEntry entry = null;
//
//			// Loop over the result lines, building objects until we're done...
//			for (int i = 1; i < resultLines.length; i++) {
//
//				String currentLine = resultLines[i].trim();
//				if (!currentLine.equals("")) {
//
//					// Get rid of trailing backtick if any
//					String nameValuePair = StringUtils.Split(resultLines[i], StringUtils.BACKTICK)[0];
//
//					// Break remainder into name and value
//					String[] nameValueFields = StringUtils.Split(nameValuePair,StringUtils.STICK);
//					String name = nameValueFields[0];
//					String value = nameValueFields[1];
//
//					if (name.equals(FILEPATH)) {
//						// If the entry is not null, it means we've just
//						// finished filling an entry
//						// since we're back to filepath. Add it to the list
//						// before creating a new one...
//						if (entry != null) {
//							entries.add(entry);
//						}
//
//						// Create new entry and set the filepath
//						entry = new DicomCorrectEntry();
//						entry.setFilePath(value);
//					}
//					else if (name.equals(GATEWAY_LOCATION))
//					{
//						entry.setGatewayLocation(value);
//					}
//					else if (name.equals(IMAGE_UID))
//					{
//						entry.setImageUID(value);
//					}
//					else if (name.equals(STUDY_UID))
//					{
//						entry.setStudyUID(value);
//					}
//					else if (name.equals(SERVICE_TYPE))
//					{
//						entry.setServiceType(value);
//					}
//					else if (name.equals(MACHINE_ID))
//					{
//						entry.setHostname(value);
//					}
//					else if (name.equals(INSTRUMENT_NAME))
//					{
//						entry.setInstrumentNickName(value);
//					}
//					else if (name.equals(CORRECTED_NAME))
//					{
//						entry.setCorrectedName(value);
//					}
//					else if (name.equals(CORRECTED_SSN))
//					{
//						entry.setCorrectedSSN(value);
//					}
//					else if (name.equals(CORRECTED_CASE_NO))
//					{
//						entry.setCorrectedCaseNumber(value);
//					}
//					else if (name.equals(CORRECTED_PROCEDURE_IEN))
//					{
//						entry.setCorrectedProcedureIEN(value);
//					}
//					else if (name.equals(CORRECTED_PROCEDURE_DESCRIPTION))
//					{
//						entry.setCorrectedProcedureDescription(value);
//					}
//					else if (name.equals(CORRECTED_DOB))
//					{
//						entry.setCorrectedDOB(value);
//					}
//					else if (name.equals(CORRECTED_SEX))
//					{
//						entry.setCorrectedSex(value);
//					}
//					else if (name.equals(CORRECTED_DFN))
//					{
//						entry.setCorrectedDFN(value);
//					}
//					else if (name.equals(CORRECTED_ICN))
//					{
//						entry.setCorrectedICN(value);
//					}
//					else if(name.equals(FILEDELETE)){
//						if(value.equals("1")){
//							entry.setFileToBeDeleted(true);
//						}
//						else{
//							entry.setFileToBeDeleted(false);
//						}
//					}
//				}
//			}
//			//
//			// We've populated the last field of the last entry.
//			// Add the entry into the list if it's not null...
//			if (entry != null)
//			{
//				entries.add(entry);
//			}
//		}
//
//		return entries;
//	}
//
//	//
//	// Delete methods
//	//
//	@Override
//	public VistaQuery generateDeleteQuery(DicomCorrectEntry dicomCorrectEntry) {
//		VistaQuery vm = new VistaQuery(RPC_DELETE);
//		String filePath = dicomCorrectEntry.getFilePath();
//		vm.addParameter(VistaQuery.LITERAL, filePath);
//		logger.debug(this.getClass().getName()+": RPC Request "
//				+RPC_DELETE+"\n"+filePath);
//		return vm;
//	}
//
//	@Override
//	public void translateDelete(String returnValue) throws DeletionException
//	{
//		logger.debug(this.getClass().getName()+": RPC Results:\n"+StringUtils.displayEncodedChars(returnValue));
//		String[] results = StringUtils.Split(returnValue, StringUtils.BACKTICK);
//
//		if (!results[0].equals("0"))
//		{
//
//			throw new DeletionException(results[1]);
//		}
//	}

}


text:
package kafka.server.checkpoints

import kafka.server.LogDirFailureChannel
import kafka.server.epoch.EpochEntry
import org.apache.kafka.server.common.CheckpointFile.EntryFormatter

import java.io._
import java.util.Optional
import java.util.regex.Pattern
import scala.collection._

trait LeaderEpochCheckpoint {
  def write(epochs: Iterable[EpochEntry]): Unit
  def read(): Seq[EpochEntry]
}

object LeaderEpochCheckpointFile {
  private val LeaderEpochCheckpointFilename = "leader-epoch-checkpoint"
  private val WhiteSpacesPattern = Pattern.compile("\\s+")
  private val CurrentVersion = 0

  def newFile(dir: File): File = new File(dir, LeaderEpochCheckpointFilename)

  object Formatter extends EntryFormatter[EpochEntry] {

    override def toString(entry: EpochEntry): String = s"${entry.epoch} ${entry.startOffset}"

    override def fromString(line: String): Optional[EpochEntry] = {
      WhiteSpacesPattern.split(line) match {
        case Array(epoch, offset) =>
          Optional.of(EpochEntry(epoch.toInt, offset.toLong))
        case _ => Optional.empty()
      }
    }

  }
}

/**
 * This class persists a map of (LeaderEpoch => Offsets) to a file (for a certain replica)
 *
 * The format in the LeaderEpoch checkpoint file is like this:
 * -----checkpoint file begin------
 * 0                <- LeaderEpochCheckpointFile.currentVersion
 * 2                <- following entries size
 * 0  1     <- the format is: leader_epoch(int32) start_offset(int64)
 * 1  2
 * -----checkpoint file end----------
 */
class LeaderEpochCheckpointFile(val file: File, logDirFailureChannel: LogDirFailureChannel = null) extends LeaderEpochCheckpoint {
  import LeaderEpochCheckpointFile._

  val checkpoint = new CheckpointFileWithFailureHandler[EpochEntry](file, CurrentVersion, Formatter, logDirFailureChannel, file.getParentFile.getParent)

  def write(epochs: Iterable[EpochEntry]): Unit = checkpoint.write(epochs)

  def read(): Seq[EpochEntry] = checkpoint.read()
}