text:
//   Copyright 2015 Esri
//   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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;

//added references
using ArcGIS.Desktop.Core;                       //access to Project
using ArcGIS.Desktop.Layouts;                    //access to LayoutProjectItem and Layout class
using ArcGIS.Desktop.Framework.Threading.Tasks;  //access to QueuedTask

namespace TextElementAddin
{
    /// <summary>
    /// This sample addin references a text element on a layout and changes it text and placement properties.
    /// </summary>
    /// <remarks>
    /// In Visual Studio:
    /// 1. Select Build --> Build Solution.
    /// 2. Click the Start button to fire up ArcGIS Pro.
    /// In ArcGIS Pro
    /// 3. Create a new project.
    /// 4. Insert a new layout called "Layout".
    /// 5. Insert a new text element called "Text".
    /// 6. Click ADD-IN Tab --> UpdateText
    /// </remarks>
    internal class UpdateText : Button
    {
        async protected override void OnClick()
        {
            //Reference a layout in the project called "Layout"
            LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout"));

            //Update all the text properties at once within a single task
            await QueuedTask.Run(() =>
            {
                var lyt = layoutItem.GetLayout();  //Each layoutItem has metadata and an associated Layout object

                //Reference a text element called "Text"
                var txtElm = lyt.Elements.Single(item => (item is TextElement && item.Name.Equals("Text"))) as TextElement;

                //Modify the text elements placement properties
                var txtPlacement = txtElm.GetPlacement();
                txtPlacement.Anchor = ArcGIS.Core.CIM.Anchor.CenterPoint;
                txtPlacement.X = 4.25;
                txtPlacement.Y = 5.5;
                txtElm.SetPlacement(txtPlacement);

                //Modify the text properties
                var txtProp = txtElm.TextProperties;
                txtProp.Text = "Some New Text";
                txtProp.Font = "Tahoma";
                txtProp.FontSize = 24;
                txtElm.SetTextProperties(txtProp);
            });
        }
    }
}


text:
external help file: Microsoft.Azure.Commands.Scheduler.dll-Help.xml
Module Name: AzureRM.Scheduler
ms.assetid: F315B193-C17B-41A9-B61D-0A0212B6B643
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.scheduler/remove-azurermschedulerjobcollection
schema: 2.0.0
---

# Remove-AzureRmSchedulerJobCollection

## SYNOPSIS
Removes a job collection.

## SYNTAX

```
Remove-AzureRmSchedulerJobCollection -ResourceGroupName <String> -JobCollectionName <String> [-PassThru]
 [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The **Remove-AzureRmSchedulerJobCollection** cmdlet removes a job collection in Azure Scheduler.

## EXAMPLES

## PARAMETERS

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -JobCollectionName
Specifies the name of a job collection.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases: Name, ResourceName

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -PassThru
Indicates that this cmdlet returns a value of Success on success.
By default, this cmdlet does not generate any output.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupName
Specifies the resource group of the job collection.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

### System.String

## NOTES

## RELATED LINKS

[Disable-AzureRmSchedulerJobCollection](./Disable-AzureRmSchedulerJobCollection.md)

[Enable-AzureRmSchedulerJobCollection](./Enable-AzureRmSchedulerJobCollection.md)

[Get-AzureRmSchedulerJobCollection](./Get-AzureRmSchedulerJobCollection.md)

[New-AzureRmSchedulerJobCollection](./New-AzureRmSchedulerJobCollection.md)

[Set-AzureRmSchedulerJobCollection](./Set-AzureRmSchedulerJobCollection.md)

redpajama_set_name: RedPajamaGithub


text:
Title: WebGL Text - Canvas 2D
Description: How to display text using a 2D canvas that is in sync with WebGL

This article is a continuation of [previous WebGL articles about drawing text](webgl-text-html.html).
If you haven't read them I suggest you start there and work your way back.

Instead of using HTML elements for text we can also use another canvas but with
a 2D context. Without profiling it's just a guess that this would be faster
than using the DOM. Of course it's also less flexible. You don't get all the
fancy CSS styling. But, there's no HTML elements to create and keep track of.

Similar to the other examples we make a container but this time we put
2 canvases in it.

    <div class="container">
      <canvas id="canvas" width="400" height="300"></canvas>
      <canvas id="text" width="400" height="300"></canvas>
    </div>

Next setup the CSS so the the canvas and the HTML overlap

    .container {
        position: relative;
    }

    #text {
        position: absolute;
        left: 0px;
        top: 0px;
        z-index: 10;
    }

Now look up the text canvas at init time and create a 2D context for it.

    // look up the text canvas.
    var textCanvas = document.getElementById("text");

    // make a 2D context for it
    var ctx = textCanvas.getContext("2d");

When drawing, just like WebGL, we need to clear the 2D canvas each frame.

    function drawScene() {
        ...

        // Clear the 2D canvas
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

And then we just call `fillText` to draw text

        ctx.fillText(someMsg, pixelX, pixelY);

And here's that example

{{{example url="../webgl-text-html-canvas2d.html" }}}

Why is the text smaller? Because that's the default size for Canvas 2D.
If you want other sizes [check out the Canvas 2D API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text).

Another reason to use Canvas 2D is it's easy to draw other things. For example
let's add an arrow

    // draw an arrow and text.

    // save all the canvas settings
    ctx.save();

    // translate the canvas origin so 0, 0 is at
    // the top front right corner of our F
    ctx.translate(pixelX, pixelY);

    // draw an arrow
    ctx.beginPath();
    ctx.moveTo(10, 5);
    ctx.lineTo(0, 0);
    ctx.lineTo(5, 10);
    ctx.moveTo(0, 0);
    ctx.lineTo(15, 15);
    ctx.stroke();

    // draw the text.
    ctx.fillText(someMessage, 20, 20);

    // restore the canvas to its old settings.
    ctx.restore();

Here we're taking advantage of the Canvas 2D translate function so we don't have to do any extra
math when drawing our arrow. We just pretend to draw at the origin and translate takes care
of moving that origin to the corner of our F.

{{{example url="../webgl-text-html-canvas2d-arrows.html" }}}

I think that covers using Canvas 2D. [Check out the Canvas 2D API](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D)
for more ideas. [Next we'll actually render text in WebGL](webgl-text-texture.html).


text:
//  Created by Simon Grinberg on 8/25/14.

#ifndef __CCSocialActionUtils_H_
#define __CCSocialActionUtils_H_

#include "cocos2d.h"

namespace soomla {

    USING_NS_CC;

    /**
     Lists all the social actions supported by social providers in Profile
     */
    enum CCSocialActionType {
        UPDATE_STATUS,
        UPDATE_STORY,
        UPLOAD_IMAGE,
        GET_CONTACTS,
        GET_FEED,
        INVITE
    };

    /**
     @class CCSocialActionUtil
     @brief a Utility class which helps convert CCSocialActionType from/to
     __String

     Currently the class' soul purpose is to convert CCProvider from/to __String
     */
    class CCSocialActionUtils
    {
    public:
        /**
         Converts the supplied enum CCSocialActionType to __String

         @param actionType The value of provider to convert
         @return The provided value represented by a __String
         */
        static __String *actionEnumToString(CCSocialActionType actionType);

        /*
         Converts the supplied __String to CCSocialActionType if possible

         @param actionTypeString The string to convert to CCSocialActionType
         @return The CCSocialActionType value corresponding to the supplied
         string, or -1 if there is none
         */
        static CCSocialActionType actionStringToEnum(__String* actionTypeString);
    };
};

#endif


text:
#ifndef YR_PROC_H
#define YR_PROC_H

#include "types.h"

int yr_process_open_iterator(
    int pid,
    YR_MEMORY_BLOCK_ITERATOR* iterator);

int yr_process_close_iterator(
    YR_MEMORY_BLOCK_ITERATOR* iterator);

#endif


text:
<?php

/**
 * @file
 * Contains \Drupal\migrate_drupal\Tests\d6\MigrateCommentVariableFieldTest.
 */

namespace Drupal\migrate_drupal\Tests\d6;

use Drupal\field\Entity\FieldStorageConfig;

/**
 * Upgrade comment variables to field.storage.node.comment.yml.
 *
 * @group migrate_drupal
 */
class MigrateCommentVariableFieldTest extends MigrateDrupal6TestBase {

  static $modules = array('comment', 'node');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    foreach (array('page', 'story', 'test') as $type) {
      entity_create('node_type', array('type' => $type))->save();
    }
    foreach (['comment', 'comment_no_subject'] as $comment_type) {
      entity_create('comment_type', array(
        'id' => $comment_type,
        'target_entity_type_id' => 'node',
      ))
      ->save();
    }
    // Add some id mappings for the dependant migrations.
    $id_mappings = array(
      'd6_comment_type' => array(
        array(array('comment'), array('comment_no_subject')),
      ),
    );
    $this->prepareMigrations($id_mappings);
    $this->loadDumps(['Variable.php', 'NodeType.php']);
    $this->executeMigration('d6_comment_field');
  }

  /**
   * Tests comment variables migrated into a field entity.
   */
  public function testCommentField() {
    $this->assertTrue(is_object(FieldStorageConfig::load('node.comment')));
  }

}


text:
#pragma once
#include <aws/iotwireless/IoTWireless_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>

namespace Aws
{
namespace IoTWireless
{
class IoTWirelessEndpointRules
{
public:
    static Aws::String GetRulesAsString();
    static const Aws::Vector<char> Rules;
};
} // namespace IoTWireless
} // namespace Aws


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;

namespace Microsoft.Azure.WebJobs.Extensions.Storage.Blobs
{
    internal static class BlobClientExtensions
    {
        public static async Task<string> DownloadTextAsync(this BlobBaseClient blobClient, CancellationToken cancellationToken = default)
        {
            using BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync(cancellationToken).ConfigureAwait(false);
            using Stream stream = blobDownloadInfo.Content;
            using StreamReader streamReader = new StreamReader(stream);
            return await streamReader.ReadToEndAsync().ConfigureAwait(false);
        }

        public static async Task UploadTextAsync(this BlockBlobClient blockBlobClient, string text, CancellationToken cancellationToken = default)
        {
            using Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(text));
            await blockBlobClient.UploadAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        // Naming rules are here: http://msdn.microsoft.com/en-us/library/dd135715.aspx
        // Validate this on the client side so that we can get a user-friendly error rather than a 400.
        // See code here: http://social.msdn.microsoft.com/Forums/en-GB/windowsazuredata/thread/d364761b-6d9d-4c15-8353-46c6719a3392
        public static void ValidateContainerName(string containerName)
        {
            if (containerName == null)
            {
                throw new ArgumentNullException(nameof(containerName));
            }

            if (!IsValidContainerName(containerName))
            {
                throw new FormatException("Invalid container name: " + containerName);
            }
        }

        public static bool IsValidContainerName(string containerName)
        {
            return BlobNameValidationAttribute.IsValidContainerName(containerName);
        }

        public static void ValidateBlobName(string blobName)
        {
            string errorMessage;

            if (!IsValidBlobName(blobName, out errorMessage))
            {
                throw new FormatException(errorMessage);
            }
        }

        // See http://msdn.microsoft.com/en-us/library/windowsazure/dd135715.aspx.
        public static bool IsValidBlobName(string blobName, out string errorMessage)
        {
            return BlobNameValidationAttribute.IsValidBlobName(blobName, out errorMessage);
        }
    }
}


text:
FOUNDATION_EXPORT double OnboardVersionNumber;
FOUNDATION_EXPORT const unsigned char OnboardVersionString[];


text:
<?php

namespace Symfony\Contracts\Tests\Translation;

use PHPUnit\Framework\TestCase;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorTrait;

/**
 * Test should cover all languages mentioned on http://translate.sourceforge.net/wiki/l10n/pluralforms
 * and Plural forms mentioned on http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms.
 *
 * See also https://developer.mozilla.org/en/Localization_and_Plurals which mentions 15 rules having a maximum of 6 forms.
 * The mozilla code is also interesting to check for.
 *
 * As mentioned by chx http://drupal.org/node/1273968 we can cover all by testing number from 0 to 199
 *
 * The goal to cover all languages is to far fetched so this test case is smaller.
 *
 * @author Clemens Tolboom clemens@build2be.nl
 */
class TranslatorTest extends TestCase
{
    public function getTranslator()
    {
        return new class() implements TranslatorInterface {
            use TranslatorTrait;
        };
    }

    /**
     * @dataProvider getTransTests
     */
    public function testTrans($expected, $id, $parameters)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected, $translator->trans($id, $parameters));
    }

    /**
     * @dataProvider getTransChoiceTests
     */
    public function testTransChoiceWithExplicitLocale($expected, $id, $number)
    {
        $translator = $this->getTranslator();
        $translator->setLocale('en');

        $this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
    }

    /**
     * @dataProvider getTransChoiceTests
     */
    public function testTransChoiceWithDefaultLocale($expected, $id, $number)
    {
        \Locale::setDefault('en');

        $translator = $this->getTranslator();

        $this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
    }

    public function testGetSetLocale()
    {
        $translator = $this->getTranslator();
        $translator->setLocale('en');

        $this->assertEquals('en', $translator->getLocale());
    }

    /**
     * @requires extension intl
     */
    public function testGetLocaleReturnsDefaultLocaleIfNotSet()
    {
        $translator = $this->getTranslator();

        \Locale::setDefault('pt_BR');
        $this->assertEquals('pt_BR', $translator->getLocale());

        \Locale::setDefault('en');
        $this->assertEquals('en', $translator->getLocale());
    }

    public function getTransTests()
    {
        return array(
            array('Symfony is great!', 'Symfony is great!', array()),
            array('Symfony is awesome!', 'Symfony is %what%!', array('%what%' => 'awesome')),
        );
    }

    public function getTransChoiceTests()
    {
        return array(
            array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),
            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
            array('There are 0 apples', 'There is 1 apple|There are %count% apples', 0),
            array('There is 1 apple', 'There is 1 apple|There are %count% apples', 1),
            array('There are 10 apples', 'There is 1 apple|There are %count% apples', 10),
            // custom validation messages may be coded with a fixed value
            array('There are 2 apples', 'There are 2 apples', 2),
        );
    }

    /**
     * @dataProvider getInternal
     */
    public function testInterval($expected, $number, $interval)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', array('%count%' => $number)));
    }

    public function getInternal()
    {
        return array(
            array('foo', 3, '{1,2, 3 ,4}'),
            array('bar', 10, '{1,2, 3 ,4}'),
            array('bar', 3, '[1,2]'),
            array('foo', 1, '[1,2]'),
            array('foo', 2, '[1,2]'),
            array('bar', 1, ']1,2['),
            array('bar', 2, ']1,2['),
            array('foo', log(0), '[-Inf,2['),
            array('foo', -log(0), '[-2,+Inf]'),
        );
    }

    /**
     * @dataProvider getChooseTests
     */
    public function testChoose($expected, $id, $number)
    {
        $translator = $this->getTranslator();

        $this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
    }

    public function testReturnMessageIfExactlyOneStandardRuleIsGiven()
    {
        $translator = $this->getTranslator();

        $this->assertEquals('There are two apples', $translator->trans('There are two apples', array('%count%' => 2)));
    }

    /**
     * @dataProvider getNonMatchingMessages
     * @expectedException \InvalidArgumentException
     */
    public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number)
    {
        $translator = $this->getTranslator();

        $translator->trans($id, array('%count%' => $number));
    }

    public function getNonMatchingMessages()
    {
        return array(
            array('{0} There are no apples|{1} There is one apple', 2),
            array('{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('{1} There is one apple|]2,Inf] There are %count% apples', 2),
            array('{0} There are no apples|There is one apple', 2),
        );
    }

    public function getChooseTests()
    {
        return array(
            array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('There are no apples', '{0}     There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),

            array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),

            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10),
            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]     There are %count% apples', 10),

            array('There are 0 apples', 'There is one apple|There are %count% apples', 0),
            array('There is one apple', 'There is one apple|There are %count% apples', 1),
            array('There are 10 apples', 'There is one apple|There are %count% apples', 10),

            array('There are 0 apples', 'one: There is one apple|more: There are %count% apples', 0),
            array('There is one apple', 'one: There is one apple|more: There are %count% apples', 1),
            array('There are 10 apples', 'one: There is one apple|more: There are %count% apples', 10),

            array('There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0),
            array('There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1),
            array('There are 10 apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10),

            array('', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1),

            // Indexed only tests which are Gettext PoFile* compatible strings.
            array('There are 0 apples', 'There is one apple|There are %count% apples', 0),
            array('There is one apple', 'There is one apple|There are %count% apples', 1),
            array('There are 2 apples', 'There is one apple|There are %count% apples', 2),

            // Tests for float numbers
            array('There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7),
            array('There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1),
            array('There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7),
            array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
            array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0),
            array('There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),

            // Test texts with new-lines
            // with double-quotes and \n in id & double-quotes and actual newlines in text
            array("This is a text with a\n            new-line in it. Selector = 0.", '{0}This is a text with a
            new-line in it. Selector = 0.|{1}This is a text with a
            new-line in it. Selector = 1.|[1,Inf]This is a text with a
            new-line in it. Selector > 1.', 0),
            // with double-quotes and \n in id and single-quotes and actual newlines in text
            array("This is a text with a\n            new-line in it. Selector = 1.", '{0}This is a text with a
            new-line in it. Selector = 0.|{1}This is a text with a
            new-line in it. Selector = 1.|[1,Inf]This is a text with a
            new-line in it. Selector > 1.', 1),
            array("This is a text with a\n            new-line in it. Selector > 1.", '{0}This is a text with a
            new-line in it. Selector = 0.|{1}This is a text with a
            new-line in it. Selector = 1.|[1,Inf]This is a text with a
            new-line in it. Selector > 1.', 5),
            // with double-quotes and id split accros lines
            array('This is a text with a
            new-line in it. Selector = 1.', '{0}This is a text with a
            new-line in it. Selector = 0.|{1}This is a text with a
            new-line in it. Selector = 1.|[1,Inf]This is a text with a
            new-line in it. Selector > 1.', 1),
            // with single-quotes and id split accros lines
            array('This is a text with a
            new-line in it. Selector > 1.', '{0}This is a text with a
            new-line in it. Selector = 0.|{1}This is a text with a
            new-line in it. Selector = 1.|[1,Inf]This is a text with a
            new-line in it. Selector > 1.', 5),
            // with single-quotes and \n in text
            array('This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0),
            // with double-quotes and id split accros lines
            array("This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1),
            // esacape pipe
            array('This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0),
            // Empty plural set (2 plural forms) from a .PO file
            array('', '|', 1),
            // Empty plural set (3 plural forms) from a .PO file
            array('', '||', 1),
        );
    }

    /**
     * @dataProvider failingLangcodes
     */
    public function testFailedLangcodes($nplural, $langCodes)
    {
        $matrix = $this->generateTestData($langCodes);
        $this->validateMatrix($nplural, $matrix, false);
    }

    /**
     * @dataProvider successLangcodes
     */
    public function testLangcodes($nplural, $langCodes)
    {
        $matrix = $this->generateTestData($langCodes);
        $this->validateMatrix($nplural, $matrix);
    }

    /**
     * This array should contain all currently known langcodes.
     *
     * As it is impossible to have this ever complete we should try as hard as possible to have it almost complete.
     *
     * @return array
     */
    public function successLangcodes()
    {
        return array(
            array('1', array('ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky')),
            array('2', array('nl', 'fr', 'en', 'de', 'de_GE', 'hy', 'hy_AM')),
            array('3', array('be', 'bs', 'cs', 'hr')),
            array('4', array('cy', 'mt', 'sl')),
            array('6', array('ar')),
        );
    }

    /**
     * This array should be at least empty within the near future.
     *
     * This both depends on a complete list trying to add above as understanding
     * the plural rules of the current failing languages.
     *
     * @return array with nplural together with langcodes
     */
    public function failingLangcodes()
    {
        return array(
            array('1', array('fa')),
            array('2', array('jbo')),
            array('3', array('cbs')),
            array('4', array('gd', 'kw')),
            array('5', array('ga')),
        );
    }

    /**
     * We validate only on the plural coverage. Thus the real rules is not tested.
     *
     * @param string $nplural       Plural expected
     * @param array  $matrix        Containing langcodes and their plural index values
     * @param bool   $expectSuccess
     */
    protected function validateMatrix($nplural, $matrix, $expectSuccess = true)
    {
        foreach ($matrix as $langCode => $data) {
            $indexes = array_flip($data);
            if ($expectSuccess) {
                $this->assertEquals($nplural, \count($indexes), "Langcode '$langCode' has '$nplural' plural forms.");
            } else {
                $this->assertNotEquals((int) $nplural, \count($indexes), "Langcode '$langCode' has '$nplural' plural forms.");
            }
        }
    }

    protected function generateTestData($langCodes)
    {
        $translator = new class() {
            use TranslatorTrait {
                getPluralizationRule as public;
            }
        };

        $matrix = array();
        foreach ($langCodes as $langCode) {
            for ($count = 0; $count < 200; ++$count) {
                $plural = $translator->getPluralizationRule($count, $langCode);
                $matrix[$langCode][$count] = $plural;
            }
        }

        return $matrix;
    }
}


text:
package edu.cmu.minorthird.text;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

import org.apache.log4j.Logger;

import edu.cmu.minorthird.util.ProgressCounter;
import edu.cmu.minorthird.util.StringUtil;

/**
 * Loads and saves the contents of a TextLabels into a file.
 *
 * Labels can be loaded from operations (see importOps) or from a serialized
 * TextLabels object. Labels can be serialized or types can be saved as
 * operations, xml, or plain lists.
 *
 * @author William Cohen
 */

public class TextLabelsLoader{

	private static Logger log=Logger.getLogger(TextLabelsLoader.class);

	/**
	 * Spans in labels are a complete list of all spans.
	 */
	static final public int CLOSE_ALL_TYPES=1;

	/**
	 * If a document has been labeled for a type, assume all spans of that type
	 * are there.
	 */
	static final public int CLOSE_TYPES_IN_LABELED_DOCS=2;

	/** Make no assumptions about closure. */
	static final public int DONT_CLOSE_TYPES=3;

	static final public int CLOSE_BY_OPERATION=4;

	public static final String[] CLOSURE_NAMES=
	{"CLOSE_ALL_TYPES","CLOSE_TYPES_IN_LABELED_DOCS","DONT_CLOSE_TYPES",
	"CLOSE_BY_OPERATION"};

	private int closurePolicy=CLOSE_BY_OPERATION;

	private int warnings=0;

	static private final int MAX_WARNINGS=10;

	/**
	 * Set the closure policy.
	 *
	 * @param policy
	 *          one of CLOSE_ALL_TYPES, CLOSE_TYPES_IN_LABELED_DOCS,
	 *          DONT_CLOSE_TYPES
	 */
	public void setClosurePolicy(int policy){
		this.closurePolicy=policy;
	}

	/**
	 * Create a new labeling by importing from a file with importOps.
	 */
	public MutableTextLabels loadOps(TextBase base,File file) throws IOException,
	FileNotFoundException{
		MutableTextLabels labels=new BasicTextLabels(base);
		importOps(labels,base,file);
		return labels;
	}

	/**
	 * Load lines modifying a TextLabels from a file. There are four allowed
	 * operations: addToType, closeType, closeAllTypes, setClosure
	 *
	 * For addToType: The lines must be of the form:
	 * addToType ID LOW LENGTH TYPE where ID is a documentID in the
	 * given TextBase, LOW is a character index into that document, and LENGTH is
	 * the length in characters of the span that will be created as given type
	 * TYPE. If LENGTH==-1, then the created span will go to the end of the
	 * document.
	 *
	 * For closeType: Lines must be closeType ID TYPE where ID is a
	 * documentID in the given TextBase and TYPE is the label type to close over
	 * that document.
	 *
	 * For closeAllTypes: Lines must be closeAllType ID where ID is
	 * a documentID in the given TextBase. The document will be closed for all
	 * types present in the TextLabels after all operations are
	 * performed.
	 *
	 * For setClosure: Lines must be setClosure POLICY where POLICY
	 * is one of the policy types defined in this class. It will immediately
	 * change the closure policy for the loader. This is best used at the
	 * beginning of the file to indicate one of the generic policies or the
	 * CLOSE_BY_OPERATION (default) policy.
	 */
	public void importOps(MutableTextLabels labels,TextBase base,File file)
	throws IOException,FileNotFoundException{
		base=labels.getTextBase();
		if(base==null)
			throw new IllegalStateException(
			"TextBase attached to labels must not be null");

		LineNumberReader in=new LineNumberReader(new FileReader(file));
		String line=null;
		List<String> docList=new ArrayList<String>();
		try{
			while((line=in.readLine())!=null){
				if(line.trim().length()==0)
					continue;
				if(line.startsWith("#"))
					continue;
				log.debug("read line #"+in.getLineNumber()+": "+line);
				StringTokenizer tok=new StringTokenizer(line);
				String op;
				try{
					op=advance(tok,in,file);
				}catch(IllegalArgumentException e){
					throw getNewException(e,", failed to find operation.");
				}
				if("addToType".equals(op)){
					addToType(tok,in,file,base,labels);
				}else if("setSpanProp".equals(op)){
					setSpanProp(tok,in,file,base,labels);
				}else if("closeType".equals(op)){
					String docId=advance(tok,in,file);
					String type=advance(tok,in,file);
					Span span=base.documentSpan(docId);
					if(span!=null){
						labels.closeTypeInside(type,span);
						log.debug("closed "+type+" on "+docId);
					}else{
						warnings++;
						if(warnings<MAX_WARNINGS){
							log.warn("unknown id '"+docId+"' in closeType");
						}else if(warnings==MAX_WARNINGS){
							log.warn("there will be no more warnings of this sort given");
						}
					}
				}else if("closeAllTypes".equalsIgnoreCase(op)){
					String docId=advance(tok,in,file);
					docList.add(docId);
				}else{
					throw new IllegalArgumentException("error on line "+
							in.getLineNumber()+" of "+file.getName());
				}
			}
			// close over the doc list for all types seen
			for(int i=0;i<docList.size();i++){
				String docId=(String)docList.get(i);
				Span span=base.documentSpan(docId);
				closeLabels(labels.getTypes(),labels,span);
			}

		}catch(IllegalArgumentException e){
			throw getNewException(e," on line: "+line);
		}
		in.close();
		closeLabels(labels,closurePolicy);
	}

	private void addToType(StringTokenizer tok,LineNumberReader in,File file,
			TextBase base,MutableTextLabels labels){
		String id=advance(tok,in,file);
		String loStr=advance(tok,in,file);
		String lenStr=advance(tok,in,file);
		String type=advance(tok,in,file);
		String confidence=tok.hasMoreTokens()?advance(tok,in,file):null;
		int lo,len;
		try{
			lo=Integer.parseInt(loStr);
			len=Integer.parseInt(lenStr);
			Span span=base.documentSpan(id);
			if(span==null){
				warnings++;
				if(warnings<MAX_WARNINGS){
					log.warn("unknown id '"+id+"' in addToType "+lo+" "+len);
				}else if(warnings==MAX_WARNINGS){
					log.warn("there will be no more warnings of this sort given");
				}
			}else{
				Details details=null;
				if(confidence!=null)
					details=new Details(StringUtil.atof(confidence));
				if(lo==0&&len<0)
					labels.addToType(span,type,details);
				else{
					// shortcut: char offsets "0 -1" means the whole document
					if(len<0)
						len=span.asString().length()-lo;
					labels.addToType(span.charIndexSubSpan(lo,lo+len),type,details);
				}
			}
		}catch(NumberFormatException e){
			throw new IllegalArgumentException("bad number on line "+
					in.getLineNumber()+" of "+file.getName());
		}
	}

	private void setSpanProp(StringTokenizer tok,LineNumberReader in,File file,
			TextBase base,MutableTextLabels labels){
		String id=advance(tok,in,file);
		String loStr=advance(tok,in,file);
		String lenStr=advance(tok,in,file);
		String prop=advance(tok,in,file);
		String value=advance(tok,in,file);
		int lo,len;
		try{
			lo=Integer.parseInt(loStr);
			len=Integer.parseInt(lenStr);
			Span span=base.documentSpan(id);
			if(span==null){
				warnings++;
				if(warnings<MAX_WARNINGS){
					log.warn("unknown id '"+id+"'");
				}else if(warnings==MAX_WARNINGS){
					log.warn("there will be no more warnings of this sort given");
				}
			}else{
				if(lo==0&&len<0)
					labels.setProperty(span,prop,value);
				else{
					if(len<0)
						len=span.asString().length()-lo;
					labels.setProperty(span.charIndexSubSpan(lo,lo+len),prop,value);
				}
			}
		}catch(NumberFormatException e){
			throw new IllegalArgumentException("bad number on line "+
					in.getLineNumber()+" of "+file.getName());
		}
	}

	private static IllegalArgumentException getNewException(
			IllegalArgumentException e,String addToMsg){
		String msg=e.getMessage()+addToMsg;
		StackTraceElement[] trace=e.getStackTrace();
		IllegalArgumentException exception=new IllegalArgumentException(msg);
		exception.setStackTrace(trace);
		return exception;
	}

	private String advance(StringTokenizer tok,LineNumberReader in,File file){
		if(!tok.hasMoreTokens())
			throw new IllegalArgumentException("error on line "+in.getLineNumber()+
					" of "+file.getName()+" failed to find token");
		return tok.nextToken();
	}

	/**
	 * Close labels on the labels according to the policy. This applies the same
	 * policy to all documents and types in the labels. To get finer control of
	 * closure use closeLabels(Set, MutableTextLabels, Span) or
	 * MutableTextLabels.closeTypeInside(...)
	 *
	 * @param labels
	 * @param policy
	 */
	public void closeLabels(MutableTextLabels labels,int policy){
		Set<String> types=labels.getTypes();
		TextBase base=labels.getTextBase();
		switch(policy){
		case CLOSE_ALL_TYPES:
			for(Iterator i=base.documentSpanIterator();i.hasNext();){
				Span document=i.next();
				closeLabels(types,labels,document);
			}
			break;
		case CLOSE_TYPES_IN_LABELED_DOCS:
			Set labeledDocs=new TreeSet();
			for(Iterator<String> j=types.iterator();j.hasNext();){
				String type=j.next();
				for(Iterator i=labels.instanceIterator(type);i.hasNext();){
					Span span=i.next();
					labeledDocs.add(span.documentSpan());
				}
			}
			for(Iterator i=labeledDocs.iterator();i.hasNext();){
				Span document=i.next();
				closeLabels(types,labels,document);
			}
			break;
		case DONT_CLOSE_TYPES: // do nothing for this
			break;
		case CLOSE_BY_OPERATION: // already closed in theory
			break;
		default:
			log.warn("closure policy("+policy+") not recognized");
		}
	}

	/**
	 * Close all types in the typeSet on the given document
	 *
	 * @param typeSet
	 *          set of types to close for this document
	 * @param labels
	 *          TextLabels holding the types
	 * @param document
	 *          Span to close types over
	 */
	private void closeLabels(Set<String> types,MutableTextLabels labels,
			Span document){
		for(Iterator<String> j=types.iterator();j.hasNext();){
			String type=j.next();
			labels.closeTypeInside(type,document);
		}
	}

	/** Read in a serialized TextLabels. */
	public MutableTextLabels loadSerialized(File file,TextBase base)
	throws IOException,FileNotFoundException{
		try{
			ObjectInputStream in=
				new ObjectInputStream(new BufferedInputStream(new FileInputStream(
						file)));
			MutableTextLabels labels=(MutableTextLabels)in.readObject();
			labels.setTextBase(base);
			in.close();
			return labels;
		}catch(ClassNotFoundException e){
			throw new IllegalArgumentException("can't read TextLabels from "+file+
					": "+e);
		}
	}

	/** Serialize a TextLabels. */
	public void saveSerialized(MutableTextLabels labels,File file)
	throws IOException{
		ObjectOutputStream out=
			new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(
					file)));
		out.writeObject(labels);
		out.flush();
		out.close();
	}

	/** Save extracted data in a format readable with loadOps. */
	public String printTypesAsOps(TextLabels labels){
		StringBuffer out=new StringBuffer();
		ProgressCounter pc=
			new ProgressCounter("saving labels","type",labels.getTypes().size());
		for(Iterator<String> i=labels.getTypes().iterator();i.hasNext();){
			String type=i.next();
			ProgressCounter pc2=new ProgressCounter("saving type "+type,"span");
			for(Iterator j=labels.instanceIterator(type);j.hasNext();){
				Span s=j.next();
				if(s.size()>0){
					int lo=s.getTextToken(0).getLo();
					int hi=s.getTextToken(s.size()-1).getHi();
					Details details=labels.getDetails(s,type);
					if(details==null||details==Details.DEFAULT){
						out.append("addToType "+s.getDocumentId()+" "+lo+" "+(hi-lo)+" "+
								type+"\n");
					}else{
						out.append("addToType "+s.getDocumentId()+" "+lo+" "+(hi-lo)+" "+
								type+" "+details.getConfidence()+"\n");
					}
				}else{
					warnings++;
					if(warnings<MAX_WARNINGS){
						log.warn("forgetting label on empty span type "+type+": "+s);
					}else if(warnings==MAX_WARNINGS){
						log.warn("there will be no more warnings of this sort given");
					}
				}
				pc2.progress();
			}
			pc2.finished();
			Iterator it=labels.closureIterator(type);
			while(it.hasNext()){
				Span s=it.next();
				Span doc=s.documentSpan();
				if(s.size()!=doc.size()){
					throw new UnsupportedOperationException(
					"can't save environment with closureSpans!=docSpans");
				}
				out.append("closeType "+s.getDocumentId()+" "+type+"\n");
			}
			pc.progress();
		}
		pc.finished();
		ProgressCounter pc3=
			new ProgressCounter("saving labels","property",labels
					.getSpanProperties().size());
		for(Iterator<String> i=labels.getSpanProperties().iterator();i.hasNext();){
			String prop=i.next();
			for(Iterator j=labels.getSpansWithProperty(prop);j.hasNext();){
				Span s=j.next();
				if(s.size()>0){
					String val=labels.getProperty(s,prop);
					int lo=s.getTextToken(0).getLo();
					int hi=s.getTextToken(s.size()-1).getHi();
					out.append("setSpanProp "+s.getDocumentId()+"  "+lo+" "+(hi-lo)+" "+
							prop+" "+val+"\n");
				}
			}
			pc3.progress();
		}
		pc3.finished();
		return out.toString();
	}

	/** Save extracted data in a format readable with loadOps. */
	public void saveTypesAsOps(TextLabels labels,File file) throws IOException{
		PrintStream out=new PrintStream(new FileOutputStream(file));
		out.println(printTypesAsOps(labels));
		out.close();
	}

	/**
	 * Save spans of given type into the file, one per line. Linefeeds in strings
	 * are replaced with spaces.
	 */
	public void saveTypesAsStrings(TextLabels labels,File file,
			boolean includeOffset) throws IOException{
		PrintStream out=new PrintStream(new FileOutputStream(file));
		// Do types
		for(Iterator<String> j=labels.getTypes().iterator();j.hasNext();){
			String type=j.next();
			for(Iterator i=labels.instanceIterator(type);i.hasNext();){
				Span span=i.next();
				if(span.size()>0){
					out.print(type);
					if(includeOffset){
						out.print(":"+span.getDocumentId()+":"+span.getTextToken(0).getLo()+
								":"+span.getTextToken(span.size()-1).getHi());
					}
					out.println("\t"+span.asString().replace('\n',' '));
				}
			}
		}
		// Do props
		for(Iterator<String> i=labels.getSpanProperties().iterator();i.hasNext();){
			String prop=i.next();
			for(Iterator j=labels.getSpansWithProperty(prop);j.hasNext();){
				Span span=j.next();
				if(span.size()>0){
					String val=labels.getProperty(span,prop);
					if(!prop.equals("_prediction")){
						out.print(prop);
						out.print("=");
					}
					out.print(val);
					if(includeOffset){
						out.print(":"+span.getDocumentId()+":"+span.getTextToken(0).getLo()+
								":"+span.getTextToken(span.size()-1).getHi());
					}
					out.println("\t"+span.asString().replace('\n',' '));
				}
			}
		}
		out.close();
	}

	/**
	 * Save documents to specified directory with extracted types embedded as xml.
	 */
	public void saveDocsWithEmbeddedTypes(TextLabels labels,File dir)
	throws IOException{
		Span currDoc;
		Iterator looper=labels.getTextBase().documentSpanIterator();
		PrintStream out;

		if(dir.exists()){
			log.warn(dir+" already exists, some files may be overwritten.");
		}
		else if(!dir.mkdir()){
			throw new IOException("Could not create directory named: "+dir);
		}

		while(looper.hasNext()){
			// this call returns the entire document with all labels embedded as xml
			currDoc=looper.next();
			out=
				new PrintStream(new FileOutputStream(new File(dir+"/"+
						currDoc.getDocumentId())));
			out.println(createXMLmarkup(currDoc.getDocumentId(),labels));
			out.close();
		}
	}

	/**
	 * Save extracted data in an XML format. Convert to string
	 * <root>..<type>...</type>..</root>.

	 *

	 * In the even that labels overlap such as [A (B C] D)E an
	 * IllegalArgumentException is thrown because a well-formed XML document
	 * cannot be created.
	 */
	public String createXMLmarkup(String documentId,TextLabels labels){
		Span docSpan=labels.getTextBase().documentSpan(documentId);
		String docString=
			labels.getTextBase().documentSpan(documentId).getDocumentContents();

		// Put all labels and their info in a list
		List<LabelInfo> unsortedLabels=new ArrayList<LabelInfo>();

		// Do types
		for(Iterator<String> i=labels.getTypes().iterator();i.hasNext();){
			String type=i.next();
			for(Iterator j=labels.instanceIterator(type,documentId);j.hasNext();){
				Span s=j.next();
				int start=s.documentSpanStartIndex();
				int end=start+s.size()-1;
				unsortedLabels.add(new LabelInfo(s,type,start,end));
			}
		}

		// Do props
		for(Iterator<String> i=labels.getSpanProperties().iterator();i.hasNext();){
			String prop=i.next();
			for(Iterator j=labels.getSpansWithProperty(prop,documentId);j.hasNext();){
				Span s=j.next();
				String val=labels.getProperty(s,prop);
				int start=s.documentSpanStartIndex();
				int end=start+s.size()-1;
				if(prop.equals("_prediction")){
					unsortedLabels.add(new LabelInfo(s,val,start,end));
				}
				else{
					unsortedLabels.add(new LabelInfo(s,prop+"."+val,start,end));
				}
			}
		}

		// Sort the labels. If two spans are overlapping then throw an exception
		List<LabelInfo> sortedLabels=
			new ArrayList<LabelInfo>(unsortedLabels.size());
		while(unsortedLabels.size()>0){
			LabelInfo curLabel=unsortedLabels.remove(0);
			int position=-1;

			boolean overlap=false;

			// Iterate through sortedLabels
			for(int j=0;j<sortedLabels.size();j++){
				LabelInfo compLabel=(LabelInfo)sortedLabels.get(j);
				// Find if there is an overlap
				if((curLabel.start<compLabel.start&&curLabel.end>compLabel.start)&&
						(curLabel.end<compLabel.end))
					overlap=true;
				else if((curLabel.start>compLabel.start&&curLabel.start<compLabel.end)&&
						(curLabel.end>compLabel.end))
					overlap=true;
				// Find position
				if((curLabel.start<compLabel.start)||
						((curLabel.start==compLabel.start)&&(curLabel.end>=compLabel.end))){
					position=j;
					break;
				}
			}

			// If the label overlapped with another label, then throw an exception
			if(overlap)
				throw new IllegalArgumentException(
				"Labels contain overalpping spans, cannot save as XML format.");

			// Otherwise add the label to the proper position in the sorted list.
			if(position>-1)
				sortedLabels.add(position,curLabel);
			else
				sortedLabels.add(curLabel);
		}

		// Create sorted list of tags
		List<TagInfo> sortedTags=new ArrayList<TagInfo>(sortedLabels.size()*2);
		for(int i=0;i<sortedLabels.size();i++){
			LabelInfo label=sortedLabels.get(i);
			sortedTags.add(new TagInfo(label.start,"<"+label.type+">",true));
		}
		boolean added=false;
		while(sortedLabels.size()>0){
			LabelInfo label=sortedLabels.remove(0);
			added=false;
			for(int y=0;y<sortedTags.size();y++){
				TagInfo tag=(TagInfo)sortedTags.get(y);
				if(label.end<tag.pos){
					sortedTags.add(y,new TagInfo(label.end,"</"+label.type+">",false));
					added=true;
					break;
				}
			}
			if(!added){
				sortedTags.add(new TagInfo(label.end,"</"+label.type+">",false));
			}
		}

		// Create markedup StringBuffer
		StringBuffer buffer=new StringBuffer();

		buffer.append("<root>");
		int docPos=0,pos=0;
		while(sortedTags.size()>0){
			TagInfo curTag=sortedTags.remove(0);

			if(curTag.pos<docSpan.size()){
				if(curTag.isOpenTag)
					pos=docSpan.subSpan(curTag.pos,1).getTextToken(0).getLo();
				else
					pos=docSpan.subSpan(curTag.pos,1).getTextToken(0).getHi();
			}else
				pos=docString.length();

			buffer.append(docString.substring(docPos,pos));
			buffer.append(curTag.tag);
			docPos=pos;
		}
		buffer.append(docString.substring(docPos,docString.length()));
		buffer.append("</root>");
		return buffer.toString();

	}

	private class TagInfo{

		public int pos;

		public String tag;

		public boolean isOpenTag;

		public TagInfo(int pos,String tag,boolean isOpenTag){
			this.pos=pos;
			this.tag=tag;
			this.isOpenTag=isOpenTag;
		}
	}

	private class LabelInfo{

//		public Span span;

		public String type;

		public int start;

		public int end;

		public LabelInfo(Span span,String type,int start,int end){
//			this.span=span;
			this.type=type;
			this.start=start;
			this.end=end;
		}
	}

//	// Helper method used to maintain a set of tag boundaries
//	private void setBoundary(SortedMap<Span,Set<String[]>> boundaries,
//			String beginOrEnd,String type,Span s){
//		Set<String[]> ops=boundaries.get(s);
//		if(ops==null)
//			boundaries.put(s,(ops=new HashSet<String[]>()));
//		ops.add(new String[]{beginOrEnd,type});
//	}

	/** Save extracted data in an XML format */
	public String saveTypesAsXML(TextLabels labels){
		StringBuffer buf=new StringBuffer("<extractions>\n");
		for(Iterator<String> i=labels.getTypes().iterator();i.hasNext();){
			String type=i.next();
			for(Iterator j=labels.instanceIterator(type);j.hasNext();){
				Span s=j.next();
				int lo=s.getTextToken(0).getLo();
				int hi=s.getTextToken(s.size()-1).getHi();
				buf.append("  <"+type+" lo="+lo+" hi="+hi+">"+s.asString()+"</"+type+
				">\n");
			}
		}
		buf.append("</extractions>\n");
		return buf.toString();
	}
}


text:
@yield('heading')

                    @yield('subheading')


text:
package com.google.cloud.genomics.utils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.api.services.genomics.Genomics;
import com.google.api.services.genomics.model.LinearAlignment;
import com.google.api.services.genomics.model.Position;
import com.google.api.services.genomics.model.Read;
import com.google.api.services.genomics.model.ReadGroupSet;
import com.google.api.services.genomics.model.SearchReadGroupSetsRequest;
import com.google.api.services.genomics.model.SearchReadGroupSetsResponse;
import com.google.api.services.genomics.model.SearchReadsRequest;
import com.google.api.services.genomics.model.SearchReadsResponse;
import com.google.api.services.genomics.model.SearchVariantsRequest;
import com.google.api.services.genomics.model.SearchVariantsResponse;
import com.google.api.services.genomics.model.Variant;
import com.google.common.collect.Lists;

import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import java.util.Arrays;
import java.util.List;

@RunWith(JUnit4.class)
public class PaginatorTest {

  @Mock Genomics genomics;
  @Mock Genomics.Readgroupsets readGroupSets;
  @Mock Genomics.Readgroupsets.Search readGroupSetSearch;
  @Mock Genomics.Variants variants;
  @Mock Genomics.Variants.Search variantsSearch;
  @Mock Genomics.Reads reads;
  @Mock Genomics.Reads.Search readsSearch;

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Before
  public void initMocks() {
    MockitoAnnotations.initMocks(this);
    Mockito.when(genomics.readgroupsets()).thenReturn(readGroupSets);
    Mockito.when(genomics.variants()).thenReturn(variants);
    Mockito.when(genomics.reads()).thenReturn(reads);
  }

  @Test
  public void testPagination() throws Exception {

    // Page 1
    Mockito.when(readGroupSets.search(new SearchReadGroupSetsRequest().setName("HG")))
        .thenReturn(readGroupSetSearch);

    // Page 2
    Mockito.when(readGroupSets.search(new SearchReadGroupSetsRequest().setName("HG")
        .setPageToken("page2")))
        .thenReturn(readGroupSetSearch);
    Mockito.when(readGroupSetSearch.execute()).thenReturn(
        new SearchReadGroupSetsResponse()
            .setReadGroupSets(Lists.newArrayList(new ReadGroupSet().setId("r1")))
            .setNextPageToken("page2"),
        new SearchReadGroupSetsResponse()
            .setReadGroupSets(Lists.newArrayList(new ReadGroupSet().setId("r2"))));

    Paginator.ReadGroupSets paginator = Paginator.ReadGroupSets.create(genomics);
    List<String> ids = Lists.newArrayList();
    for (ReadGroupSet readGroupSet : paginator.search(
        new SearchReadGroupSetsRequest().setName("HG"))) {
      ids.add(readGroupSet.getId());
    }

    assertEquals(Lists.newArrayList("r1", "r2"), ids);
  }

  @Test
  public void testPagination_withNullResults() throws Exception {
    Mockito.when(readGroupSets.search(new SearchReadGroupSetsRequest()))
        .thenReturn(readGroupSetSearch);
    Mockito.when(readGroupSetSearch.execute()).thenReturn(new SearchReadGroupSetsResponse());

    Paginator.ReadGroupSets paginator = Paginator.ReadGroupSets.create(genomics);
    List<String> ids = Lists.newArrayList();
    for (ReadGroupSet readGroupSet : paginator.search(new SearchReadGroupSetsRequest())) {
      ids.add(readGroupSet.getId());
    }

    // No results and no exceptions
    assertTrue(ids.isEmpty());
  }

  @Test
  public void testFields() throws Exception {
    Mockito.when(readGroupSets.search(new SearchReadGroupSetsRequest().setName("HG")))
        .thenReturn(readGroupSetSearch);
    Mockito.when(readGroupSetSearch.setFields(Mockito.anyString()))
        .thenReturn(readGroupSetSearch);
    Mockito.when(readGroupSetSearch.execute()).thenReturn(
        new SearchReadGroupSetsResponse()
            .setReadGroupSets(Lists.newArrayList(new ReadGroupSet().setId("r1"))));

    Paginator.ReadGroupSets paginator = Paginator.ReadGroupSets.create(genomics);
    List<String> ids = Lists.newArrayList();
    for (ReadGroupSet set : paginator.search(
        new SearchReadGroupSetsRequest().setName("HG"), "nextPageToken,readGroupSets(id,name)")) {
      ids.add(set.getId());
    }

    assertEquals(Lists.newArrayList("r1"), ids);

    // Make sure the fields parameter actually gets passed along
    Mockito.verify(readGroupSetSearch, Mockito.atLeastOnce()).setFields("nextPageToken,readGroupSets(id,name)");
  }

  @Test
  public void testFieldsMissingNextPageToken() throws Exception {
    Mockito.when(readGroupSets.search(new SearchReadGroupSetsRequest().setName("HG")))
    .thenReturn(readGroupSetSearch);

    Paginator.ReadGroupSets paginator = Paginator.ReadGroupSets.create(genomics);
    thrown.expect(IllegalArgumentException.class);
    paginator.search(new SearchReadGroupSetsRequest().setName("HG"), "readGroupSets(id,name)").iterator().next();
  }

  @Test
  public void testVariantPagination() throws Exception {

    SearchVariantsRequest request = new SearchVariantsRequest().setStart(1000L).setEnd(2000L);
    Mockito.when(variants.search(request)).thenReturn(variantsSearch);

    Variant overlapStartWithinExtent = new Variant().setStart(900L).setEnd(1005L);
    Variant overlapStartExtent = new Variant().setStart(999L).setEnd(5000L);
    Variant atStartWithinExtent = new Variant().setStart(1000L).setEnd(1002L);
    Variant atStartOverlapExtent = new Variant().setStart(1000L).setEnd(5000L);
    Variant beyondStartWithinExtent = new Variant().setStart(1500L).setEnd(1502L);
    Variant beyondOverlapExtent = new Variant().setStart(1500L).setEnd(5000L);
    Variant[] input = new Variant[] { overlapStartWithinExtent, overlapStartExtent, atStartWithinExtent,
            atStartOverlapExtent, beyondStartWithinExtent, beyondOverlapExtent };

    Mockito.when(variantsSearch.execute()).thenReturn(
        new SearchVariantsResponse().setVariants(Arrays.asList(input)));

    Paginator.Variants filteredPaginator = Paginator.Variants.create(genomics, ShardBoundary.Requirement.STRICT);
    List<Variant> filteredVariants = Lists.newArrayList();
    for (Variant variant : filteredPaginator.search(request)) {
      filteredVariants.add(variant);
    }
    assertEquals(4, filteredVariants.size());
    assertThat(filteredVariants, CoreMatchers.hasItems(atStartWithinExtent,
        atStartOverlapExtent, beyondStartWithinExtent, beyondOverlapExtent));

    // Ensure searches with fields verify the preconditions for strict shards.
    final String nullFields = null;
    assertNotNull(filteredPaginator.search(request, nullFields).iterator().next());
    assertNotNull(filteredPaginator.search(request, "nextPageToken,variants(start,id,calls(genotype,callSetName))").iterator().next());
    assertNotNull(filteredPaginator.search(request, "id,nextPageToken,variants(start,id,calls(genotype,callSetName))").iterator().next());
    assertNotNull(filteredPaginator.search(request, "variants(start,id,calls(genotype,callSetName)),nextPageToken").iterator().next());
    try {
      filteredPaginator.search(request, "nextPageToken,variants(id,calls(genotype,callSetName))").iterator().next();
      fail("should have thrown an IllegalArgumentxception");
    } catch (IllegalArgumentException e) {}

    Paginator.Variants overlappingPaginator = Paginator.Variants.create(genomics, ShardBoundary.Requirement.OVERLAPS);
    List<Variant> overlappingVariants = Lists.newArrayList();
    for (Variant variant : overlappingPaginator.search(request)) {
      overlappingVariants.add(variant);
    }
    assertEquals(6, overlappingVariants.size());
    assertThat(overlappingVariants, CoreMatchers.hasItems(input));

    // Ensure searches with fields verify the preconditions for overlapping shards.
    assertNotNull(overlappingPaginator.search(request, nullFields).iterator().next());
    assertNotNull(overlappingPaginator.search(request, "nextPageToken,variants(start,id,calls(genotype,callSetName))").iterator().next());
    assertNotNull(overlappingPaginator.search(request, "nextPageToken,variants(id,calls(genotype,callSetName))").iterator().next());
    assertNotNull(overlappingPaginator.search(request, "id,nextPageToken,variants(start,id,calls(genotype,callSetName))").iterator().next());
    assertNotNull(overlappingPaginator.search(request, "variants(id,calls(genotype,callSetName)),nextPageToken").iterator().next());
  }

  @Test
  public void testVariantPaginationEmptyShard() throws Exception {

    SearchVariantsRequest request = new SearchVariantsRequest().setStart(1000L).setEnd(2000L);
    Mockito.when(variants.search(request)).thenReturn(variantsSearch);

    Mockito.when(variantsSearch.execute()).thenReturn(
        new SearchVariantsResponse());

    Paginator.Variants filteredPaginator = Paginator.Variants.create(genomics, ShardBoundary.Requirement.STRICT);
    assertNotNull(filteredPaginator.search(request));
  }

  static Read readHelper(int start, int end) {
    Position position = new Position().setPosition((long) start);
    LinearAlignment alignment = new LinearAlignment().setPosition(position);
    return new Read().setAlignment(alignment).setFragmentLength(end-start);
  }

  @Test
  public void testReadPagination() throws Exception {

    SearchReadsRequest request = new SearchReadsRequest().setStart(1000L).setEnd(2000L);
    Mockito.when(reads.search(request)).thenReturn(readsSearch);

    Read overlapStartWithinExtent = readHelper(900,1005);
    Read overlapStartExtent = readHelper(999, 5000);
    Read atStartWithinExtent = readHelper(1000, 1002);
    Read atStartOverlapExtent = readHelper(1000, 5000);
    Read beyondStartWithinExtent = readHelper(1500, 1502);
    Read beyondOverlapExtent = readHelper(1500, 5000);
    Read[] input = new Read[] { overlapStartWithinExtent, overlapStartExtent, atStartWithinExtent,
            atStartOverlapExtent, beyondStartWithinExtent, beyondOverlapExtent };

    Mockito.when(readsSearch.execute()).thenReturn(
        new SearchReadsResponse().setAlignments(Arrays.asList(input)));

    Paginator.Reads filteredPaginator = Paginator.Reads.create(genomics, ShardBoundary.Requirement.STRICT);
    List<Read> filteredReads = Lists.newArrayList();
    for (Read read : filteredPaginator.search(request)) {
      filteredReads.add(read);
    }
    assertEquals(4, filteredReads.size());
    assertThat(filteredReads, CoreMatchers.hasItems(atStartWithinExtent,
        atStartOverlapExtent, beyondStartWithinExtent, beyondOverlapExtent));

    Paginator.Reads overlappingPaginator = Paginator.Reads.create(genomics, ShardBoundary.Requirement.OVERLAPS);
    List<Read> overlappingReads = Lists.newArrayList();
    for (Read read : overlappingPaginator.search(request)) {
      overlappingReads.add(read);
    }
    assertEquals(6, overlappingReads.size());
    assertThat(overlappingReads, CoreMatchers.hasItems(input));
  }

  @Test
  public void testReadPaginationStrictShardPrecondition() throws Exception {
    SearchReadsRequest request = new SearchReadsRequest().setStart(1000L).setEnd(2000L);
    Mockito.when(reads.search(request)).thenReturn(readsSearch);

    Paginator.Reads filteredPaginator = Paginator.Reads.create(genomics, ShardBoundary.Requirement.STRICT);
    thrown.expect(IllegalArgumentException.class);
    filteredPaginator.search(request, "nextPageToken,reads(id,alignment(cigar))").iterator().next();
  }

  @Test
  public void testStrictReadPaginationNextPageTokenPrecondition() throws Exception {
    SearchReadsRequest request = new SearchReadsRequest().setStart(1000L).setEnd(2000L);
    Mockito.when(reads.search(request)).thenReturn(readsSearch);

    Paginator.Reads filteredPaginator = Paginator.Reads.create(genomics, ShardBoundary.Requirement.STRICT);
    thrown.expect(IllegalArgumentException.class);
    filteredPaginator.search(request, "reads(id,alignment(cigar,position))").iterator().next();
  }

  @Test
  public void testOverlappingReadPaginationNextPageTokenPrecondition() throws Exception {
    SearchReadsRequest request = new SearchReadsRequest().setStart(1000L).setEnd(2000L);
    Mockito.when(reads.search(request)).thenReturn(readsSearch);

    Paginator.Reads overlappingPaginator = Paginator.Reads.create(genomics, ShardBoundary.Requirement.OVERLAPS);
    thrown.expect(IllegalArgumentException.class);
    overlappingPaginator.search(request, "reads(id,alignment(cigar,position))").iterator().next();
  }

}


text:
package com.sequenceiq.freeipa.api.v1.freeipa.test.model;

import javax.validation.constraints.NotEmpty;

import com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;
import com.sequenceiq.cloudbreak.validation.ValidCrn;
import com.sequenceiq.service.api.doc.ModelDescriptions;

import io.swagger.annotations.ApiModelProperty;

public abstract class ClientTestBaseRequest {

    @NotEmpty
    @ValidCrn(resource = CrnResourceDescriptor.ENVIRONMENT)
    @ApiModelProperty(value = ModelDescriptions.ENVIRONMENT_CRN, required = true)
    private String environmentCrn;

    public String getEnvironmentCrn() {
        return environmentCrn;
    }

    public void setEnvironmentCrn(String environmentCrn) {
        this.environmentCrn = environmentCrn;
    }
}


text:
local FpuStackIncrementInfo = {}

---Creates a new instance
---
---@param increment integer #(`i32`) Used if `writes_top` is `true`. Value added to `TOP`.
---@param conditional boolean #`true` if it's a conditional push/pop (eg. `FPTAN` or `FSINCOS`)
---@param writes_top boolean #`true` if `TOP` is written (it's a conditional/unconditional push/pop, `FNSAVE`, `FLDENV`, etc)
---@return FpuStackIncrementInfo
function FpuStackIncrementInfo.new(increment, conditional, writes_top) end

---Used if `FpuStackIncrementInfo:writes_top()` is `true`. Value added to `TOP`.
---
---This is negative if it pushes one or more values and positive if it pops one or more values
---and `0` if it writes to `TOP` (eg. `FLDENV`, etc) without pushing/popping anything.
---
---@return integer
function FpuStackIncrementInfo:increment() end

---`true` if it's a conditional push/pop (eg. `FPTAN` or `FSINCOS`)
---
---@return boolean
function FpuStackIncrementInfo:conditional() end

---`true` if `TOP` is written (it's a conditional/unconditional push/pop, `FNSAVE`, `FLDENV`, etc)
---
---@return boolean
function FpuStackIncrementInfo:writes_top() end

return FpuStackIncrementInfo


text:
<?php
/**
 * Created by PhpStorm.
 * User: Ivan
 * Date: 11.01.2017
 * Time: 22:34
 */

namespace Auth\Storage;

class Result
{
    protected $message;
    const SUCCESS = 1;
    const FAILURE = 0;
    const FAILURE_IDENTITY_NOT_FOUND = -1;
    const FAILURE_IDENTITY_AMBIGUOUS = -2;
    const FAILURE_CREDENTIAL_INVALID = -3;
    const FAILURE_UNCATEGORIZED = -4;

    public function __construct($code, $identity, array $messages = [
        0 => "0",
        1 => "1",
        -1 => "-1",
        -2 => "-2",
        -3 => "-3",
        -4 => "-4"
    ]) {

        switch ($code) {
            case Result::FAILURE:
                $this->setMessage("Faillure", "error");
                break;
            case Result::SUCCESS:
                $this->setMessage(sprintf($messages[$code], $identity), "success");
                break;
            case Result::FAILURE_IDENTITY_NOT_FOUND:
                $this->setMessage(sprintf($messages[$code], $identity), "alert");
                break;
            case Result::FAILURE_IDENTITY_AMBIGUOUS:
                $this->setMessage(sprintf($messages[$code], $identity), "alert");
                break;
            case Result::FAILURE_CREDENTIAL_INVALID:
                $this->setMessage(sprintf($messages[$code], $identity), "alert");
                break;
            case Result::FAILURE_UNCATEGORIZED:
                $this->setMessage(sprintf($messages[$code], $identity), "alert");
                break;
            default:
        }

    }

    public function getMessage() {
        return $this->message;
    }

    public function setMessage($message, $class='success') {
        $icon['success'] = 'ion-checkmark-found';
        $icon['info'] = 'ion-information-circled';
        $icon['alert'] = 'ion-alert-circled';
        $icon['error'] = 'ion-close-circled';
        $this->message = sprintf("
%s
div>", $class, $message, $icon[$class]);
    }
}


text:
package org.apache.ambari.server.security.ldap;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.configuration.AmbariServerConfigurationKey;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.security.ClientSecurityType;
import org.apache.ambari.server.security.authorization.AuthorizationTestModule;
import org.apache.ambari.server.security.authorization.Users;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

/**
 * Performs sync request to real LDAP server.
 */
@Ignore
public class LdapPerformanceTest {

  private static Injector injector;

  @Inject
  private AmbariLdapDataPopulator populator;

  @Inject
  private Users users;

  @Inject
  Configuration configuration;

  @Inject
  AmbariLdapConfiguration ldapConfiguration;

  final String SPRING_CONTEXT_LOCATION = "classpath:webapp/WEB-INF/spring-security.xml";

  @Before
  public void setUp() {
    injector = Guice.createInjector(new AuthorizationTestModule());

    injector.injectMembers(this);
    injector.getInstance(GuiceJpaInitializer.class);
    configuration.setClientSecurityType(ClientSecurityType.LDAP);

    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.SERVER_HOST, "c6402.ambari.apache.org");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.SERVER_PORT, "389");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.USER_OBJECT_CLASS, "posixAccount");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.USER_NAME_ATTRIBUTE, "uid");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.GROUP_OBJECT_CLASS, "posixGroup");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.GROUP_NAME_ATTRIBUTE, "cn");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.GROUP_MEMBER_ATTRIBUTE, "memberUid");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.USER_SEARCH_BASE, "dc=apache,dc=org");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.ANONYMOUS_BIND, "false");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.BIND_DN, "uid=hdfs,ou=people,ou=dev,dc=apache,dc=org");
    ldapConfiguration.setValueFor(AmbariServerConfigurationKey.BIND_PASSWORD, "hdfs");
  }

  @After
  public void tearDown() throws AmbariException, SQLException {
    H2DatabaseCleaner.clearDatabaseAndStopPersistenceService(injector);
  }

  @Test
  public void testLdapSync() throws AmbariException, InterruptedException {
    long time = System.currentTimeMillis();
    Set<LdapGroupDto> groups = populator.getExternalLdapGroupInfo();
    Set<LdapUserDto> users = populator.getExternalLdapUserInfo();
    Set<String> userNames = new HashSet<>();
    for (LdapUserDto user : users) {
      userNames.add(user.getUserName());
    }
    Set<String> groupNames = new HashSet<>();
    for (LdapGroupDto group : groups) {
      groupNames.add(group.getGroupName());
    }
    System.out.println("Data fetch: " + (System.currentTimeMillis() - time));
    time = System.currentTimeMillis();
    LdapBatchDto batchDto = new LdapBatchDto();
    populator.synchronizeLdapUsers(userNames, batchDto, false);
    populator.synchronizeLdapGroups(groupNames, batchDto, false);
    this.users.processLdapSync(batchDto);
    System.out.println("Initial sync: " + (System.currentTimeMillis() - time));
    time = System.currentTimeMillis();
    batchDto = new LdapBatchDto();
    populator.synchronizeLdapUsers(userNames, batchDto, false);
    populator.synchronizeLdapGroups(groupNames, batchDto, false);
    this.users.processLdapSync(batchDto);
    System.out.println("Subsequent sync: " + (System.currentTimeMillis() - time));
  }
}


text:
package com.crawljax.condition.browserwaiter;

import net.jcip.annotations.ThreadSafe;

import com.crawljax.browser.EmbeddedBrowser;

/**
 * Interface for defining conditions to wait for.
 *
 * @author dannyroest@gmail.com (Danny Roest)
 * @version $Id$
 */
@ThreadSafe
public interface ExpectedCondition {

	/**
	 * Is the expected condition satisfied.
	 *
	 * @param browser
	 *            the browser to execute the check on
	 * @return Whether the condition is satisfied.
	 */
	boolean isSatisfied(EmbeddedBrowser browser);

}


text:
class Tongue{

public:

    sf::Texture tongue;

Tongue(){
    angle = 0;
    size = 10; //HARDCODED ALERT it will be the width of the tongue
    timeSinceTriggered = 0;
    tongue.loadFromFile("res/tongue.png");
    texture = tongue;
    dest = sf::Vector2f(600,600);
    sprite.setTexture(tongue);
}

void reset(){
    timeSinceTriggered = 0;
}

sf::Vector2f getOrig() const {
    return orig;
}

void setOrig(const sf::Vector2f &value) {
    orig = value;
}

sf::Vector2f getDest() const {
    return dest;
}

void setDest(const sf::Vector2f value) {
    dest = value;
}

void setFatherRadius(float value) {
    fatherRadius = value;
}

void update(float deltatime) {
    sprite.setTexture(tongue);
    if(timeSinceTriggered < animationTime) timeSinceTriggered += deltatime;
}

float getAngle(sf::Vector2f &orig, sf::Vector2f &des) {
    return std::atan2(des.y - orig.y, des.x - orig.x)*180/(M_PI);
}

float getModule(const sf::Vector2f &orig, const sf::Vector2f &des) {
    return std::sqrt(std::pow(std::abs(des.x-orig.x), 2) + std::pow(std::abs(des.y-orig.y), 2));
}

void draw(sf::RenderWindow &window) {

    sf::Vector2f desp = dest-orig;
    float moduloDesp = getModule(orig,dest);
    float constante = fatherRadius*0.8;
    desp.x *= constante/moduloDesp;
    desp.y *= constante/moduloDesp;

    sf::Vector2f newOrig = orig + desp;

    float tongueLength = (getModule(newOrig,dest)/sprite.getLocalBounds().width);
    float tongueWidth = size/sprite.getLocalBounds().height;
    if(timeSinceTriggered < animationTime) {
        sprite.setScale( tongueLength * timeSinceTriggered/animationTime,
                                                                tongueWidth);
    }
    else sprite.setScale(tongueLength, tongueWidth);

    sprite.setOrigin(0, sprite.getLocalBounds().height/2);
    sprite.setPosition(newOrig);
    sprite.setRotation(getAngle(newOrig,dest));
    window.draw(sprite);

}

private:

    //Positions
    sf::Vector2f orig;
    sf::Vector2f dest;

    //Images
    sf::Sprite sprite;
    sf::Texture texture;

    //Variables
    float size;
    float angle;
    float timeSinceTriggered;
    float fatherRadius;

};

#endif // TONGUE_HPP


text:
namespace _03.InterfacesAndImplementation.Model
{
    using Contracts;

    public class Square : IShape
    {
        public Square(int x, int y, int size)
        {
            this.X = x;
            this.Y = y;
            this.Size = size;
        }

        public int X { get; set; }

        public int Y { get; set; }

        public int Size { get; }

        public void SetPosition(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }

        public double CalculateSurface() => this.Size * this.Size;
    }
}


text:
from . import relays

__red_end_user_data_statement__ = (
    "This cog does not persistently store data or metadata about users."
)

async def setup(bot):
    cog = relays.Relays(bot)
    bot.add_cog(cog)
    cog.init()


text:
package multiInheritance;

/**
 * Created by AOleynikov on 12.12.2018.
 */
public class startClass {
    public static void main(String[] args) {
        C c = new C();
        C.D d = c.new D();
    }
}


text:
package com.yujian.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

public class HttpUtil {
    public static final String TEXT_XML = "text/xml";

    public static final String UTF_8 = "UTF-8";

    public static final String APPLICATION_JSON = "application/json";

    public static final String APPLICATION_X_WWW_FORM_URLENCODED =
        "application/x-www-form-urlencoded";
    public static int DEFAULT_TIMEOUT = 30000;
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);

    public static String clientPost(String url, String content, String contentType, String charset) {
        return clientPost(url, content, contentType, charset, DEFAULT_TIMEOUT);
    }

    public static String clientPost(String url, String content, String contentType, String charset,
                                    int readTimeout) {
        ConnectionConfig connConfig =
            ConnectionConfig.custom().setCharset(Charset.forName(charset)).build();
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(readTimeout).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultConnectionConfig(connConfig)
                                                      .setDefaultSocketConfig(socketConfig).build();
        log.info("url={}", url);
        log.info("post={}", content);
        HttpPost http = new HttpPost(url);
        try {
            http.setHeader("Connection", "close");
            http.setEntity(new StringEntity(content, ContentType.create(contentType, charset)));
            CloseableHttpResponse response = client.execute(http);
            String result = IOUtils.toString(response.getEntity().getContent(), charset);
            response.close();
            client.close();
            log.info("result={}", result);
            return result;
        } catch (Exception e) {
            log.error("post error,url={} content={} contentType={} charset={} readTimeout={}", url,
                      content, contentType, charset, readTimeout, e);
            return "";
        } finally {
            http.releaseConnection();
        }
    }

    public static String clientGet(String url) {
        return clientGet(url, DEFAULT_TIMEOUT);
    }

    public static String clientGet(String url, int readTimeout) {
        return clientGet(url, DEFAULT_TIMEOUT, UTF_8);
    }

    public static String clientGet(String url, int readTimeout, String charset) {
        ConnectionConfig connConfig =
            ConnectionConfig.custom().setCharset(Charset.forName(charset)).build();
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(readTimeout).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultConnectionConfig(connConfig)
                                                      .setDefaultSocketConfig(socketConfig).build();
        log.info("url={}", url);
        HttpGet http = new HttpGet(url);
        try {
            http.setHeader("Connection", "close");
            CloseableHttpResponse response = client.execute(http);
            String result = IOUtils.toString(response.getEntity().getContent(), charset);
            response.close();
            client.close();
            log.info("result={}", result);
            return result;
        } catch (Exception e) {
            log.error("post error,url={} charset={} readTimeout={}", url, charset, readTimeout, e);
            return "";
        } finally {
            http.releaseConnection();
        }
    }
}


text:
import { TYPE, URL } from '../constants';
import { Rest } from 'grommet';

export function loadDeviceTypes() {
  return dispatch => {
    Rest.default.get(URL.DEVICE_TYPES).then((res) => {
      let deviceTypes = res.body;
      let deviceTypesMenus = deviceTypes.map((type) => {
        return type.name;
      });
      return dispatch({
        type: TYPE.INIT_DEVICE_TYPE,
        deviceTypesMenus,
        deviceTypes
      });
    });
  };
};

export function loadDevices() {
  return dispatch => {
    Rest.default.get(URL.DEVICES).then((res) => {
      let devices = res.body;
      console.log(devices);
      return dispatch({
        type: TYPE.LOAD_ALL_DEVICES,
        devices
      });
    });
  };
};


text:
 Projects

  Improvement In Face Recognition Technique

Research & Development

 January 2017 - Present

    As a Research and Development Project, working over improvement of face recognition techniques. Reading previous research papers and finding about the drawbacks of techniques used earlier. Currently reading techniques used by facebook and google for face recognition i.e., Deep Learning.

My Contribution:  Working on Google's research paper which gives detailed information about techniques used by Google to recognise the face. Developing Front-end of the Engine  and study regarding working of OCR and Elastic Search.

 Indian History Quest

 Question Answer Engine

 January 2017 - Present

To develop an efficient Q and A engine to answer the natural language query for INDIAN HISTORY in one sentence rather than providing the reference links for the answer.
                                                                  The efficiency of the Engine will be calculated in terms of processing time and specificness of the answer. Speciality of our Q and A enigne is that the domain of the questions asked will be INDIAN HISTORY which is Restricted domain.
                                                                  User can ask Factoid Questions which include who, when, where, what, which. The data source that will be used is Unstructured one like web pages, books, articles, etc.

 My COntribution: Learning about Natural language processing and working of an QAEngine. Also trying to work on Console.

 Launch Attack on DES Encryption

 Information Security

January 2017 - Present

     In this project, aim is to understand the innards of Data Encryption Standard (DES). DES is the first symmetric key encryption standard adopted by NIST and US federal agencies including banking sector.
                                Though DES is not the first or last block cipher it definitely is computer science's first step towards increasing security by using cryptography. The first block cipher happens to be Lucifer, introduced by
                                IBM and is a direct precursor to DES. Thus, DES is kind of influenced by the design of Lucifer. Built the original code for DES Encryption. After this design of launching an attack on DES code breaking using known plain text brute force
                                attack is required. For this phase "plain text" and "cipher text" is needed. The attack must find the "key" used to perform this encryption.

  Anvesh

The Smart Search Engine

 September 2016 - December 2016

   Developed a smart search engine which optimises the search. It provides result in a sorted way which makes easy for user to get the resulted document.
                                It also works as a online file management system. It stores the file in the online database or cloud where your file is safe. User can view as well as download the document.
                                The speciality of this engine is that it can search within the non- searchable pdfs as well as within images with the help of OCR and Elastic Search.
                                It convert images or non-serachable pdfs into text files and searchable pdfs and then performs the search. It also provide multiple search.

 My Contribution: Developing Front-end of the Engine  and study regarding working of OCR and Elastic Search

                               Check it out

 Event Management System

  Database System

 February 2016 - May 2016

    Developed a system for event management as a Database management system course project. The coding for database system is done using MySQL .

      Check it out

 Ayurveda Online Solutions

 Entrepreneurship Project

 September 2015 - December 2015

The project includes the business plan for a small venture. It is basically an idea of platform based business which connects costumers who require ayurvedic medicines and the suppliers. It also had additional features of onnline consultancy with doctor.

                            Check it out


text:
""" Defines classes for static models, derived from geodyn classes. """

import numpy as np
import matplotlib.pyplot as plt  # for figures
import math
from scipy.integrate import ode
from scipy.optimize import fsolve

# personal routines
from . import positions
from . import intersection
from . import geodyn

class Hemispheres(geodyn.Model):
    """ Static hemispheres:

        proxy is just defines as -1 in the western hemisphere and +1 in the eastern one."""

    def __init__(self, angletheta=0., anglephi=30.):
        self.name = "Static hemispheres"
        self.anglephi = anglephi
        self.angletheta = angletheta
        self.tau_ic = 0.

    def proxy_singlepoint(self, point, proxy_type):
        """ -1 in western hemisphere, +1 in the eastern hemisphere"""
        proxy = {}  # empty dict
        proxy["hemisphere"] = np.sign(
            np.sin((point.phi + self.anglephi) * np.pi / 180.))
        return proxy

    def velocity(self, time, point):
        """ has to be defined, but set to 0 """
        return [0., 0., 0.]

    def radius_ic(self, t):
        return self.rICB

    def verification(self):
        pass

class Radial_sym(geodyn.Model):
    """ Simple radial symmetry (no flow)

    An additional function can be added and given as a variable (fonction) to define the radial dependency.
    See the class Innermost_IC for an example.
    """

    def __init__(self, fonction=None):
        self.name = "Radial symmetry"
        self.tau_ic = 0.

        if fonction is None:  # TODO maybe should be something as "check if self.radial_dependency is defined, and if not, then defines it"?
            def fonction(r):
                return r
        # has to be a function with 1 argument (radius)
        self.radial_dependency = fonction

    def proxy_singlepoint(self, point, proxy_type):
        """  """
        proxy = {}  # empty dict
        proxy["radius"] = self.radial_dependency(point.r)
        #np.sign(np.sin((point.phi + self.anglephi) * np.pi / 180.))
        return proxy

    def velocity(self, time, point):
        """ has to be defined, but set to 0 """
        return [0., 0., 0.]

    def radius_ic(self, t):
        return self.rICB

    def verification(self):
        pass

class Innermost_IC(Radial_sym):
    """ """

    def __init__(self, radius_IIC):
        self.radius_IIC = radius_IIC

        def fonction(r):
            if r > self.radius_IIC:
                answer = 1.
            else:
                answer = 0.
            return answer

        Radial_sym.__init__(self, fonction)
        self.name = "Innermost inner core"