text:
// Copyright (c) 2001-2014 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////

using System;
using System.Collections;
using System.Drawing;
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Fields;
using Aspose.Words.Fonts;
using Aspose.Words.Tables;
using NUnit.Framework;
using QA_Tests.Tests;

namespace QA_Tests.Examples.Font
{
    [TestFixture]
    public class ExFont : QaTestsBase
    {
        [Test]
        public void CreateFormattedRun()
        {
            //ExStart
            //ExFor:Document.#ctor
            //ExFor:Font
            //ExFor:Font.Name
            //ExFor:Font.Size
            //ExFor:Font.HighlightColor
            //ExFor:Run
            //ExFor:Run.#ctor(DocumentBase,String)
            //ExFor:Story.FirstParagraph
            //ExSummary:Shows how to add a formatted run of text to a document using the object model.
            // Create an empty document. It contains one empty paragraph.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // Create a new run of text.
            Run run = new Run(doc, "Hello");

            // Specify character formatting for the run of text.
            Aspose.Words.Font f = run.Font;
            f.Name = "Courier New";
            f.Size = 36;
            f.HighlightColor = Color.Yellow;

            // Append the run of text to the end of the first paragraph
            // in the body of the first section of the document.
            doc.FirstSection.Body.FirstParagraph.AppendChild(run);
            //ExEnd
        }

        [Test]
        public void Caps()
        {
            //ExStart
            //ExFor:Font.AllCaps
            //ExFor:Font.SmallCaps
            //ExSummary:Shows how to use all capitals and small capitals character formatting properties.
            // Create an empty document. It contains one empty paragraph.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // Get the paragraph from the document, we will be adding runs of text to it.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 0, true);

            Run run = new Run(doc, "All capitals");
            run.Font.AllCaps = true;
            para.AppendChild(run);

            run = new Run(doc, "SMALL CAPITALS");
            run.Font.SmallCaps = true;
            para.AppendChild(run);
            //ExEnd
        }

        [Test]
        public void GetDocumentFonts()
        {
            //ExStart:
            //ExFor:FontInfoCollection
            //ExFor:DocumentBase.FontInfos
            //ExFor:FontInfo
            //ExFor:FontInfo.Name
            //ExFor:FontInfo.IsTrueType
            //ExSummary:Shows how to gather the details of what fonts are present in a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc");

            FontInfoCollection fonts = doc.FontInfos;
            int fontIndex = 1;

            // The fonts info extracted from this document does not necessarily mean that the fonts themselves are
            // used in the document. If a font is present but not used then most likely they were referenced at some time
            // and then removed from the Document.
            foreach (FontInfo info in fonts)
            {
                // Print out some important details about the font.
                Console.WriteLine("Font #{0}", fontIndex);
                Console.WriteLine("Name: {0}", info.Name);
                Console.WriteLine("IsTrueType: {0}", info.IsTrueType);
                fontIndex++;
            }
            //ExEnd
        }

        [Test]
        public void Strikethrough()
        {
            //ExStart
            //ExFor:Font.StrikeThrough
            //ExFor:Font.DoubleStrikeThrough
            //ExSummary:Shows how to use strike-through character formatting properties.
            // Create an empty document. It contains one empty paragraph.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // Get the paragraph from the document, we will be adding runs of text to it.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 0, true);

            Run run = new Run(doc, "Double strike through text");
            run.Font.DoubleStrikeThrough = true;
            para.AppendChild(run);

            run = new Run(doc, "Single strike through text");
            run.Font.StrikeThrough = true;
            para.AppendChild(run);
            //ExEnd
        }

        [Test]
        public void PositionSubscript()
        {
            //ExStart
            //ExFor:Font.Position
            //ExFor:Font.Subscript
            //ExFor:Font.Superscript
            //ExSummary:Shows how to use subscript, superscript and baseline text position properties.
            // Create an empty document. It contains one empty paragraph.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // Get the paragraph from the document, we will be adding runs of text to it.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 0, true);

            // Add a run of text that is raised 5 points above the baseline.
            Run run = new Run(doc, "Raised text");
            run.Font.Position = 5;
            para.AppendChild(run);

            // Add a run of normal text.
            run = new Run(doc, "Normal text");
            para.AppendChild(run);

            // Add a run of text that appears as subscript.
            run = new Run(doc, "Subscript");
            run.Font.Subscript = true;
            para.AppendChild(run);

            // Add a run of text that appears as superscript.
            run = new Run(doc, "Superscript");
            run.Font.Superscript = true;
            para.AppendChild(run);
            //ExEnd
        }

        [Test]
        public void ScalingSpacing()
        {
            //ExStart
            //ExFor:Font.Scaling
            //ExFor:Font.Spacing
            //ExSummary:Shows how to use character scaling and spacing properties.
            // Create an empty document. It contains one empty paragraph.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            // Get the paragraph from the document, we will be adding runs of text to it.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 0, true);

            // Add a run of text with characters 150% width of normal characters.
            Run run = new Run(doc, "Wide characters");
            run.Font.Scaling = 150;
            para.AppendChild(run);

            // Add a run of text with extra 1pt space between characters.
            run = new Run(doc, "Expanded by 1pt");
            run.Font.Spacing = 1;
            para.AppendChild(run);

            // Add a run of text with with space between characters reduced by 1pt.
            run = new Run(doc, "Condensed by 1pt");
            run.Font.Spacing = -1;
            para.AppendChild(run);
            //ExEnd
        }

        [Test]
        public void EmbossItalic()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Emboss
            //ExFor:Font.Italic
            //ExSummary:Shows how to create a run of formatted text.
            Run run = new Run(doc, "Hello");
            run.Font.Emboss = true;
            run.Font.Italic = true;
            //ExEnd
        }

        [Test]
        public void Engrave()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Engrave
            //ExSummary:Shows how to create a run of text formatted as engraved.
            Run run = new Run(doc, "Hello");
            run.Font.Engrave = true;
            //ExEnd
        }

        [Test]
        public void Shadow()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Shadow
            //ExSummary:Shows how to create a run of text formatted with a shadow.
            Run run = new Run(doc, "Hello");
            run.Font.Engrave = true;
            //ExEnd
        }

        [Test]
        public void Outline()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Outline
            //ExSummary:Shows how to create a run of text formatted as outline.
            Run run = new Run(doc, "Hello");
            run.Font.Outline = true;
            //ExEnd
        }

        [Test]
        public void Hidden()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Hidden
            //ExSummary:Shows how to create a hidden run of text.
            Run run = new Run(doc, "Hello");
            run.Font.Hidden = true;
            //ExEnd
        }

        [Test]
        public void Kerning()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Kerning
            //ExSummary:Shows how to specify the font size at which kerning starts.
            Run run = new Run(doc, "Hello");
            run.Font.Kerning = 24;
            //ExEnd
        }

        [Test]
        public void NoProofing()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.NoProofing
            //ExSummary:Shows how to specify that the run of text is not to be spell checked by Microsoft Word.
            Run run = new Run(doc, "Hello");
            run.Font.NoProofing = true;
            //ExEnd
        }

        [Test]
        public void LocaleId()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();

            //ExStart
            //ExFor:Font.LocaleId
            //ExSummary:Shows how to specify the language of a text run so Microsoft Word can use a proper spell checker.
            //Create a run of text that contains Russian text.
            Run run = new Run(doc, "Привет");

            //Specify the locale so Microsoft Word recognizes this text as Russian.
            //For the list of locale identifiers see http://www.microsoft.com/globaldev/reference/lcid-all.mspx
            run.Font.LocaleId = 1049;
            //ExEnd
        }

        [Test]
        public void Underlines()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();
            //ExStart
            //ExFor:Font.Underline
            //ExFor:Font.UnderlineColor
            //ExSummary:Shows how use the underline character formatting properties.
            Run run = new Run(doc, "Hello");
            run.Font.Underline = Underline.Dotted;
            run.Font.UnderlineColor = Color.Red;
            //ExEnd
        }

        [Test]
        public void Shading()
        {
            //ExStart
            //ExFor:Font.Shading
            //ExSummary:Shows how to apply shading for a run of text.
            DocumentBuilder builder = new DocumentBuilder();

            Shading shd = builder.Font.Shading;
            shd.Texture = TextureIndex.TextureDiagonalCross;
            shd.BackgroundPatternColor = Color.Blue;
            shd.ForegroundPatternColor = Color.BlueViolet;

            builder.Font.Color = Color.White;

            builder.Writeln("White text on a blue background with texture.");
            //ExEnd
        }

        [Test]
        public void Bidi()
        {
            //ExStart
            //ExFor:Font.Bidi
            //ExFor:Font.NameBi
            //ExFor:Font.SizeBi
            //ExFor:Font.ItalicBi
            //ExFor:Font.BoldBi
            //ExFor:Font.LocaleIdBi
            //ExSummary:Shows how to insert and format right-to-left text.
            DocumentBuilder builder = new DocumentBuilder();

            // Signal to Microsoft Word that this run of text contains right-to-left text.
            builder.Font.Bidi = true;

            // Specify the font and font size to be used for the right-to-left text.
            builder.Font.NameBi = "Andalus";
            builder.Font.SizeBi = 48;

            // Specify that the right-to-left text in this run is bold and italic.
            builder.Font.ItalicBi = true;
            builder.Font.BoldBi = true;

            // Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
            // For the list of locale identifiers see http://www.microsoft.com/globaldev/reference/lcid-all.mspx
            builder.Font.LocaleIdBi = 1025;

            // Insert some Arabic text.
            builder.Writeln("مرحبًا");

            builder.Document.Save(ExDir + "Font.Bidi Out.doc");
            //ExEnd
        }

        [Test]
        public void FarEast()
        {
            //ExStart
            //ExFor:Font.NameFarEast
            //ExFor:Font.LocaleIdFarEast
            //ExSummary:Shows how to insert and format text in Chinese or any other Far East language.
            DocumentBuilder builder = new DocumentBuilder();

            builder.Font.Size = 48;

            // Specify the font name. Make sure it the font has the glyphs that you want to display.
            builder.Font.NameFarEast = "SimSun";

            // Specify the locale so Microsoft Word recognizes this text as Chinese.
            // For the list of locale identifiers see http://www.microsoft.com/globaldev/reference/lcid-all.mspx
            builder.Font.LocaleIdFarEast = 2052;

            // Insert some Chinese text.
            builder.Writeln("你好世界");

            builder.Document.Save(ExDir + "Font.FarEast Out.doc");
            //ExEnd
        }

        [Test]
        public void Names()
        {
            //ExStart
            //ExFor:Font.NameAscii
            //ExFor:Font.NameOther
            //ExSummary:A pretty unusual example of how Microsoft Word can combine two different fonts in one run.
            DocumentBuilder builder = new DocumentBuilder();

            // This tells Microsoft Word to use Arial for characters 0..127 and
            // Times New Roman for characters 128..255.
            // Looks like a pretty strange case to me, but it is possible.
            builder.Font.NameAscii = "Arial";
            builder.Font.NameOther = "Times New Roman";

            builder.Writeln("Hello, Привет");

            builder.Document.Save(ExDir + "Font.Names Out.doc");
            //ExEnd
        }

        [Test]
        public void ChangeStyleIdentifier()
        {
            //ExStart
            //ExFor:Font.StyleIdentifier
            //ExFor:StyleIdentifier
            //ExSummary:Shows how to use style identifier to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.StyleIdentifier.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that using StyleIdentifier we can identify a built-in style regardless
                // of the language of Microsoft Word used to create the document.
                if (run.Font.StyleIdentifier.Equals(StyleIdentifier.Emphasis))
                    run.Font.StyleIdentifier = StyleIdentifier.Strong;
            }

            doc.Save(ExDir + "Font.StyleIdentifier Out.doc");
            //ExEnd
        }

        [Test]
        public void ChangeStyleName()
        {
            //ExStart
            //ExFor:Font.StyleName
            //ExSummary:Shows how to use style name to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.StyleName.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that names of built in styles could be different in documents
                // created by Microsoft Word versions for different languages.
                if (run.Font.StyleName.Equals("Emphasis"))
                    run.Font.StyleName = "Strong";
            }

            doc.Save(ExDir + "Font.StyleName Out.doc");
            //ExEnd
        }

        [Test]
        public void Style()
        {
            //ExStart
            //ExFor:Font.Style
            //ExFor:Style.BuiltIn
            //ExSummary:Applies double underline to all runs in a document that are formatted with custom character styles.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Style.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                Aspose.Words.Style charStyle = run.Font.Style;

                // If the style of the run is not a built-in character style, apply double underline.
                if (!charStyle.BuiltIn)
                    run.Font.Underline = Underline.Double;
            }

            doc.Save(ExDir + "Font.Style Out.doc");
            //ExEnd
        }

        [Test]
        public void GetAllFonts()
        {
            //ExStart
            //ExFor:Run
            //ExSummary:Gets all fonts used in a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Names.doc");

            // Select all runs in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Use a hashtable so we will keep only unique font names.
            Hashtable fontNames = new Hashtable();

            foreach (Run run in runs)
            {
                // This adds an entry into the hashtable.
                // The key is the font name. The value is null, we don't need the value.
                fontNames[run.Font.Name] = null;
            }

            // There are two fonts used in this document.
            Console.WriteLine("Font Count: " + fontNames.Count);
            //ExEnd

            // Verify the font count is correct.
            Assert.AreEqual(2, fontNames.Count);

        }

        /// <summary>
        /// This calls the below method to resolve skipping of [Test] in VB.NET.
        /// </summary>
        [Test]
        public void RemoveHiddenContentCaller()
        {
            RemoveHiddenContentFromDocument();
        }

        //ExStart
        //ExFor:Font.Hidden
        //ExFor:Paragraph.Accept
        //ExFor:DocumentVisitor.VisitParagraphStart(Aspose.Words.Paragraph)
        //ExFor:DocumentVisitor.VisitFormField(Aspose.Words.Fields.FormField)
        //ExFor:DocumentVisitor.VisitTableEnd(Aspose.Words.Tables.Table)
        //ExFor:DocumentVisitor.VisitCellEnd(Aspose.Words.Tables.Cell)
        //ExFor:DocumentVisitor.VisitRowEnd(Aspose.Words.Tables.Row)
        //ExFor:DocumentVisitor.VisitSpecialChar(Aspose.Words.SpecialChar)
        //ExFor:DocumentVisitor.VisitGroupShapeStart(Aspose.Words.Drawing.GroupShape)
        //ExFor:DocumentVisitor.VisitShapeStart(Aspose.Words.Drawing.Shape)
        //ExFor:DocumentVisitor.VisitCommentStart(Aspose.Words.Comment)
        //ExFor:DocumentVisitor.VisitFootnoteStart(Aspose.Words.Footnote)
        //ExFor:SpecialChar
        //ExFor:Node.Accept
        //ExFor:Paragraph.ParagraphBreakFont
        //ExFor:Table.Accept
        //ExSummary:Implements the Visitor Pattern to remove all content formatted as hidden from the document.
        public void RemoveHiddenContentFromDocument()
        {
            // Open the document we want to remove hidden content from.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Hidden.doc");

            // Create an object that inherits from the DocumentVisitor class.
            RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

            // This is the well known Visitor pattern. Get the model to accept a visitor.
            // The model will iterate through itself by calling the corresponding methods
            // on the visitor object (this is called visiting).

            // We can run it over the entire the document like so:
            doc.Accept(hiddenContentRemover);

            // Or we can run it on only a specific node.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 4, true);
            para.Accept(hiddenContentRemover);

            // Or over a different type of node like below.
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
            table.Accept(hiddenContentRemover);

            doc.Save(ExDir + "Font.Hidden Out.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count); //ExSkip
        }

        /// <summary>
        /// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
        /// </summary>
        class RemoveHiddenContentVisitor : DocumentVisitor
        {
            /// <summary>
            /// Called when a FieldStart node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFieldStart(FieldStart fieldStart)
            {
                // If this node is hidden, then remove it.
                if (isHidden(fieldStart))
                    fieldStart.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a FieldEnd node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
            {
                if (isHidden(fieldEnd))
                    fieldEnd.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a FieldSeparator node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
            {
                if (isHidden(fieldSeparator))
                    fieldSeparator.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a Run node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitRun(Run run)
            {
                if (isHidden(run))
                    run.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a Paragraph node is encountered in the document.
            /// </summary>
            public override VisitorAction VisitParagraphStart(Paragraph paragraph)
            {
                if (isHidden(paragraph))
                    paragraph.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a FormField is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFormField(FormField field)
            {
                if (isHidden(field))
                    field.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a GroupShape is encountered in the document.
            /// </summary>
            public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
            {
                if (isHidden(groupShape))
                    groupShape.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a Shape is encountered in the document.
            /// </summary>
            public override VisitorAction VisitShapeStart(Shape shape)
            {
                if (isHidden(shape))
                    shape.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a Comment is encountered in the document.
            /// </summary>
            public override VisitorAction VisitCommentStart(Aspose.Words.Comment comment)
            {
                if (isHidden(comment))
                    comment.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a Footnote is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFootnoteStart(Footnote footnote)
            {
                if (isHidden(footnote))
                    footnote.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when visiting of a Table node is ended in the document.
            /// </summary>
            public override VisitorAction VisitTableEnd(Table table)
            {
                // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
                // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
                // hidden and thus removed by previous visits as well. This will result in the container being empty
                // so if this is the case we know to remove the table node.
                //
                // Note that a table which is not hidden but simply has no content will not be affected by this algorthim,
                // as technically they are not completely empty (for example a properly formed Cell will have at least
                // an empty paragraph in it)
                if (!table.HasChildNodes)
                    table.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when visiting of a Cell node is ended in the document.
            /// </summary>
            public override VisitorAction VisitCellEnd(Cell cell)
            {
                if (!cell.HasChildNodes && cell.ParentNode != null)
                    cell.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when visiting of a Row node is ended in the document.
            /// </summary>
            public override VisitorAction VisitRowEnd(Row row)
            {
                if (!row.HasChildNodes && row.ParentNode != null)
                    row.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Called when a SpecialCharacter is encountered in the document.
            /// </summary>
            public override VisitorAction VisitSpecialChar(SpecialChar character)
            {
                if (isHidden(character))
                    character.Remove();

                return VisitorAction.Continue;
            }

            /// <summary>
            /// Returns true if the node passed is set as hidden, returns false if it is visible.
            /// </summary>
            private bool isHidden(Aspose.Words.Node node)
            {
                if (node is Aspose.Words.Inline)
                {
                    // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
                    Aspose.Words.Inline currentNode = (Aspose.Words.Inline)node;
                    return currentNode.Font.Hidden;
                }
                else if (node.NodeType == NodeType.Paragraph)
                {
                    // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
                    Paragraph para = (Paragraph)node;
                    return para.ParagraphBreakFont.Hidden;
                }
                else if (node is ShapeBase)
                {
                    // Node is a shape or groupshape.
                    ShapeBase shape = (ShapeBase)node;
                    return shape.Font.Hidden;
                }
                else if (node is InlineStory)
                {
                    // Node is a comment or footnote.
                    InlineStory inlineStory = (InlineStory)node;
                    return inlineStory.Font.Hidden;
                }

                // A node that is passed to this method which does not contain a hidden property will end up here.
                // By default nodes are not hidden so return false.
                return false;
            }

        }
        //ExEnd
    }
}


text:
var MockServer  = require('../../../lib/mockserver.js');
var assert = require('assert');
var Nightwatch = require('../../../lib/nightwatch.js');
var MochaTest = require('../../../lib/mochatest.js');

module.exports = MochaTest.add('getElementSize', {

  'client.getElementSize()' : function(done) {
    var client = Nightwatch.api();

    MockServer.addMock({
      url : '/wd/hub/session/1352110219202/element/0/size',
      method:'GET',
      response : JSON.stringify({
        sessionId: '1352110219202',
        status:0,
        value :100
      })
    });

    client.getElementSize('#weblogin', function callback(result) {
      assert.equal(result.value, 100);
    }).getElementSize('css selector', '#weblogin', function callback(result) {
      assert.equal(result.value, 100);
      done();
    });

    Nightwatch.start();
  }
}
);

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.google.cloud</groupId>
  <artifactId>cloudasset-install-without-bom</artifactId>
  <packaging>jar</packaging>
  <name>Google Cloud Asset Inventory Install Without Bom</name>
  <url>https://github.com/googleapis/java-asset</url>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- [START cloudasset_install_without_bom] -->
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-asset</artifactId>
      <version>3.7.1</version>
    </dependency>
    <!-- [END cloudasset_install_without_bom] -->

    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-core</artifactId>
      <version>2.8.20</version>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-storage</artifactId>
      <version>2.13.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-bigquery</artifactId>
      <version>2.17.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-pubsub</artifactId>
      <version>1.120.20</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-resourcemanager</artifactId>
      <version>1.5.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>1.1.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <!-- compile and run all snippet tests -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.3.0</version>
        <executions>
          <execution>
            <id>add-snippets-source</id>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>../snippets/src/main/java</source>
              </sources>
            </configuration>
          </execution>
          <execution>
            <id>add-snippets-tests</id>
            <goals>
              <goal>add-test-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>../snippets/src/test/java</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
import { connect } from 'react-redux';
import Nav from '../components/Nav';

const mapStateToProps = state => (
  {
    // active: ownProps.filter === state.visibilityFilter,
    name: state.user.name,
    teamName: state.user.teamName,
    isFetching: state.user.isFetching,
    error: state.user.error,
  }
);

const NavBar = connect(
  mapStateToProps,
)(Nav);

export default NavBar;


text:
#pragma once

#include <cilantro/3rd_party/nanoflann/nanoflann.hpp>
#include <cilantro/core/data_containers.hpp>
#include <cilantro/core/nearest_neighbors.hpp>

namespace cilantro {
    namespace KDTreeDataAdaptors {
        // Eigen Map to nanoflann adaptor class
        template <class ScalarT, ptrdiff_t EigenDim>
        struct EigenMap {
            typedef ScalarT coord_t;

            // A const ref to the data set origin
            const Eigen::Map<const Eigen::Matrix<ScalarT,EigenDim,Eigen::Dynamic>>& obj;

            // The constructor that sets the data set source
            EigenMap(const Eigen::Map<const Eigen::Matrix<ScalarT,EigenDim,Eigen::Dynamic>> &obj_) : obj(obj_) {}

            // CRTP helper method
            inline const Eigen::Map<const Eigen::Matrix<ScalarT,EigenDim,Eigen::Dynamic>>& derived() const { return obj; }

            // Must return the number of data points
            inline size_t kdtree_get_point_count() const { return obj.cols(); }

            // Returns the dim'th component of the idx'th point in the class
            inline coord_t kdtree_get_pt(const size_t idx, int dim) const { return obj(dim,idx); }

            // Optional bounding-box computation: return false to default to a standard bbox computation loop.
            //   Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again.
            //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)
            template <class BBOX>
            bool kdtree_get_bbox(BBOX& /*bb*/) const { return false; }
        };
    } // namespace KDTreeDataAdaptors

    namespace KDTreeDistanceAdaptors {
        template <class DataAdaptor>
        using L1 = nanoflann::L1_Adaptor<typename DataAdaptor::coord_t, DataAdaptor, typename DataAdaptor::coord_t>;

        template <class DataAdaptor>
        using L2 = nanoflann::L2_Adaptor<typename DataAdaptor::coord_t, DataAdaptor, typename DataAdaptor::coord_t>;

        template <class DataAdaptor>
        using L2Simple = nanoflann::L2_Simple_Adaptor<typename DataAdaptor::coord_t, DataAdaptor, typename DataAdaptor::coord_t>;

        template <class DataAdaptor>
        using SO2 = nanoflann::SO2_Adaptor<typename DataAdaptor::coord_t, DataAdaptor, typename DataAdaptor::coord_t>;

        template <class DataAdaptor>
        using SO3 = nanoflann::SO3_Adaptor<typename DataAdaptor::coord_t, DataAdaptor, typename DataAdaptor::coord_t>;
    } // namespace KDTreeDistanceAdaptors

    template <typename ScalarT, typename IndexT = size_t, typename CountT = size_t>
    class KNNSearchResultAdaptor {
    public:
        KNNSearchResultAdaptor(Neighborhood<ScalarT,IndexT> &results, CountT k, ScalarT max_radius = std::numeric_limits<ScalarT>::max())
                : results_(results), k_(k), count_(0)
        {
            results_.resize(k_);
            results_[k_-1].value = max_radius;
        }

        inline CountT size() const { return count_; }

        inline bool full() const { return count_ == k_; }

        inline bool addPoint(ScalarT dist, IndexT index) {
            CountT i;
            for (i = count_; i > 0; --i) {
                if (results_[i-1].value > dist) {
                    if (i < k_) {
                        results_[i].index = results_[i-1].index;
                        results_[i].value = results_[i-1].value;
                    }
                } else {
                    break;
                }
            }
            if (i < k_) {
                results_[i].index = index;
                results_[i].value = dist;
            }
            if (count_ < k_) count_++;

            return true;
        }

        inline ScalarT worstDist() const { return results_[k_-1].value; }

    private:
        Neighborhood<ScalarT,IndexT>& results_;
        const CountT k_;
        CountT count_;
    };

    template <typename ScalarT, typename IndexT = size_t, typename CountT = size_t>
    class RadiusSearchResultAdaptor {
    public:
        RadiusSearchResultAdaptor(Neighborhood<ScalarT,IndexT> &results, ScalarT radius)
                : results_(results), radius_(radius)
        {
            results_.clear();
        }

        inline CountT size() const { return results_.size(); }

        inline bool full() const { return true; }

        inline bool addPoint(ScalarT dist, IndexT index) {
            // dist < worstDist() is guaranteed when addPoint is called.
            results_.emplace_back(index, dist);
            return true;
        }

        inline ScalarT worstDist() const { return radius_; }

    private:
        Neighborhood<ScalarT,IndexT>& results_;
        const ScalarT radius_;
    };

    template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    class KDTree {
    public:
        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        typedef ScalarT Scalar;
        typedef IndexT Index;

        typedef Neighbor<ScalarT,IndexT> NeighborResult;
        typedef Neighborhood<ScalarT,IndexT> NeighborhoodResult;
        typedef NeighborSet<ScalarT,IndexT> NeighborSetResult;
        typedef NeighborhoodSet<ScalarT,IndexT> NeighborhoodSetResult;

        enum { Dimension = EigenDim };

        typedef nanoflann::KDTreeSingleIndexAdaptor<DistAdaptor<KDTreeDataAdaptors::EigenMap<ScalarT,EigenDim>>,KDTreeDataAdaptors::EigenMap<ScalarT,EigenDim>,EigenDim,IndexT> InternalTree;

        KDTree(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &data, size_t max_leaf_size = 10)
                : data_map_(data),
                  data_adaptor_(data_map_),
                  kd_tree_(data.rows(), data_adaptor_, nanoflann::KDTreeSingleIndexAdaptorParams(max_leaf_size))
        {
            params_.sorted = true;
            kd_tree_.buildIndex();
        }

        ~KDTree() {}

        inline const ConstVectorSetMatrixMap<ScalarT,EigenDim>& getPointsMatrixMap() const { return data_map_; }

        inline bool isEmpty() const { return data_map_.cols() == 0; }

        inline const InternalTree& nanoflannTree() const { return kd_tree_; }

        // Do not call if tree is empty!
        inline const KDTree& nearestNeighborSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                                   NeighborResult &result) const
        {
            kd_tree_.knnSearch(query_pt.data(), 1, &result.index, &result.value);
            return *this;
        }

        // Do not call if tree is empty!
        inline NeighborResult nearestNeighborSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt) const
        {
            NeighborResult result;
            kd_tree_.knnSearch(query_pt.data(), 1, &result.index, &result.value);
            return result;
        }

        // Do not call if tree is empty!
        const KDTree& nearestNeighborSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                            NeighborhoodResult &results) const
        {
            results.resize(query_pts.cols());
#pragma omp parallel for shared (results)
            for (size_t i = 0; i < query_pts.cols(); i++) {
                nearestNeighborSearch(query_pts.col(i), results[i]);
            }
            return *this;
        }

        // Do not call if tree is empty!
        // Unlike the other batch searches, this one returns a flat vector of Neighbor
        inline NeighborhoodResult nearestNeighborSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts) const {
            NeighborhoodResult results;
            nearestNeighborSearch(query_pts, results);
            return results;
        }

        template <typename CountT = size_t>
        inline const KDTree& kNNSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                       CountT k,
                                       NeighborhoodResult &results) const
        {
            KNNSearchResultAdaptor<ScalarT,IndexT,CountT> sra(results, k);
            kd_tree_.findNeighbors(sra, query_pt.data(), params_);
            results.resize(sra.size());
            return *this;
        }

        template <typename CountT = size_t>
        inline NeighborhoodResult kNNSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                            CountT k) const
        {
            NeighborhoodResult results;
            kNNSearch(query_pt, k, results);
            return results;
        }

        template <typename CountT = size_t>
        const KDTree& kNNSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                CountT k,
                                NeighborhoodSetResult &results) const
        {
            results.resize(query_pts.cols());
#pragma omp parallel for shared (results)
            for (size_t i = 0; i < query_pts.cols(); i++) {
                kNNSearch(query_pts.col(i), k, results[i]);
            }
            return *this;
        }

        template <typename CountT = size_t>
        inline NeighborhoodSetResult kNNSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                               CountT k) const
        {
            NeighborhoodSetResult results;
            kNNSearch(query_pts, k, results);
            return results;
        }

        inline const KDTree& radiusSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                          ScalarT radius,
                                          NeighborhoodResult &results) const
        {
            RadiusSearchResultAdaptor<ScalarT,IndexT,size_t> sra(results, radius);
            kd_tree_.findNeighbors(sra, query_pt.data(), params_);
            std::sort(results.begin(), results.end(), typename NeighborResult::ValueLessComparator());
            return *this;
        }

        inline NeighborhoodResult radiusSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                               ScalarT radius) const
        {
            NeighborhoodResult results;
            radiusSearch(query_pt, radius, results);
            return results;
        }

        const KDTree& radiusSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                   ScalarT radius,
                                   NeighborhoodSetResult &results) const
        {
            results.resize(query_pts.cols());
#pragma omp parallel for shared (results)
            for (size_t i = 0; i < query_pts.cols(); i++) {
                radiusSearch(query_pts.col(i), radius, results[i]);
            }
            return *this;
        }

        inline NeighborhoodSetResult radiusSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                                  ScalarT radius) const
        {
            NeighborhoodSetResult results;
            radiusSearch(query_pts, radius, results);
            return results;
        }

        template <typename CountT = size_t>
        inline const KDTree& kNNInRadiusSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                               CountT k,
                                               ScalarT radius,
                                               NeighborhoodResult &results) const
        {
            KNNSearchResultAdaptor<ScalarT,IndexT,CountT> sra(results, k, radius);
            kd_tree_.findNeighbors(sra, query_pt.data(), params_);
            results.resize(sra.size());
            return *this;
        }

        template <typename CountT = size_t>
        inline NeighborhoodResult kNNInRadiusSearch(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                                    CountT k,
                                                    ScalarT radius) const
        {
            NeighborhoodResult results;
            kNNInRadiusSearch(query_pt, k, radius, results);
            return results;
        }

        template <typename CountT = size_t>
        const KDTree& kNNInRadiusSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                        CountT k,
                                        ScalarT radius,
                                        NeighborhoodSetResult &results) const
        {
            results.resize(query_pts.cols());
#pragma omp parallel for shared (results)
            for (size_t i = 0; i < query_pts.cols(); i++) {
                kNNInRadiusSearch(query_pts.col(i), k, radius, results[i]);
            }
            return *this;
        }

        template <typename CountT = size_t>
        inline NeighborhoodSetResult kNNInRadiusSearch(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                                       CountT k,
                                                       ScalarT radius) const
        {
            NeighborhoodSetResult results;
            kNNInRadiusSearch(query_pts, k, radius, results);
            return results;
        }

        template <typename CountT = size_t>
        inline const KDTree& search(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                    const KNNNeighborhoodSpecification<CountT> &nh,
                                    NeighborhoodResult &results) const
        {
            kNNSearch(query_pt, nh.maxNumberOfNeighbors, results);
            return *this;
        }

        template <typename CountT = size_t>
        inline const KDTree& search(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                    const KNNNeighborhoodSpecification<CountT> &nh,
                                    NeighborhoodSetResult &results) const
        {
            kNNSearch(query_pts, nh.maxNumberOfNeighbors, results);
            return *this;
        }

        inline const KDTree& search(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                    const RadiusNeighborhoodSpecification<ScalarT> &nh,
                                    NeighborhoodResult &results) const
        {
            radiusSearch(query_pt, nh.radius, results);
            return *this;
        }

        inline const KDTree& search(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                    const RadiusNeighborhoodSpecification<ScalarT> &nh,
                                    NeighborhoodSetResult &results) const
        {
            radiusSearch(query_pts, nh.radius, results);
            return *this;
        }

        template <typename CountT = size_t>
        inline const KDTree& search(const Eigen::Ref<const Vector<ScalarT,EigenDim>> &query_pt,
                                    const KNNInRadiusNeighborhoodSpecification<ScalarT,CountT> &nh,
                                    NeighborhoodResult &results) const
        {
            kNNInRadiusSearch(query_pt, nh.maxNumberOfNeighbors, nh.radius, results);
            return *this;
        }

        template <typename CountT = size_t>
        inline const KDTree& search(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
                                    const KNNInRadiusNeighborhoodSpecification<ScalarT,CountT> &nh,
                                    NeighborhoodSetResult &results) const
        {
            kNNInRadiusSearch(query_pts, nh.maxNumberOfNeighbors, nh.radius, results);
            return *this;
        }

        template <typename PointT, typename NeighborhoodSpecT>
        inline typename std::enable_if<PointT::ColsAtCompileTime == 1,NeighborhoodResult>::type
        search(const PointT &query_pt,
               const NeighborhoodSpecT &nh) const
        {
            NeighborhoodResult res;
            search(query_pt, nh, res);
            return res;
        }

        template <typename PointsT, typename NeighborhoodSpecT>
        inline typename std::enable_if<PointsT::ColsAtCompileTime == Eigen::Dynamic,NeighborhoodSetResult>::type
        search(const PointsT &query_pts,
               const NeighborhoodSpecT &nh) const
        {
            NeighborhoodSetResult res;
            search(query_pts, nh, res);
            return res;
        }

    private:
        ConstVectorSetMatrixMap<ScalarT,EigenDim> data_map_;
        const KDTreeDataAdaptors::EigenMap<ScalarT,EigenDim> data_adaptor_;
        InternalTree kd_tree_;
        nanoflann::SearchParams params_;
    };

    template <template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    using KDTree2f = KDTree<float,2,DistAdaptor,IndexT>;

    template <template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    using KDTree2d = KDTree<double,2,DistAdaptor,IndexT>;

    template <template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    using KDTree3f = KDTree<float,3,DistAdaptor,IndexT>;

    template <template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    using KDTree3d = KDTree<double,3,DistAdaptor,IndexT>;

    template <template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    using KDTreeXf = KDTree<float,Eigen::Dynamic,DistAdaptor,IndexT>;

    template <template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, typename IndexT = size_t>
    using KDTreeXd = KDTree<double,Eigen::Dynamic,DistAdaptor,IndexT>;
}


text:
<?php
namespace de\ilusionstudios\utility;

class StringUtil {

	public static function length($str) {
		return strlen($str);
	}

	public static function startsWith($str, $needle) {
		return strpos($str, $needle) === 0;
	}

	public static function endsWith($str, $needle) {
		return $needle === "" || substr($str, -strlen($needle)) === $needle;
	}

	public static function lastIndexOf($str, $needle) {
		return strrpos($str, $needle);
	}

    public static function XORString($text, $key) {
        $ret = '';

        for($i = 0; $i < strlen($text);) {
            for($j = 0; ($j < strlen($key) && $i < strlen($text)); $j++, $i++) {
                $ret .= $text{$i} ^ $key{$j};
            }
        }

        return $ret;
    }
}


text:
require 'kawana/client'

module Kawana
  VERSION="0.0.0"
end


text:
<head>
  <link href="https://gmpg.org/xfn/11" rel="profile">
  <meta https-equiv="X-UA-Compatible" content="IE=edge">
  <meta https-equiv="content-type" content="text/html; charset=utf-8">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>
    {% if page.title == "Home" %}
      {{ site.title }} · {{ site.tagline }}
    {% else %}
      {{ page.title }} · {{ site.title }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="{{ site.url }}/assets/css/poole.css">
  <link rel="stylesheet" href="{{ site.url }}/assets/css/syntax.css">
  <link rel="stylesheet" href="{{ site.url }}/assets/css/hyde.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>


text:
package pzubaha.list;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Chapter_005. Collection. Pro.
 * List.
 * Find loop in the list.
 * <p>
 * Contains solution of task 161.
 * Test class.
 * Created 10.11.2017.
 *
 * @author Pavel Zubaha (mailto:Apximar@gmail.com)
 * @version 1
 */
public class LinkedListLoopTest {
    /**
     * Tested instances and variables.
     */
    private LinkedListLoop lLL = new LinkedListLoop();
    private LinkedListLoop.Node node1 = lLL.makeNode();
    private LinkedListLoop.Node node2 = lLL.makeNode();
    private LinkedListLoop.Node node3 = lLL.makeNode();
    private LinkedListLoop.Node node4 = lLL.makeNode();

    /**
     * Setup before testing.
     */
    @Before
    public void setUp() {
        lLL.setHead(node1);
        node1.connect(node2);
        node2.connect(node3);
        node3.connect(node4);
    }

    /**
     * Test isLoop method.
     */
    @Test
    public void whenTryIsLoopThenReturnedTrueIfThereIsALoopInTheList() {
        assertTrue(!lLL.isLoop());
        node4.connect(node1);
        assertTrue(lLL.isLoop());
    }
}


text:
package validate

import (
	"fmt"
	"log"
	"reflect"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/spec"
	"github.com/go-openapi/strfmt"
)

// An EntityValidator is an interface for things that can validate entities
type EntityValidator interface {
	Validate(interface{}) *Result
}

type valueValidator interface {
	SetPath(path string)
	Applies(interface{}, reflect.Kind) bool
	Validate(interface{}) *Result
}

type itemsValidator struct {
	items        *spec.Items
	root         interface{}
	path         string
	in           string
	validators   []valueValidator
	KnownFormats strfmt.Registry
}

func newItemsValidator(path, in string, items *spec.Items, root interface{}, formats strfmt.Registry) *itemsValidator {
	iv := &itemsValidator{path: path, in: in, items: items, root: root, KnownFormats: formats}
	iv.validators = []valueValidator{
		&typeValidator{
			Type:   spec.StringOrArray([]string{items.Type}),
			Format: items.Format,
			In:     in,
			Path:   path,
		},
		iv.stringValidator(),
		iv.formatValidator(),
		iv.numberValidator(),
		iv.sliceValidator(),
		iv.commonValidator(),
	}
	return iv
}

func (i *itemsValidator) Validate(index int, data interface{}) *Result {
	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()
	mainResult := new(Result)
	path := fmt.Sprintf("%s.%d", i.path, index)

	for _, validator := range i.validators {
		validator.SetPath(path)
		if validator.Applies(i.root, kind) {
			result := validator.Validate(data)
			mainResult.Merge(result)
			mainResult.Inc()
			if result != nil && result.HasErrors() {
				return mainResult
			}
		}
	}
	return mainResult
}

func (i *itemsValidator) commonValidator() valueValidator {
	return &basicCommonValidator{
		In:      i.in,
		Default: i.items.Default,
		Enum:    i.items.Enum,
	}
}

func (i *itemsValidator) sliceValidator() valueValidator {
	return &basicSliceValidator{
		In:           i.in,
		Default:      i.items.Default,
		MaxItems:     i.items.MaxItems,
		MinItems:     i.items.MinItems,
		UniqueItems:  i.items.UniqueItems,
		Source:       i.root,
		Items:        i.items.Items,
		KnownFormats: i.KnownFormats,
	}
}

func (i *itemsValidator) numberValidator() valueValidator {
	return &numberValidator{
		In:               i.in,
		Default:          i.items.Default,
		MultipleOf:       i.items.MultipleOf,
		Maximum:          i.items.Maximum,
		ExclusiveMaximum: i.items.ExclusiveMaximum,
		Minimum:          i.items.Minimum,
		ExclusiveMinimum: i.items.ExclusiveMinimum,
	}
}

func (i *itemsValidator) stringValidator() valueValidator {
	return &stringValidator{
		In:              i.in,
		Default:         i.items.Default,
		MaxLength:       i.items.MaxLength,
		MinLength:       i.items.MinLength,
		Pattern:         i.items.Pattern,
		AllowEmptyValue: false,
	}
}

func (i *itemsValidator) formatValidator() valueValidator {
	return &formatValidator{
		In: i.in,
		//Default:      i.items.Default,
		Format:       i.items.Format,
		KnownFormats: i.KnownFormats,
	}
}

type basicCommonValidator struct {
	Path    string
	In      string
	Default interface{}
	Enum    []interface{}
}

func (b *basicCommonValidator) SetPath(path string) {
	b.Path = path
}

func (b *basicCommonValidator) Applies(source interface{}, kind reflect.Kind) bool {
	switch source.(type) {
	case *spec.Parameter, *spec.Schema, *spec.Header:
		return true
	}
	return false
}

func (b *basicCommonValidator) Validate(data interface{}) (res *Result) {
	if len(b.Enum) > 0 {
		for _, enumValue := range b.Enum {
			actualType := reflect.TypeOf(enumValue)
			if actualType == nil {
				continue
			}
			expectedValue := reflect.ValueOf(data)
			if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
				if reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), enumValue) {
					return nil
				}
			}
		}
		return sErr(errors.EnumFail(b.Path, b.In, data, b.Enum))
	}
	return nil
}

// A HeaderValidator has very limited subset of validations to apply
type HeaderValidator struct {
	name         string
	header       *spec.Header
	validators   []valueValidator
	KnownFormats strfmt.Registry
}

// NewHeaderValidator creates a new header validator object
func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry) *HeaderValidator {
	p := &HeaderValidator{name: name, header: header, KnownFormats: formats}
	p.validators = []valueValidator{
		&typeValidator{
			Type:   spec.StringOrArray([]string{header.Type}),
			Format: header.Format,
			In:     "header",
			Path:   name,
		},
		p.stringValidator(),
		p.formatValidator(),
		p.numberValidator(),
		p.sliceValidator(),
		p.commonValidator(),
	}
	return p
}

// Validate the value of the header against its schema
func (p *HeaderValidator) Validate(data interface{}) *Result {
	result := new(Result)
	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()

	for _, validator := range p.validators {
		if validator.Applies(p.header, kind) {
			if err := validator.Validate(data); err != nil {
				result.Merge(err)
				if err.HasErrors() {
					return result
				}
			}
		}
	}
	return nil
}

func (p *HeaderValidator) commonValidator() valueValidator {
	return &basicCommonValidator{
		Path:    p.name,
		In:      "response",
		Default: p.header.Default,
		Enum:    p.header.Enum,
	}
}

func (p *HeaderValidator) sliceValidator() valueValidator {
	return &basicSliceValidator{
		Path:         p.name,
		In:           "response",
		Default:      p.header.Default,
		MaxItems:     p.header.MaxItems,
		MinItems:     p.header.MinItems,
		UniqueItems:  p.header.UniqueItems,
		Items:        p.header.Items,
		Source:       p.header,
		KnownFormats: p.KnownFormats,
	}
}

func (p *HeaderValidator) numberValidator() valueValidator {
	return &numberValidator{
		Path:             p.name,
		In:               "response",
		Default:          p.header.Default,
		MultipleOf:       p.header.MultipleOf,
		Maximum:          p.header.Maximum,
		ExclusiveMaximum: p.header.ExclusiveMaximum,
		Minimum:          p.header.Minimum,
		ExclusiveMinimum: p.header.ExclusiveMinimum,
	}
}

func (p *HeaderValidator) stringValidator() valueValidator {
	return &stringValidator{
		Path:            p.name,
		In:              "response",
		Default:         p.header.Default,
		Required:        true,
		MaxLength:       p.header.MaxLength,
		MinLength:       p.header.MinLength,
		Pattern:         p.header.Pattern,
		AllowEmptyValue: false,
	}
}

func (p *HeaderValidator) formatValidator() valueValidator {
	return &formatValidator{
		Path: p.name,
		In:   "response",
		//Default:      p.header.Default,
		Format:       p.header.Format,
		KnownFormats: p.KnownFormats,
	}
}

// A ParamValidator has very limited subset of validations to apply
type ParamValidator struct {
	param        *spec.Parameter
	validators   []valueValidator
	KnownFormats strfmt.Registry
}

// NewParamValidator creates a new param validator object
func NewParamValidator(param *spec.Parameter, formats strfmt.Registry) *ParamValidator {
	p := &ParamValidator{param: param, KnownFormats: formats}
	p.validators = []valueValidator{
		&typeValidator{
			Type:   spec.StringOrArray([]string{param.Type}),
			Format: param.Format,
			In:     param.In,
			Path:   param.Name,
		},
		p.stringValidator(),
		p.formatValidator(),
		p.numberValidator(),
		p.sliceValidator(),
		p.commonValidator(),
	}
	return p
}

// Validate the data against the description of the parameter
func (p *ParamValidator) Validate(data interface{}) *Result {
	result := new(Result)
	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()

	// TODO: validate type
	for _, validator := range p.validators {
		if validator.Applies(p.param, kind) {
			if err := validator.Validate(data); err != nil {
				result.Merge(err)
				if err.HasErrors() {
					return result
				}
			}
		}
	}
	return nil
}

func (p *ParamValidator) commonValidator() valueValidator {
	return &basicCommonValidator{
		Path:    p.param.Name,
		In:      p.param.In,
		Default: p.param.Default,
		Enum:    p.param.Enum,
	}
}

func (p *ParamValidator) sliceValidator() valueValidator {
	return &basicSliceValidator{
		Path:         p.param.Name,
		In:           p.param.In,
		Default:      p.param.Default,
		MaxItems:     p.param.MaxItems,
		MinItems:     p.param.MinItems,
		UniqueItems:  p.param.UniqueItems,
		Items:        p.param.Items,
		Source:       p.param,
		KnownFormats: p.KnownFormats,
	}
}

func (p *ParamValidator) numberValidator() valueValidator {
	return &numberValidator{
		Path:             p.param.Name,
		In:               p.param.In,
		Default:          p.param.Default,
		MultipleOf:       p.param.MultipleOf,
		Maximum:          p.param.Maximum,
		ExclusiveMaximum: p.param.ExclusiveMaximum,
		Minimum:          p.param.Minimum,
		ExclusiveMinimum: p.param.ExclusiveMinimum,
	}
}

func (p *ParamValidator) stringValidator() valueValidator {
	return &stringValidator{
		Path:            p.param.Name,
		In:              p.param.In,
		Default:         p.param.Default,
		AllowEmptyValue: p.param.AllowEmptyValue,
		Required:        p.param.Required,
		MaxLength:       p.param.MaxLength,
		MinLength:       p.param.MinLength,
		Pattern:         p.param.Pattern,
	}
}

func (p *ParamValidator) formatValidator() valueValidator {
	return &formatValidator{
		Path: p.param.Name,
		In:   p.param.In,
		//Default:      p.param.Default,
		Format:       p.param.Format,
		KnownFormats: p.KnownFormats,
	}
}

type basicSliceValidator struct {
	Path           string
	In             string
	Default        interface{}
	MaxItems       *int64
	MinItems       *int64
	UniqueItems    bool
	Items          *spec.Items
	Source         interface{}
	itemsValidator *itemsValidator
	KnownFormats   strfmt.Registry
}

func (s *basicSliceValidator) SetPath(path string) {
	s.Path = path
}

func (s *basicSliceValidator) Applies(source interface{}, kind reflect.Kind) bool {
	switch source.(type) {
	case *spec.Parameter, *spec.Items, *spec.Header:
		return kind == reflect.Slice
	}
	return false
}

func sErr(err errors.Error) *Result {
	return &Result{Errors: []error{err}}
}

func (s *basicSliceValidator) Validate(data interface{}) *Result {
	val := reflect.ValueOf(data)

	size := int64(val.Len())
	if s.MinItems != nil {
		if err := MinItems(s.Path, s.In, size, *s.MinItems); err != nil {
			return sErr(err)
		}
	}

	if s.MaxItems != nil {
		if err := MaxItems(s.Path, s.In, size, *s.MaxItems); err != nil {
			return sErr(err)
		}
	}

	if s.UniqueItems {
		if err := UniqueItems(s.Path, s.In, data); err != nil {
			return sErr(err)
		}
	}

	if s.itemsValidator == nil && s.Items != nil {
		s.itemsValidator = newItemsValidator(s.Path, s.In, s.Items, s.Source, s.KnownFormats)
	}

	if s.itemsValidator != nil {
		for i := 0; i < int(size); i++ {
			ele := val.Index(i)
			if err := s.itemsValidator.Validate(i, ele.Interface()); err != nil && err.HasErrors() {
				return err
			}
		}
	}
	return nil
}

func (s *basicSliceValidator) hasDuplicates(value reflect.Value, size int) bool {
	dict := make(map[interface{}]struct{})
	for i := 0; i < size; i++ {
		ele := value.Index(i)
		if _, ok := dict[ele.Interface()]; ok {
			return true
		}
		dict[ele.Interface()] = struct{}{}
	}
	return false
}

type numberValidator struct {
	Path             string
	In               string
	Default          interface{}
	MultipleOf       *float64
	Maximum          *float64
	ExclusiveMaximum bool
	Minimum          *float64
	ExclusiveMinimum bool
}

func (n *numberValidator) SetPath(path string) {
	n.Path = path
}

func (n *numberValidator) Applies(source interface{}, kind reflect.Kind) bool {
	switch source.(type) {
	case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header:
		isInt := kind >= reflect.Int && kind <= reflect.Uint64
		isFloat := kind == reflect.Float32 || kind == reflect.Float64
		r := isInt || isFloat
		if Debug {
			log.Printf("schema props validator for %q applies %t for %T (kind: %v)\n", n.Path, r, source, kind)
		}
		return r
	}
	if Debug {
		log.Printf("schema props validator for %q applies %t for %T (kind: %v)\n", n.Path, false, source, kind)
	}
	return false
}

func (n *numberValidator) convertToFloat(val interface{}) float64 {
	v := reflect.ValueOf(val)
	switch v.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(v.Int())
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return float64(v.Uint())
	case reflect.Float32, reflect.Float64:
		return v.Float()
	}
	return 0
}

func (n *numberValidator) Validate(val interface{}) *Result {
	data := n.convertToFloat(val)

	if n.MultipleOf != nil {
		if err := MultipleOf(n.Path, n.In, data, *n.MultipleOf); err != nil {
			return sErr(err)
		}
	}
	if n.Maximum != nil {
		if err := Maximum(n.Path, n.In, data, *n.Maximum, n.ExclusiveMaximum); err != nil {
			return sErr(err)
		}
	}
	if n.Minimum != nil {
		if err := Minimum(n.Path, n.In, data, *n.Minimum, n.ExclusiveMinimum); err != nil {
			return sErr(err)
		}
	}
	result := new(Result)
	result.Inc()
	return result
}

type stringValidator struct {
	Default         interface{}
	Required        bool
	AllowEmptyValue bool
	MaxLength       *int64
	MinLength       *int64
	Pattern         string
	Path            string
	In              string
}

func (s *stringValidator) SetPath(path string) {
	s.Path = path
}

func (s *stringValidator) Applies(source interface{}, kind reflect.Kind) bool {
	switch source.(type) {
	case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header:
		r := kind == reflect.String
		if Debug {
			log.Printf("string validator for %q applies %t for %T (kind: %v)\n", s.Path, r, source, kind)
		}
		return r
	}
	if Debug {
		log.Printf("string validator for %q applies %t for %T (kind: %v)\n", s.Path, false, source, kind)
	}
	return false
}

func (s *stringValidator) Validate(val interface{}) *Result {
	data := val.(string)

	if s.Required && !s.AllowEmptyValue && (s.Default == nil || s.Default == "") {
		if err := RequiredString(s.Path, s.In, data); err != nil {
			return sErr(err)
		}
	}

	if s.MaxLength != nil {
		if err := MaxLength(s.Path, s.In, data, *s.MaxLength); err != nil {
			return sErr(err)
		}
	}

	if s.MinLength != nil {
		if err := MinLength(s.Path, s.In, data, *s.MinLength); err != nil {
			return sErr(err)
		}
	}

	if s.Pattern != "" {
		if err := Pattern(s.Path, s.In, data, s.Pattern); err != nil {
			return sErr(err)
		}
	}
	return nil
}


text:
<?php

namespace PlentymarketsAdapter\ReadApi\Account;

use PlentymarketsAdapter\ReadApi\ApiAbstract;

class ContactClass extends ApiAbstract
{
    /**
     * @return array
     */
    public function findAll(): array
    {
        return $this->client->request('GET', 'accounts/contacts/classes');
    }
}


text:
package com.linkedin.parseq.promise;

/**
 * A listener that can be registered with a promise. When that promise is resolved
 * (either it has a value or an error) the {@link #onResolved(Promise)} method will
 * be invoked. The instance passed in to {@code onResolved} method does not have to
 * be the exact same instance the {@code PromiseListener} was registered with.
 *
 * @author Chris Pettitt (cpettitt@linkedin.com)
 * @author Chi Chan (ckchan@linkedin.com)
 * @author Jaroslaw Odzga (jodzga@linkedin.com)
 * @see Promise#addListener(PromiseListener)
 */
@FunctionalInterface
public interface PromiseListener<P> {
  /**
   * A callback method that is invoked when the promise completes. The code
   * in this method should not block.
   *
   * @param promise the promise containing result. It is not guaranteed that it is exact same
   * instance the {@code PromiseListener} was registered with.
   */
  void onResolved(Promise<P> promise);
}


text:
<?php
/**
 * Integrates this theme with SiteOrigin panels page builder.
 *
 * @package influence
 * @since 1.0
 * @license GPL 2.0
 */

/**
 * Adds default page layouts
 *
 * @param $layouts
 */
function influence_prebuilt_page_layouts($layouts){
	$layouts['basic-home'] = array (
		'name' => __('Basic Home Page', 'influence'),
		'widgets' =>
			array (
				0 =>
					array (
						'features' =>
							array (
								0 =>
									array (
										'container_color' => '',
										'icon' => 'fontawesome-bullhorn',
										'icon_color' => '',
										'icon_image' => '',
										'title' => 'Lorem Ipsum Dolor',
										'text' => 'Curabitur fermentum arcu et elit lacinia rutrum. Mauris viverra mi sit amet nisi laoreet, nec luctus nulla scelerisque. Curabitur bibendum nec lacus at mattis. Ut vitae egestas tortor. Vivamus ex augue, tincidunt eu mauris in, semper molestie massa.',
										'more_text' => '',
										'more_url' => '',
									),
								1 =>
									array (
										'container_color' => '',
										'icon' => 'fontawesome-user',
										'icon_color' => '',
										'icon_image' => '',
										'title' => 'Lorem Ipsum Dolor',
										'text' => 'Curabitur fermentum arcu et elit lacinia rutrum. Mauris viverra mi sit amet nisi laoreet, nec luctus nulla scelerisque. Curabitur bibendum nec lacus at mattis. Ut vitae egestas tortor. Vivamus ex augue, tincidunt eu mauris in, semper molestie massa.',
										'more_text' => '',
										'more_url' => '',
									),
								2 =>
									array (
										'container_color' => '',
										'icon' => 'fontawesome-anchor',
										'icon_color' => '',
										'icon_image' => '',
										'title' => 'Lorem Ipsum Dolor',
										'text' => 'Curabitur fermentum arcu et elit lacinia rutrum. Mauris viverra mi sit amet nisi laoreet, nec luctus nulla scelerisque. Curabitur bibendum nec lacus at mattis. Ut vitae egestas tortor. Vivamus ex augue, tincidunt eu mauris in, semper molestie massa.',
										'more_text' => '',
										'more_url' => '',
									),
							),
						'container_shape' => 'rounded-hex',
						'container_size' => '84',
						'icon_size' => '24',
						'per_row' => '3',
						'responsive' => '1',
						'title_link' => '',
						'icon_link' => '',
						'new_window' => '',
						'info' =>
							array (
								'grid' => '0',
								'cell' => '0',
								'id' => '0',
								'class' => 'SiteOrigin_Widget_Features_Widget',
							),
					),
				1 =>
					array (
						'title' => 'Curabitur Bibendum Nec Lacus ',
						'sub_title' => 'Vivamus ex augue, tincidunt eu mauris in, semper molestie massa.',
						'design' =>
							array (
								'background_color' => '',
								'border_color' => '',
							),
						'button' =>
							array (
								'text' => 'More Info',
								'url' => '#',
								'button_icon' =>
									array (
										'icon_selected' => '',
										'icon_color' => '',
										'icon' => '',
									),
								'design' =>
									array (
										'align' => 'center',
										'theme' => 'atom',
										'button_color' => '',
										'text_color' => '',
										'hover' => '1',
										'font_size' => '1',
										'rounding' => '0.25',
										'padding' => '1',
									),
								'attributes' =>
									array (
										'id' => '',
										'title' => '',
										'onclick' => '',
									),
								'new_window' => '',
							),
						'info' =>
							array (
								'grid' => '0',
								'cell' => '0',
								'id' => '1',
								'class' => 'SiteOrigin_Widget_Cta_Widget',
							),
					),
				2 =>
					array (
						'title' => '',
						'text' => 'Cras et iaculis arcu. Etiam semper dictum est, quis placerat nisi consequat eu. Morbi id lacinia turpis. Curabitur fermentum arcu et elit lacinia rutrum. Mauris viverra mi sit amet nisi laoreet, nec luctus nulla scelerisque. Curabitur bibendum nec lacus at mattis. Ut vitae egestas tortor. Vivamus ex augue, tincidunt eu mauris in, semper molestie massa.

Nunc nec auctor risus. Donec mollis mi a finibus fermentum. Suspendisse ac ornare turpis. Integer mollis eros a dapibus congue. Vestibulum eu vulputate magna. Nulla urna odio, tincidunt quis est et, mattis volutpat enim. Cras mollis orci massa, id pellentesque felis sodales at. Aenean risus est, rhoncus a enim sit amet, auctor cursus augue.',
						'filter' => '1',
						'info' =>
							array (
								'grid' => '1',
								'cell' => '0',
								'id' => '2',
								'class' => 'WP_Widget_Text',
							),
					),
				3 =>
					array (
						'image' => false,
						'size' => 'large',
						'title' => '',
						'alt' => '',
						'url' => '',
						'bound' => '1',
						'new_window' => '',
						'info' =>
							array (
								'grid' => '1',
								'cell' => '1',
								'id' => '3',
								'class' => 'SiteOrigin_Widget_Image_Widget',
							),
					),
			),
		'grids' =>
			array (
				0 =>
					array (
						'cells' => '1',
					),
				1 =>
					array (
						'cells' => '2',
					),
			),
		'grid_cells' =>
			array (
				0 =>
					array (
						'weight' => '1',
						'grid' => '0',
					),
				1 =>
					array (
						'weight' => '0.5',
						'grid' => '1',
					),
				2 =>
					array (
						'weight' => '0.5',
						'grid' => '1',
					),
			),
	);

	return $layouts;
}
add_filter('siteorigin_panels_prebuilt_layouts', 'influence_prebuilt_page_layouts');

/**
 * Display a special form for missing widgets.
 *
 * @param $widget
 * @param $instance
 *
 * @return string
 */
function influence_missing_widget_forms($form, $widget, $instance){

	if( preg_match('/SiteOrigin_Widget_([A-Za-z]+)_Widget/', $widget, $matches) ) {
		$form = '

'
			. __('This widget uses the SiteOrigin Widgets Bundle plugin. A free plugin that gives you a lot of widgets to use in your Page Builder pages.', 'influence')
			. '
'
			. '
' . __('Install Plugin', 'influence') . ' '
		    . ''.__('Free', 'influence').''
			.'
';
	}

	return $form;
}
add_filter('siteorigin_panels_missing_widget_form', 'influence_missing_widget_forms', 10, 3);

/**
 * Add the title and description for any known missing widgets.
 *
 * @param $widget
 * @param $data
 *
 * @return array
 */
function influence_missing_widget_data($data, $widget){

	switch($widget) {
		case 'SiteOrigin_Widget_Features_Widget' :
			$data = array(
				'title' => __('Features', 'influence'),
				'description' => __('Display a list of features and icons.', 'influence'),
			);
			break;
	}

	return $data;
}
add_filter('siteorigin_panels_missing_widget_data', 'influence_missing_widget_data', 10, 2);


text:
namespace Affecto.IdentityManagement.Querying.Data
{
    public enum AccountType
    {
        ActiveDirectory,
        Federated,
        Password
    }
}


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                       */
/*    This file is part of the HiGHS linear optimization suite           */
/*                                                                       */
/*    Written and engineered 2008-2020 at the University of Edinburgh    */
/*                                                                       */
/*    Available as open-source under the MIT License                     */
/*                                                                       */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file simplex/HDual.h
 * @brief Dual simplex solver for HiGHS
 * @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier
 */
#ifndef SIMPLEX_HDUAL_H_
#define SIMPLEX_HDUAL_H_

#include <set>
#include <string>
#include <vector>

#include "HConfig.h"
#include "lp_data/HighsModelObject.h"
#include "simplex/HCrash.h"
#include "simplex/HDualRHS.h"
#include "simplex/HDualRow.h"
#include "simplex/HSimplex.h"
#include "simplex/HVector.h"

class HFactor;

/**
 * Limit on the number of column slices for parallel calculations. SIP uses
 * num_threads-2 slices; PAMI uses num_threads-1 slices
 */
const int HIGHS_SLICED_LIMIT =
    HIGHS_THREAD_LIMIT;  // Was 100, but can't see why this should be higher
                         // than HIGHS_THREAD_LIMIT;

/**
 * Parameters controlling number of Devex iterations.
 *
 * There is a new Devex framework if either
 *
 * 1) The weight inaccuracy ratio exceeds maxAllowedDevexWeightRatio
 *
 * 2) There have been max(minAbsNumberDevexIterations,
 * numRow/minRlvNumberDevexIterations) Devex iterations
 */
const int minAbsNumberDevexIterations = 25;
const double minRlvNumberDevexIterations = 1e-2;
const double maxAllowedDevexWeightRatio = 3.0;

/**
 * Multiplier used in running average calculations
 */
const double runningAverageMu = 0.05;

/**
 * Candidate persistence cut-off in PAMI
 */
const double pami_cutoff = 0.95;

/**
 * @brief Dual simplex solver for HiGHS
 */
class HDual {
 public:
  HDual(HighsModelObject& model_object)
      : workHMO(model_object), dualRow(model_object), dualRHS(model_object) {
    dualRow.setup();
    for (int i = 0; i < HIGHS_SLICED_LIMIT; i++)
      slice_dualRow.push_back(HDualRow(model_object));
    dualRHS.setup();
  }

  /**
   * @brief Solve a model instance
   */
  HighsStatus solve();

  const SimplexAlgorithm algorithm = SimplexAlgorithm::DUAL;

 public:
  /**
   * @brief Set solver options from simplex options
   */
  void options();
  /**
   * @brief Initialise a dual simplex instance
   *
   * Copy dimensions and pointers to matrix, factor and solver-related
   * model data, plus tolerances. Sets up local std::vectors (columnDSE,
   * columnBFRT, column, row_ep and row_ap), scalars for their average
   * density and buffers for dualRow and dualRHS.
   */
  void init();

  /**
   * @brief Initialise parallel aspects of a dual simplex instance
   *
   * Sets up data structures for SIP or PAMI
   */
  void initParallel();

  /**
   * @brief Initialise matrix slices and slices of row_ap or dualRow for SIP or
   * PAMI
   *
   * TODO generalise call slice_matrix[i].setup_lgBs so slice can be
   * used with non-logical initial basis
   */
  void initSlice(
      const int init_sliced_num  //!< Ideal number of slices - true number
                                 //!< is modified in light of limits
  );

  /**
   * @brief Perform Phase 1 dual simplex iterations
   */
  void solvePhase1();

  /**
   * @brief Perform Phase 2 dual simplex iterations
   */
  void solvePhase2();

  /**
   * @brief Reinvert if INVERT not fresh, then recompute dual and primal values
   *
   * Also collects primal infeasibilities and computes the dual objective value
   */

  void rebuild();

  /**
   * @brief Remove perturbation and recompute the dual solution
   *
   * Also collects primal infeasibilities and computes the dual objective value
   */
  void cleanup();

  /**
   * @brief Perform a single serial dual simplex iteration
   *
   * All the methods it calls have as their first line "if (invertHint)
   * return;", where invertHint is, for example, set to 1 when CHUZR
   * finds no candidate. This causes a break from the inner loop of
   * solve_phase% and, hence, a call to rebuild().
   */
  void iterate();

  /**
   * @brief Perform a single SIP dual simplex iteration
   */
  void iterateTasks();

  /**
   * @brief Perform a single PAMI dual simplex iteration - source code in
   * HDualMulti.cpp
   */
  void iterateMulti();  // in HDualMulti.cpp

  /**
   * @brief Pass the data for the serial iteration analysis, report and rebuild
   * report
   */
  void iterationAnalysisData();

  /**
   * @brief Perform the serial iteration analysis
   */
  void iterationAnalysis();

  /**
   * @brief Pass the data for the PAMI iteration analysis for a minor iteration,
   * report and rebuild report
   */
  void iterationAnalysisMinorData();

  /**
   * @brief Perform the PAMI iteration analysis for a minor iteration
   */
  void iterationAnalysisMinor();

  /**
   * @brief Pass the data for the PAMI iteration analysis for a major iteration
   */
  void iterationAnalysisMajorData();

  /**
   * @brief Perform the PAMI iteration analysis for a major iteration
   */
  void iterationAnalysisMajor();

  /**
   * @brief Single line report after rebuild
   */
  void reportRebuild(const int rebuild_invert_hint = -1);

  /**
   * @brief Choose the index of a good row to leave the basis (CHUZR)
   */
  void chooseRow();

  /**
   * @brief Determine whether the updated_edge_weight is accurate enough to
   * be accepted, and update the analysis of weight errors
   */
  bool acceptDualSteepestEdgeWeight(const double updated_edge_weight);

  /**
   * @brief Determine whether the updated_edge_weight error should trigger a new
   * Devex framework
   */
  bool newDevexFramework(const double updated_edge_weight);

  /**
   * @brief Compute pivot row (PRICE) and choose the index of a good column to
   * enter the basis (CHUZC)
   */
  void chooseColumn(HVector* row_ep);

  /**
   * @brief Choose the index of a good column to enter the basis (CHUZC) by
   * exploiting slices of the pivotal row - for SIP and PAMI
   */
  void chooseColumnSlice(HVector* row_ep);

  /**
   * @brief Compute the pivotal column (FTRAN)
   */
  void updateFtran();

  /**
   * @brief Compute the RHS changes corresponding to the BFRT
   * (FTRAN-BFRT)
   */
  void updateFtranBFRT();

  /**
   * @brief Compute the std::vector required to update DSE weights - being
   * FTRAN applied to the pivotal column (FTRAN-DSE)
   */
  void updateFtranDSE(HVector* DSE_Vector  //!< Pivotal column as RHS for FTRAN
  );
  /**
   * @brief Compare the pivot value computed row-wise and column-wise
   * and determine whether reinversion is advisable
   */
  void updateVerify();

  /**
   * @brief Update the dual values
   */
  void updateDual();

  /**
   * @brief Update the primal values and any edge weights
   */
  void updatePrimal(HVector* DSE_Vector  //!< FTRANned pivotal column
  );

  /**
   * @brief Update the basic and nonbasic variables, iteration count,
   * invertible representation of the basis matrix and row-wise
   * representation of the nonbasic columns, delete the Freelist entry
   * for the entering column, update the primal value for the row
   * where the basis change has occurred, and set the corresponding
   * primal infeasibility value in dualRHS.work_infeasibility, and
   * then determine whether to reinvert according to the synthetic
   * clock
   */
  void updatePivots();

  /**
   * @brief Initialise a Devex framework: reference set is all basic
   * variables
   */
  void initialiseDevexFramework(const bool parallel = false);

  /**
   * @brief Interpret the dual edge weight strategy as setting of a mode and
   * other actions
   */
  void interpretDualEdgeWeightStrategy(
      const int simplex_dual_edge_weight_strategy);

  bool reachedExactDualObjectiveValueUpperBound();
  double computeExactDualObjectiveValue();

  /**
   * @brief PAMI: Choose the indices of a good set of rows to leave the
   * basis (CHUZR)
   */
  void majorChooseRow();

  /**
   * @brief PAMI: Perform multiple BTRAN
   */
  void majorChooseRowBtran();

  /**
   * @brief PAMI: Choose the index (from the set of indices) of a good
   * row to leave the basis (CHUZR-MI)
   */
  void minorChooseRow();

  /**
   * @brief PAMI: Update the data during minor iterations
   */
  void minorUpdate();

  /**
   * @brief PAMI: Update the dual values during minor iterations
   */
  void minorUpdateDual();

  /**
   * @brief PAMI: Update the primal values during minor iterations
   */
  void minorUpdatePrimal();

  /**
   * @brief PAMI: Perform a basis change during minor iterations
   */
  void minorUpdatePivots();

  /**
   * @brief PAMI: Update the tableau rows during minor iterations
   */
  void minorUpdateRows();

  /**
   * @brief PAMI: Initialise a new Devex framework during minor iterations
   */
  void minorInitialiseDevexFramework();

  /**
   * @brief PAMI: Perform updates after a set of minor iterations
   */
  void majorUpdate();

  /**
   * @brief PAMI: Prepare for the FTRANs after a set of minor iterations
   */
  void majorUpdateFtranPrepare();

  /**
   * @brief PAMI: Perform the parallel part of multiple FTRANs after a
   * set of minor iterations
   */
  void majorUpdateFtranParallel();

  /**
   * @brief PAMI: Perform the final part of multiple FTRANs after a set
   * of minor iterations
   */
  void majorUpdateFtranFinal();

  /**
   * @brief PAMI: Update the primal values after a set of minor
   * iterations
   */
  void majorUpdatePrimal();

  /**
   * @brief PAMI: Update the invertible representation of the basis
   * matrix after a set of minor iterations
   */
  void majorUpdateFactor();

  /**
   * @brief PAMI: Roll back some iterations if numerical trouble
   * detected when updating the invertible representation of the basis
   * matrix after a set of minor iterations
   */
  void majorRollback();

  // private:
  HighsStatus returnFromSolve(const HighsStatus return_status);
  void saveDualRay();
  bool getNonsingularInverse();
  bool getBacktrackingBasis(vector<double>& scattered_edge_weights);
  void putBacktrackingBasis();
  void putBacktrackingBasis(const vector<int>& basicIndex_before_compute_factor,
                            const vector<double>& scattered_edge_weights);

  void assessPhase1Optimality();
  void exitPhase1ResetDuals();
  void reportOnPossibleLpDualInfeasibility();

  bool checkNonUnitWeightError(std::string message);
  bool dualInfoOk(const HighsLp& lp);
  bool bailoutReturn();
  bool bailoutOnTimeIterations();
  bool bailoutOnDualObjective();

  bool solve_bailout;  //!< Set true if control is to be returned immediately to
                       //!< calling function

  // Devex scalars
  int num_devex_iterations =
      0;  //!< Number of Devex iterations with the current framework
  bool new_devex_framework = false;  //!< Set a new Devex framework
  bool minor_new_devex_framework =
      false;  //!< Set a new Devex framework in PAMI minor iterations

  // Model
  HighsModelObject& workHMO;
  int solver_num_row;
  int solver_num_col;
  int solver_num_tot;

  const HMatrix* matrix;
  const HFactor* factor;
  HighsSimplexAnalysis* analysis;

  const int* jMove;
  const double* workRange;
  const double* baseLower;
  const double* baseUpper;
  double* baseValue;
  double* workDual;
  double* workValue;
  double* colLower;
  double* colUpper;
  double* rowLower;
  double* rowUpper;
  int* nonbasicFlag;

  // Options
  DualEdgeWeightMode dual_edge_weight_mode;
  bool initialise_dual_steepest_edge_weights;
  bool allow_dual_steepest_edge_to_devex_switch;

  const double min_dual_steepest_edge_weight = 1e-4;

  double Tp;  // Tolerance for primal
  double primal_feasibility_tolerance;

  double Td;  // Tolerance for dual
  double dual_feasibility_tolerance;
  double dual_objective_value_upper_bound;

  int solvePhase;
  int invertHint;

  HVector row_ep;
  HVector row_ap;
  HVector col_aq;
  HVector col_BFRT;
  HVector col_DSE;

  HDualRow dualRow;

  // Solving related buffers
  int dualInfeasCount;

  HDualRHS dualRHS;

  // Simplex pivotal information
  int rowOut;
  int columnOut;
  int sourceOut;  // -1 from small to lower, +1 to upper
  int columnIn;
  double deltaPrimal;
  double thetaDual;
  double thetaPrimal;
  double alpha;
  double alphaRow;
  double numericalTrouble;
  // (Local) value of computed weight
  double computed_edge_weight;

  bool check_invert_condition = false;

  // Partitioned coefficient matrix
  int slice_num;
  int slice_PRICE;
  int slice_start[HIGHS_SLICED_LIMIT + 1];
  HMatrix slice_matrix[HIGHS_SLICED_LIMIT];
  HVector slice_row_ap[HIGHS_SLICED_LIMIT];
  std::vector<HDualRow> slice_dualRow;

  /**
   * @brief Multiple CHUZR data
   */
  struct MChoice {
    int rowOut;
    double baseValue;
    double baseLower;
    double baseUpper;
    double infeasValue;
    double infeasEdWt;
    double infeasLimit;
    HVector row_ep;
    HVector col_aq;
    HVector col_BFRT;
  };

  /**
   * @brief Multiple minor iteration data
   */
  struct MFinish {
    int moveIn;
    double shiftOut;
    std::vector<int> flipList;

    int rowOut;
    int columnOut;
    int columnIn;
    double alphaRow;
    double thetaPrimal;
    double basicBound;
    double basicValue;
    double EdWt;
    HVector_ptr row_ep;
    HVector_ptr col_aq;
    HVector_ptr col_BFRT;
  };

  int multi_num;
  int multi_chosen;
  int multi_iChoice;
  int multi_nFinish;
  int multi_iteration;
  int multi_chooseAgain;
  MChoice multi_choice[HIGHS_THREAD_LIMIT];
  MFinish multi_finish[HIGHS_THREAD_LIMIT];

#ifdef HiGHSDEV
  const bool rp_reinvert_syntheticClock = false;  // true;//
  const bool rp_numericalTrouble = false;         // true;//
#endif
  const double original_multi_build_syntheticTick_mu = 1.5;
  const double multi_build_syntheticTick_mu = 1.0;
  // original_multi_build_syntheticTick_mu;//
  const double numerical_trouble_tolerance = 1e-7;
  const double original_multi_numerical_trouble_tolerance = 1e-8;
  const double multi_numerical_trouble_tolerance = 1e-7;
  // original_multi_numerical_trouble_tolerance;

  const int synthetic_tick_reinversion_min_update_count = 50;
  const int original_multi_synthetic_tick_reinversion_min_update_count = 201;
  const int multi_synthetic_tick_reinversion_min_update_count =
      synthetic_tick_reinversion_min_update_count;
  // original_multi_synthetic_tick_reinversion_min_update_count;

  double build_syntheticTick;
  double total_syntheticTick;
};

#endif /* SIMPLEX_HDUAL_H_ */


text:
/*
 * Ismet Said Calik
 * http://ismetsaidcalik.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import java.util.Scanner;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

/**
 * This example code demonstrates how to perform simple state control of a GPIO
 * pin on the Raspberry Pi.
 *
 * @author Ismet Said Calik
 */
public class GPIO_Control {
	private static Scanner cmd;
	public static void main(String[] args) throws InterruptedException {

		System.out.println("GPIO Control Example ... started.");
		System.out.println("Use 1 or 0 command!");
		final GpioController gpio = GpioFactory.getInstance();
		final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(
				RaspiPin.GPIO_01, "MyLED", PinState.LOW);
		cmd = new Scanner(System.in);
		while (true) {
			if (cmd.nextInt() == 1) {
				pin.high();
			}
			if (cmd.nextInt() == 0) {
				pin.low();
			} else {
				System.out.println("Use 1 or 0 command!");

			}

		}
	}
}


text:
class AddAnnotatedColumnToGenome < ActiveRecord::Migration
  def change
    add_column :genomes, :annotated, :boolean, default: false
  end
end


text:
<?php
namespace Sensor;

class Watcher
{
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PatientManagement.PatientManagement.Entities;
using PatientManagement.PatientManagement.Repositories;
using Serenity;
using Serenity.Data;
using Serenity.Navigation;
using Serenity.Services;

namespace PatientManagement.Navigation
{
    //public class VisitTypesNavigation : INavigationItemSource
    //{
    //    public List<NavigationItemAttribute> GetItems()
    //    {
    //        var user = (UserDefinition)Authorization.UserDefinition;

    //        var items = new List<NavigationItemAttribute>
    //        {
    //            new NavigationMenuAttribute(506, LocalText.Get("Db.PatientManagement.VisitTypes.EntityPlural"), "fa-stethoscope")
    //        };

    //        var connection = SqlConnections.NewFor<VisitTypesRow>();
    //        var visitTypesFlds = VisitTypesRow.Fields;
    //        //TODO: IsActive Delete Row should be checked here! #119
    //        var visitTypes = connection.List<VisitTypesRow>(visitTypesFlds.TenantId == user.TenantId);

    //        foreach (var visitType in visitTypes)
    //        {
    //            items.Add(new NavigationLinkAttribute(506,
    //                path: LocalText.Get("Db.PatientManagement.VisitTypes.EntityPlural") + "/" + visitType.Name.Replace("/", "//"),
    //                url: "/PatientManagement/Visits?visittype=" + visitType.VisitTypeId,
    //                icon: "fa-circle-o fc-event-droppable " + visitType.BackgroundColor,
    //                permission: "PatientManagement:VisitTypes:Read"
    //            ));
    //        }
    //        return items;
    //    }
    //}
}


text:
import collection.mutable.Stack
import org.scalatest._

class StackSpec extends FlatSpec {

  "A Stack" should "pop values in last-in-first-out order" in {
    val stack = new Stack[Int]
    stack.push(1)
    stack.push(2)
    assert(stack.pop() === 2)
    assert(stack.pop() === 1)
  }

  it should "throw NoSuchElementException if an empty stack is popped" in {
    val emptyStack = new Stack[String]
    intercept[NoSuchElementException] {
      emptyStack.pop()
    }
  }
}


text:
process.env.NODE_ENV = 'test';

const assert = require('chai').assert;
const { suite, test } = require('mocha');
const knex = require('../knex.js');
const { addDatabaseHooks } = require('./utils.js')
suite('favorites migrations', addDatabaseHooks(() => {
  test('favorites columns', (done) => {
    knex('favorites').columnInfo()
      .then((actual) => {
        const expected = {
          id: {
            type: 'integer',
            maxLength: null,
            nullable: false,
            defaultValue: 'nextval(\'favorites_id_seq\'::regclass)'
          },

          coffee_id: {
            type: 'integer',
            maxLength: null,
            nullable: false,
            defaultValue: null
          },

          user_id: {
            type: 'integer',
            maxLength: null,
            nullable: false,
            defaultValue: null
          },

          created_at: {
            type: 'timestamp with time zone',
            maxLength: null,
            nullable: false,
            defaultValue: 'now()'
          },

          updated_at: {
            type: 'timestamp with time zone',
            maxLength: null,
            nullable: false,
            defaultValue: 'now()'
          }
        };

        for (const column in expected) {
          assert.deepEqual(
            actual[column],
            expected[column],
            `Column ${column} is not the same`
          );
        }
        done();
      })
      .catch((err) => {
        done(err);
      });
  });
}));


text:
require "RoboGame/version"
require "RoboGame/console"
require "RoboGame/robot"
require "RoboGame/board"


text:
@interface OKGKScoreWrapper : NSObject<OKScoreProtocol>

@property (nonatomic, strong) GKScore *score;
@property (nonatomic, strong) GKPlayer *player;
// Rank is a read only property of GKScore, and since we are showing social scores ranked against each other, we need a way to store a local rank
@property (nonatomic, strong) NSString *explicitlySetRank;

-(void)setRank:(NSInteger)rank;

@end


text:
INCLUDE(FindPackageHandleStandardArgs)

FIND_PATH(VORBIS_INCLUDE_DIR
    vorbis/codec.h
    PATHS $ENV{VORBISDIR}
    PATH_SUFFIXES include
)

IF(WIN32)
    FIND_LIBRARY(VORBIS_LIBRARIES
        NAMES libvorbis libvorbis-static-mt
        PATHS $ENV{VORBISDIR}
        PATH_SUFFIXES Release
    )
ELSE()
    FIND_LIBRARY(VORBIS_LIBRARIES
        NAMES vorbis
        PATH_SUFFIXES lib
    )
ENDIF(WIN32)

# Handle the REQUIRED argument and set VORBIS_FOUND
IF(NOT WIN32)
    FIND_PACKAGE_HANDLE_STANDARD_ARGS(Vorbis DEFAULT_MSG
    VORBIS_LIBRARIES
    VORBIS_INCLUDE_DIR
)
ELSE()
    FIND_PACKAGE_HANDLE_STANDARD_ARGS(Vorbis DEFAULT_MSG
    VORBIS_LIBRARIES
    VORBIS_INCLUDE_DIR
)
ENDIF(NOT WIN32)

MARK_AS_ADVANCED(
    CLEAR
    VORBIS_INCLUDE_DIR
    VORBIS_LIBRARIES
)


text: define({deleteButton:"[Sil]"});