text:
<?php

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\Core\DataTransformer\PercentToLocalizedStringTransformer;
use Symfony\Component\Intl\Util\IntlTestHelper;

class PercentToLocalizedStringTransformerTest extends TestCase
{
    use ExpectDeprecationTrait;

    private $defaultLocale;

    protected function setUp(): void
    {
        $this->defaultLocale = \Locale::getDefault();
        \Locale::setDefault('en');
    }

    protected function tearDown(): void
    {
        \Locale::setDefault($this->defaultLocale);
    }

    public function testTransform()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals('10', $transformer->transform(0.1));
        $this->assertEquals('15', $transformer->transform(0.15));
        $this->assertEquals('12', $transformer->transform(0.1234));
        $this->assertEquals('200', $transformer->transform(2));
    }

    public function testTransformEmpty()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals('', $transformer->transform(null));
    }

    public function testTransformWithInteger()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, 'integer', \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals('0', $transformer->transform(0.1));
        $this->assertEquals('1', $transformer->transform(1));
        $this->assertEquals('15', $transformer->transform(15));
        $this->assertEquals('16', $transformer->transform(15.9));
    }

    public function testTransformWithScale()
    {
        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_AT');

        $transformer = new PercentToLocalizedStringTransformer(2, null, \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals('12,34', $transformer->transform(0.1234));
    }

    /**
     * @group legacy
     */
    public function testReverseTransformWithScaleAndRoundingDisabled()
    {
        $this->expectDeprecation('Since symfony/form 5.1: Not passing a rounding mode to "Symfony\Component\Form\Extension\Core\DataTransformer\PercentToLocalizedStringTransformer::__construct()" is deprecated. Starting with Symfony 6.0 it will default to "\NumberFormatter::ROUND_HALFUP".');

        $transformer = new PercentToLocalizedStringTransformer(2, PercentToLocalizedStringTransformer::FRACTIONAL);

        $this->assertEquals(0.0123456, $transformer->reverseTransform('1.23456'));
    }

    public function testReverseTransform()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals(0.1, $transformer->reverseTransform('10'));
        $this->assertEquals(0.15, $transformer->reverseTransform('15'));
        $this->assertEquals(0.12, $transformer->reverseTransform('12'));
        $this->assertEquals(2, $transformer->reverseTransform('200'));
    }

    public function reverseTransformWithRoundingProvider()
    {
        return [
            // towards positive infinity (1.6 -> 2, -1.6 -> -1)
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 35, \NumberFormatter::ROUND_CEILING],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 35, \NumberFormatter::ROUND_CEILING],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.5, \NumberFormatter::ROUND_CEILING],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.5, \NumberFormatter::ROUND_CEILING],
            [null, 0, '34.5', 0.35, \NumberFormatter::ROUND_CEILING],
            [null, 0, '34.4', 0.35, \NumberFormatter::ROUND_CEILING],
            [null, 1, '3.45', 0.035, \NumberFormatter::ROUND_CEILING],
            [null, 1, '3.44', 0.035, \NumberFormatter::ROUND_CEILING],
            // towards negative infinity (1.6 -> 1, -1.6 -> -2)
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 34, \NumberFormatter::ROUND_FLOOR],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 34, \NumberFormatter::ROUND_FLOOR],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.4, \NumberFormatter::ROUND_FLOOR],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.4, \NumberFormatter::ROUND_FLOOR],
            [null, 0, '34.5', 0.34, \NumberFormatter::ROUND_FLOOR],
            [null, 0, '34.4', 0.34, \NumberFormatter::ROUND_FLOOR],
            [null, 1, '3.45', 0.034, \NumberFormatter::ROUND_FLOOR],
            [null, 1, '3.44', 0.034, \NumberFormatter::ROUND_FLOOR],
            // away from zero (1.6 -> 2, -1.6 -> 2)
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 35, \NumberFormatter::ROUND_UP],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 35, \NumberFormatter::ROUND_UP],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.5, \NumberFormatter::ROUND_UP],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.5, \NumberFormatter::ROUND_UP],
            [null, 0, '34.5', 0.35, \NumberFormatter::ROUND_UP],
            [null, 0, '34.4', 0.35, \NumberFormatter::ROUND_UP],
            [null, 1, '3.45', 0.035, \NumberFormatter::ROUND_UP],
            [null, 1, '3.44', 0.035, \NumberFormatter::ROUND_UP],
            // towards zero (1.6 -> 1, -1.6 -> -1)
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 34, \NumberFormatter::ROUND_DOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 34, \NumberFormatter::ROUND_DOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.4, \NumberFormatter::ROUND_DOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.4, \NumberFormatter::ROUND_DOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 2, '37.37', 37.37, \NumberFormatter::ROUND_DOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 2, '2.01', 2.01, \NumberFormatter::ROUND_DOWN],
            [null, 0, '34.5', 0.34, \NumberFormatter::ROUND_DOWN],
            [null, 0, '34.4', 0.34, \NumberFormatter::ROUND_DOWN],
            [null, 1, '3.45', 0.034, \NumberFormatter::ROUND_DOWN],
            [null, 1, '3.44', 0.034, \NumberFormatter::ROUND_DOWN],
            [null, 2, '37.37', 0.3737, \NumberFormatter::ROUND_DOWN],
            [null, 2, '2.01', 0.0201, \NumberFormatter::ROUND_DOWN],
            // round halves (.5) to the next even number
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.6', 35, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 34, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 34, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '33.5', 34, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '32.5', 32, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.46', 3.5, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.4, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.4, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.35', 3.4, \NumberFormatter::ROUND_HALFEVEN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.25', 3.2, \NumberFormatter::ROUND_HALFEVEN],
            [null, 0, '34.6', 0.35, \NumberFormatter::ROUND_HALFEVEN],
            [null, 0, '34.5', 0.34, \NumberFormatter::ROUND_HALFEVEN],
            [null, 0, '34.4', 0.34, \NumberFormatter::ROUND_HALFEVEN],
            [null, 0, '33.5', 0.34, \NumberFormatter::ROUND_HALFEVEN],
            [null, 0, '32.5', 0.32, \NumberFormatter::ROUND_HALFEVEN],
            [null, 1, '3.46', 0.035, \NumberFormatter::ROUND_HALFEVEN],
            [null, 1, '3.45', 0.034, \NumberFormatter::ROUND_HALFEVEN],
            [null, 1, '3.44', 0.034, \NumberFormatter::ROUND_HALFEVEN],
            [null, 1, '3.35', 0.034, \NumberFormatter::ROUND_HALFEVEN],
            [null, 1, '3.25', 0.032, \NumberFormatter::ROUND_HALFEVEN],
            // round halves (.5) away from zero
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.6', 35, \NumberFormatter::ROUND_HALFUP],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 35, \NumberFormatter::ROUND_HALFUP],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 34, \NumberFormatter::ROUND_HALFUP],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.46', 3.5, \NumberFormatter::ROUND_HALFUP],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.5, \NumberFormatter::ROUND_HALFUP],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.4, \NumberFormatter::ROUND_HALFUP],
            [null, 0, '34.6', 0.35, \NumberFormatter::ROUND_HALFUP],
            [null, 0, '34.5', 0.35, \NumberFormatter::ROUND_HALFUP],
            [null, 0, '34.4', 0.34, \NumberFormatter::ROUND_HALFUP],
            [null, 1, '3.46', 0.035, \NumberFormatter::ROUND_HALFUP],
            [null, 1, '3.45', 0.035, \NumberFormatter::ROUND_HALFUP],
            [null, 1, '3.44', 0.034, \NumberFormatter::ROUND_HALFUP],
            // round halves (.5) towards zero
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.6', 35, \NumberFormatter::ROUND_HALFDOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.5', 34, \NumberFormatter::ROUND_HALFDOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 0, '34.4', 34, \NumberFormatter::ROUND_HALFDOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.46', 3.5, \NumberFormatter::ROUND_HALFDOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.45', 3.4, \NumberFormatter::ROUND_HALFDOWN],
            [PercentToLocalizedStringTransformer::INTEGER, 1, '3.44', 3.4, \NumberFormatter::ROUND_HALFDOWN],
            [null, 0, '34.6', 0.35, \NumberFormatter::ROUND_HALFDOWN],
            [null, 0, '34.5', 0.34, \NumberFormatter::ROUND_HALFDOWN],
            [null, 0, '34.4', 0.34, \NumberFormatter::ROUND_HALFDOWN],
            [null, 1, '3.46', 0.035, \NumberFormatter::ROUND_HALFDOWN],
            [null, 1, '3.45', 0.034, \NumberFormatter::ROUND_HALFDOWN],
            [null, 1, '3.44', 0.034, \NumberFormatter::ROUND_HALFDOWN],
        ];
    }

    /**
     * @dataProvider reverseTransformWithRoundingProvider
     */
    public function testReverseTransformWithRounding($type, $scale, $input, $output, $roundingMode)
    {
        $transformer = new PercentToLocalizedStringTransformer($scale, $type, $roundingMode);

        $this->assertSame($output, $transformer->reverseTransform($input));
    }

    public function testReverseTransformEmpty()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $this->assertNull($transformer->reverseTransform(''));
    }

    public function testReverseTransformWithInteger()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, 'integer', \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals(10, $transformer->reverseTransform('10'));
        $this->assertEquals(15, $transformer->reverseTransform('15'));
        $this->assertEquals(12, $transformer->reverseTransform('12'));
        $this->assertEquals(200, $transformer->reverseTransform('200'));
    }

    public function testReverseTransformWithScale()
    {
        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_AT');

        $transformer = new PercentToLocalizedStringTransformer(2, null, \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals(0.1234, $transformer->reverseTransform('12,34'));
    }

    public function testTransformExpectsNumeric()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $this->expectException(TransformationFailedException::class);

        $transformer->transform('foo');
    }

    public function testReverseTransformExpectsString()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $this->expectException(TransformationFailedException::class);

        $transformer->reverseTransform(1);
    }

    public function testDecimalSeparatorMayBeDotIfGroupingSeparatorIsNotDot()
    {
        IntlTestHelper::requireFullIntl($this, '4.8.1.1');

        \Locale::setDefault('fr');
        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        // completely valid format
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234,5'));
        // accept dots
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234.5'));
        // omit group separator
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
    }

    public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot()
    {
        $this->expectException(TransformationFailedException::class);
        // Since we test against "de_DE", we need the full implementation
        IntlTestHelper::requireFullIntl($this, '4.8.1.1');

        \Locale::setDefault('de_DE');

        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('1.234.5');
    }

    public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDotWithNoGroupSep()
    {
        $this->expectException(TransformationFailedException::class);
        // Since we test against "de_DE", we need the full implementation
        IntlTestHelper::requireFullIntl($this, '4.8.1.1');

        \Locale::setDefault('de_DE');

        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('1234.5');
    }

    public function testDecimalSeparatorMayBeDotIfGroupingSeparatorIsDotButNoGroupingUsed()
    {
        // Since we test against other locales, we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('fr');
        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
    }

    public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsNotComma()
    {
        // Since we test against other locales, we need the full implementation
        IntlTestHelper::requireFullIntl($this, '4.8.1.1');

        \Locale::setDefault('bg');
        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        // completely valid format
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234.5'));
        // accept commas
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234,5'));
        // omit group separator
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
    }

    public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma()
    {
        $this->expectException(TransformationFailedException::class);
        IntlTestHelper::requireFullIntl($this, '4.8.1.1');

        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('1,234,5');
    }

    public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsCommaWithNoGroupSep()
    {
        $this->expectException(TransformationFailedException::class);
        IntlTestHelper::requireFullIntl($this, '4.8.1.1');

        $transformer = new PercentToLocalizedStringTransformer(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('1234,5');
    }

    public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsCommaButNoGroupingUsed()
    {
        $transformer = new PercentToLocalizedStringTransformerWithoutGrouping(1, 'integer', \NumberFormatter::ROUND_HALFUP);

        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
    }

    public function testReverseTransformDisallowsLeadingExtraCharacters()
    {
        $this->expectException(TransformationFailedException::class);
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('foo123');
    }

    public function testReverseTransformDisallowsCenteredExtraCharacters()
    {
        $this->expectException(TransformationFailedException::class);
        $this->expectExceptionMessage('The number contains unrecognized characters: "foo3"');
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('12foo3');
    }

    /**
     * @requires extension mbstring
     */
    public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte()
    {
        $this->expectException(TransformationFailedException::class);
        $this->expectExceptionMessage('The number contains unrecognized characters: "foo8"');
        // Since we test against other locales, we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('ru');

        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform("12\xc2\xa0345,67foo8");
    }

    public function testReverseTransformDisallowsTrailingExtraCharacters()
    {
        $this->expectException(TransformationFailedException::class);
        $this->expectExceptionMessage('The number contains unrecognized characters: "foo"');
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform('123foo');
    }

    /**
     * @requires extension mbstring
     */
    public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte()
    {
        $this->expectException(TransformationFailedException::class);
        $this->expectExceptionMessage('The number contains unrecognized characters: "foo"');
        // Since we test against other locales, we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('ru');

        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP);

        $transformer->reverseTransform("12\xc2\xa0345,678foo");
    }

    public function testTransformForHtml5Format()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP, true);

        // Since we test against "de_CH", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_CH');

        $this->assertEquals('10', $transformer->transform(0.104));
        $this->assertEquals('11', $transformer->transform(0.105));
        $this->assertEquals('200000', $transformer->transform(2000));
    }

    public function testTransformForHtml5FormatWithInteger()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, 'integer', \NumberFormatter::ROUND_HALFUP, true);

        // Since we test against "de_CH", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_CH');

        $this->assertEquals('0', $transformer->transform(0.1));
        $this->assertEquals('1234', $transformer->transform(1234));
    }

    public function testTransformForHtml5FormatWithScale()
    {
        // Since we test against "de_CH", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_CH');

        $transformer = new PercentToLocalizedStringTransformer(2, null, \NumberFormatter::ROUND_HALFUP, true);

        $this->assertEquals('12.34', $transformer->transform(0.1234));
    }

    public function testReverseTransformForHtml5Format()
    {
        // Since we test against "de_CH", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_CH');

        $transformer = new PercentToLocalizedStringTransformer(null, null, \NumberFormatter::ROUND_HALFUP, true);

        $this->assertEquals(0.02, $transformer->reverseTransform('1.5')); // rounded up, for 2 decimals
        $this->assertEquals(0.15, $transformer->reverseTransform('15'));
        $this->assertEquals(2000, $transformer->reverseTransform('200000'));
    }

    public function testReverseTransformForHtml5FormatWithInteger()
    {
        // Since we test against "de_CH", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_CH');

        $transformer = new PercentToLocalizedStringTransformer(null, 'integer', \NumberFormatter::ROUND_HALFUP, true);

        $this->assertEquals(10, $transformer->reverseTransform('10'));
        $this->assertEquals(15, $transformer->reverseTransform('15'));
        $this->assertEquals(12, $transformer->reverseTransform('12'));
        $this->assertEquals(200, $transformer->reverseTransform('200'));
    }

    public function testReverseTransformForHtml5FormatWithScale()
    {
        // Since we test against "de_CH", we need the full implementation
        IntlTestHelper::requireFullIntl($this, false);

        \Locale::setDefault('de_CH');

        $transformer = new PercentToLocalizedStringTransformer(2, null, \NumberFormatter::ROUND_HALFUP, true);

        $this->assertEquals(0.1234, $transformer->reverseTransform('12.34'));
    }
}

class PercentToLocalizedStringTransformerWithoutGrouping extends PercentToLocalizedStringTransformer
{
    protected function getNumberFormatter(): \NumberFormatter
    {
        $formatter = new \NumberFormatter(\Locale::getDefault(), \NumberFormatter::DECIMAL);
        $formatter->setAttribute(\NumberFormatter::GROUPING_USED, false);

        return $formatter;
    }
}


text:
#ifndef TALK_P2P_BASE_TRANSPORTINFO_H_
#define TALK_P2P_BASE_TRANSPORTINFO_H_

#include <string>
#include <vector>

#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/transportdescription.h"
#include "webrtc/base/helpers.h"

namespace cricket {

// A TransportInfo is NOT a transport-info message.  It is comparable
// to a "ContentInfo". A transport-infos message is basically just a
// collection of TransportInfos.
struct TransportInfo {
  TransportInfo() {}

  TransportInfo(const std::string& content_name,
                const TransportDescription& description)
      : content_name(content_name),
        description(description) {}

  std::string content_name;
  TransportDescription description;
};

typedef std::vector<TransportInfo> TransportInfos;

}  // namespace cricket

#endif  // TALK_P2P_BASE_TRANSPORTINFO_H_

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.DataLayer;
using UserGroupPermissions.ExtensionMethods;

namespace UserGroupPermissions.Businesslogic
{
    /// <summary>
    ///
    /// </summary>
    public class UserTypePermissions
    {
            public int NodeId { get; private set; }
            public int UserTypeId { get; private set; }
            public char PermissionId { get; private set; }

            /// <summary>
            /// Private constructor, this class cannot be directly instantiated
            /// </summary>
            private UserTypePermissions() { }

            private static ISqlHelper SqlHelper
            {
                get { return Application.SqlHelper; }
            }

            [MethodImpl(MethodImplOptions.Synchronized)]
            public static void MakeNew(umbraco.BusinessLogic.UserType userType, umbraco.cms.businesslogic.CMSNode Node, char PermissionKey)
            {
                IParameter[] parameters = new IParameter[] { SqlHelper.CreateParameter("@userTypeId", userType.Id),
                                                         SqlHelper.CreateParameter("@nodeId", Node.Id),
                                                         SqlHelper.CreateParameter("@permission", PermissionKey.ToString()) };

                // Method is synchronized so exists remains consistent (avoiding race condition)
                bool exists = SqlHelper.ExecuteScalar<int>("SELECT COUNT(userTypeId) FROM UserGroupPermissions_UserType2NodePermission WHERE userTypeId = @userTypeId AND nodeId = @nodeId AND permission = @permission",
                                                           parameters) > 0;
                if (!exists)
                    SqlHelper.ExecuteNonQuery("INSERT INTO UserGroupPermissions_UserType2NodePermission (userTypeId, nodeId, permission) VALUES (@userTypeId, @nodeId, @permission)",
                                              parameters);
            }

            /// <summary>
            /// Returns the permissions for a user
            /// </summary>
            /// <param name="user"></param>
            /// <returns></returns>
            public static IEnumerable<UserTypePermissions> GetUserTypePermissions(UserType userType)
            {
                var items = new List<UserTypePermissions>();
                using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from UserGroupPermissions_UserType2NodePermission where userTypeId = @userTypeId order by nodeId", SqlHelper.CreateParameter("@userTypeId", userType.Id)))
                {
                    while (dr.Read())
                    {
                        items.Add(new UserTypePermissions()
                        {
                            NodeId = dr.GetInt("nodeId"),
                            PermissionId = Convert.ToChar(dr.GetString("permission")),
                            UserTypeId = dr.GetInt("userTypeId")
                        });
                    }
                }
                return items;
            }

            /// <summary>
            /// Returns the permissions for a node
            /// </summary>
            /// <param name="user"></param>
            /// <returns></returns>
            public static IEnumerable<UserTypePermissions> GetNodePermissions(CMSNode node)
            {
                var items = new List<UserTypePermissions>();
                using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from UserGroupPermissions_UserType2NodePermission where nodeId = @nodeId order by nodeId", SqlHelper.CreateParameter("@nodeId", node.Id)))
                {
                    while (dr.Read())
                    {
                        items.Add(new UserTypePermissions()
                        {
                            NodeId = dr.GetInt("nodeId"),
                            PermissionId = Convert.ToChar(dr.GetString("permission")),
                            UserTypeId = dr.GetInt("userTypeId")
                        });
                    }
                }
                return items;
            }

            /// <summary>
            /// Copies the usertype permissions for single user
            /// </summary>
            /// <param name="user">The user.</param>
            public static void CopyPermissionsForSingleUser(User user)
            {
                var permissions = GetUserTypePermissions(user.UserType);

                foreach (var permission in permissions)
                {
                    Permission.MakeNew(user, new CMSNode(permission.NodeId), permission.PermissionId);
                    user.initCruds();
                }

            }

            /// <summary>
            /// Copies all  permissions to related users of the usertype
            /// </summary>
            /// <param name="userType">Type of the user.</param>
            /// <param name="node">The node.</param>
            public static void CopyPermissions(UserType userType, CMSNode node)
            {
                string permissions = userType.GetPermissions(node.Path);
                foreach (User user in userType.GetAllRelatedUsers())
                {
                    if (!user.IsAdmin() && !user.Disabled)
                    {
                        Permission.UpdateCruds(user, node, permissions);
                        user.initCruds();
                    }
                }
            }

            /// <summary>
            /// Delets all permissions for the node/user combination
            /// </summary>
            /// <param name="user"></param>
            /// <param name="node"></param>
            public static void DeletePermissions(UserType userType, CMSNode node)
            {
                // delete all settings on the node for this user
                SqlHelper.ExecuteNonQuery("delete from UserGroupPermissions_UserType2NodePermission where userTypeId = @userTypeId and nodeId = @nodeId",
                    SqlHelper.CreateParameter("@userTypeId", userType.Id), SqlHelper.CreateParameter("@nodeId", node.Id));
            }

            /// <summary>
            /// deletes all permissions for the user
            /// </summary>
            /// <param name="user"></param>
            public static void DeletePermissions(UserType userType)
            {
                // delete all settings on the node for this user
                SqlHelper.ExecuteNonQuery("delete from UserGroupPermissions_UserType2NodePermission where userTypeId = @userTypeId",
                    SqlHelper.CreateParameter("@userTypeId", userType.Id));
            }

            public static void DeletePermissions(int userTypeId, int[] iNodeIDs)
            {
                string sql = "DELETE FROM UserGroupPermissions_UserType2NodePermission WHERE nodeID IN ({0}) AND userTypeId=@userTypeId";
                string nodeIDs = string.Join(",", Array.ConvertAll<int, string>(iNodeIDs, Converter));
                sql = string.Format(sql, nodeIDs);
                SqlHelper.ExecuteNonQuery(sql,
                    new IParameter[] { SqlHelper.CreateParameter("@userTypeId", userTypeId) });
            }
            //public static void DeletePermissions(int iUserID, int iNodeID)
            //{
            //    DeletePermissions(iUserID, new int[] { iNodeID });
            //}
            private static string Converter(int from)
            {
                return from.ToString();
            }

            /// <summary>
            /// delete all permissions for this node
            /// </summary>
            /// <param name="node"></param>
            public static void DeletePermissions(CMSNode node)
            {

                SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodePermission where nodeId = @nodeId",
                    SqlHelper.CreateParameter("@nodeId", node.Id));
            }

            [MethodImpl(MethodImplOptions.Synchronized)]
            public static void UpdateCruds(UserType userType, CMSNode node, string permissions)
            {
                // delete all settings on the node for this user
                DeletePermissions(userType, node);

                // Loop through the permissions and create them
                foreach (char c in permissions.ToCharArray())
                    MakeNew(userType, node, c);
            }
        }
    }


text:
/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include "StorageService.hpp"

namespace AssimpWorker {

	StorageService::StorageService() {

	}

	StorageService::~StorageService() {

	}
}


text:
<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1"
         xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">

    <sys:environment>

        <sys:moduleId>
            <sys:groupId>CONNECT</sys:groupId>
            <sys:artifactId>DocumentQuery</sys:artifactId>
            <sys:version>2.0</sys:version>
            <sys:type>war</sys:type>
        </sys:moduleId>

        <sys:inverse-classloading/>

    </sys:environment>

    <context-root>Gateway/DocumentQuery/2_0</context-root>

</web-app>


text:
<?xml version="1.0"?>
<vertical display_name="Lecture code handout (PDF)">
  <html url_name="Lecture_code_handout__PDF__html4"/>
</vertical>


text:
<?php
/**
 * Created with IntelliJ IDEA by Nick Chervyakov.
 * User: Nikolay Chervyakov
 * Date: 21.05.2015
 * Time: 14:36
  */

namespace AppBundle\Model;

use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as JMSSerializer;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class ModelStatCollection
 * @package AppBundle\Model
 * @JMSSerializer\XmlRoot("model_stats")
 */
class ModelStatCollection extends AbstractRestCollection
{
    /**
     * @var ArrayCollection
     * @JMSSerializer\Type("array<AppBundle\Entity\Conversation>")
     * @JMSSerializer\XmlList("conversation")
     * @JMSSerializer\Groups({"model_read", "admin_read", "model_stat"})
     */
    private $conversations;

    /**
     * @var double
     *
     * @JMSSerializer\Type("double")
     * @JMSSerializer\Groups({"model_read", "admin_read", "model_stat"})
     */
    private $totalEarnings;

    /**
     * @var int
     * @JMSSerializer\Type("integer")
     * @JMSSerializer\Groups({"model_read", "admin_read", "model_stat"})
     */
    private $totalSeconds;

    /**
     * ModelStatCollection constructor.
     * @param array $conversations
     * @param int $page
     * @param int $perPage
     */
    public function __construct($conversations = [], $page = 1, $perPage = 10)
    {
        if (!($conversations instanceof ArrayCollection)) {
            if (is_array($conversations)) {
                $conversations = new ArrayCollection($conversations);
            } else {
                $conversations = new ArrayCollection();
            }
        }
        $this->conversations = $conversations;
        $this->setPage($page);
        $this->setPerPage($perPage);
    }

    /**
     * @return ArrayCollection|array
     */
    public function getConversations()
    {
        return $this->conversations;
    }

    /**
     * @param ArrayCollection|array $conversations
     */
    public function setConversations($conversations)
    {
        $this->conversations = $conversations;
    }

    /**
     * @return float
     */
    public function getTotalEarnings()
    {
        return $this->totalEarnings;
    }

    /**
     * @param float $totalEarnings
     */
    public function setTotalEarnings($totalEarnings)
    {
        $this->totalEarnings = $totalEarnings;
    }

    /**
     * @return int
     */
    public function getTotalSeconds()
    {
        return $this->totalSeconds;
    }

    /**
     * @param int $totalSeconds
     */
    public function setTotalSeconds($totalSeconds)
    {
        $this->totalSeconds = $totalSeconds;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace RockSolidIoc.Tests
{
  [TestClass]
  public class UseResolverAttributeStrategyImplTests
  {

    [TestMethod]
    public void TestWithAttributedObject()
    {
      Mock<IResolverMap> mockMap = new Mock<IResolverMap>();
      UseResolverAttributeStrategyImpl testStrategy = new UseResolverAttributeStrategyImpl();
      Type requestedType = typeof(AttributedWithResolver);
      Assert.AreEqual(typeof(ResolverImpl1), testStrategy.FindResolver(requestedType, String.Empty));
      Assert.AreEqual(typeof(ResolverImpl2), testStrategy.FindResolver(requestedType, "2"));
    }

    [TestMethod]
    public void TestNoAttributesWithNextStep()
    {
      Mock<IResolverMap> mockMap = new Mock<IResolverMap>();
      UseResolverAttributeStrategyImpl testStrategy = new UseResolverAttributeStrategyImpl();
      Mock<FindResolverStrategy> mockNextStep = new Mock<FindResolverStrategy>();
      testStrategy.NextStep = mockNextStep.Object;
      Type requestedType = typeof(object);
      String requestedIdentifier = "identifier";
      testStrategy.FindResolver(requestedType, requestedIdentifier);
      mockNextStep.Verify(step => step.FindResolver(requestedType, requestedIdentifier));
    }

    [TestMethod]
    public void TestNoAttributesNoNextStep()
    {
      Mock<IResolverMap> mockMap = new Mock<IResolverMap>();
      UseResolverAttributeStrategyImpl testStrategy = new UseResolverAttributeStrategyImpl();
      Assert.IsNull(testStrategy.FindResolver(typeof(object), "identifier"));
    }

  }

}


text:
package com.anttaylor.searchjpg.utils;

import android.content.Context;

/**
 * Created by Taylor on 2016/5/30 11:43.
 * Description:
 */
public class UIUtils {

    /**
     * 获取上下文
     */
    public static Context getContext() {
        return UtilsApplication.getContext();
    }

    /**
     * dp转化成px
     */
    public static int dip2px(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f);
    }
}


text:
package com.intellij.lang.javascript.formatter;

import javax.annotation.Nonnull;

import com.intellij.formatting.Block;
import com.intellij.formatting.FormattingDocumentModel;
import com.intellij.formatting.FormattingModel;
import com.intellij.formatting.FormattingModelProvider;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;

/**
 * @author ven
 */
public class JSFormattingModel implements FormattingModel
{
	private FormattingModel myModel;

	public JSFormattingModel(final PsiFile file, CodeStyleSettings settings, final Block rootBlock)
	{
		myModel = FormattingModelProvider.createFormattingModelForPsiFile(file, rootBlock, settings);
	}

	@Override
	@Nonnull
	public Block getRootBlock()
	{
		return myModel.getRootBlock();
	}

	@Override
	@Nonnull
	public FormattingDocumentModel getDocumentModel()
	{
		return myModel.getDocumentModel();
	}

	@Override
	public TextRange replaceWhiteSpace(TextRange textRange, String whiteSpace)
	{
		return myModel.replaceWhiteSpace(textRange, whiteSpace);
	}

	@Override
	public TextRange shiftIndentInsideRange(ASTNode node, TextRange range, int indent)
	{
		return myModel.shiftIndentInsideRange(node, range, indent);
	}

	@Override
	public void commitChanges()
	{
		myModel.commitChanges();
	}
}


text:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/expenseFragment"
    tools:context="io.rg.mp.ui.MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="12dp"
        app:layout_constraintEnd_toEndOf="@+id/expenseCardView"
        app:layout_constraintStart_toStartOf="@+id/expenseCardView"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/categoryTextInputLayout"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="8dp"
        android:hint="@string/category_hint"
        app:layout_constraintBottom_toTopOf="@+id/descriptionTextInputLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/categoryEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:focusable="false"
            android:inputType="textNoSuggestions" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/amountTextInputLayout"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="16dp"
        android:hint="@string/amount_hint"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/addButton">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/amountEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="numberDecimal"
            android:text="" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/addButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:text="@string/button_add"
        app:layout_constraintBottom_toBottomOf="@+id/amountTextInputLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/dateTextInputLayout"
        app:layout_constraintTop_toTopOf="@+id/amountTextInputLayout" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/descriptionTextInputLayout"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:hint="@string/description_hint"
        app:layout_constraintBottom_toTopOf="@+id/amountTextInputLayout"
        app:layout_constraintEnd_toStartOf="@+id/dateTextInputLayout"
        app:layout_constraintStart_toStartOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/descriptionEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="text" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/dateTextInputLayout"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:hint="@string/date_hint"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/categoryTextInputLayout">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/dateEditText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:focusable="false"
            android:inputType="textNoSuggestions"
            android:textAlignment="center"
            tools:text="01/01/2017" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.card.MaterialCardView
        android:id="@+id/expenseCardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >

            <TextView
                android:id="@+id/titleTextView"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="16dp"
                android:textAppearance="@android:style/TextAppearance.Large"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:text="February 2019" />

            <TextView
                android:id="@+id/currentBalanceTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@android:style/TextAppearance.Medium"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="@+id/plannedBalanceTextView"
                app:layout_constraintTop_toTopOf="@+id/currentBalanceLabel"
                tools:text="@sample/money" />

            <TextView
                android:id="@+id/plannedBalanceTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:textAppearance="@android:style/TextAppearance.Medium"
                app:layout_constraintStart_toEndOf="@+id/plannedBalanceLabel"
                app:layout_constraintTop_toTopOf="@+id/plannedBalanceLabel"
                tools:text="@sample/money" />

            <TextView
                android:id="@+id/actualBalanceTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@android:style/TextAppearance.Medium"
                app:layout_constraintStart_toStartOf="@+id/plannedBalanceTextView"
                app:layout_constraintTop_toTopOf="@+id/actualBalanceLabel"
                tools:text="@sample/money" />

            <TextView
                android:id="@+id/currentBalanceLabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="24dp"
                android:layout_marginTop="8dp"
                android:text="@string/current_balance"
                android:textAppearance="@android:style/TextAppearance.Medium"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/titleTextView" />

            <TextView
                android:id="@+id/plannedBalanceLabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="24dp"
                android:layout_marginTop="24dp"
                android:text="@string/planned_expenses"
                android:textAppearance="@android:style/TextAppearance.Medium"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/currentBalanceLabel" />

            <TextView
                android:id="@+id/actualBalanceLabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="24dp"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:text="@string/actual_expenses"
                android:textAppearance="@android:style/TextAppearance.Medium"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/plannedBalanceLabel" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </com.google.android.material.card.MaterialCardView>

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.67"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
package search

import (
	"encoding/gob"
	"fmt"
	"github.com/ctdk/goiardi/client"
	"github.com/ctdk/goiardi/config"
	"github.com/ctdk/goiardi/databag"
	"github.com/ctdk/goiardi/environment"
	"github.com/ctdk/goiardi/indexer"
	"github.com/ctdk/goiardi/node"
	"github.com/ctdk/goiardi/role"
	"testing"
	//"time"
)

// Most search testing can be handled fine with chef-pedant, but that's no
// reason to not have some go tests for it too.

var node1 *node.Node
var node2 *node.Node
var node3 *node.Node
var node4 *node.Node
var role1 *role.Role
var role2 *role.Role
var role3 *role.Role
var role4 *role.Role
var env1 *environment.ChefEnvironment
var env2 *environment.ChefEnvironment
var env3 *environment.ChefEnvironment
var env4 *environment.ChefEnvironment
var client1 *client.Client
var client2 *client.Client
var client3 *client.Client
var client4 *client.Client
var dbag1 *databag.DataBag
var dbag2 *databag.DataBag
var dbag3 *databag.DataBag
var dbag4 *databag.DataBag

func makeSearchItems() int {
	indexer.Initialize(config.Config)
	/* Gotta populate the search index */
	nodes := make([]*node.Node, 4)
	roles := make([]*role.Role, 4)
	envs := make([]*environment.ChefEnvironment, 4)
	clients := make([]*client.Client, 4)
	dbags := make([]*databag.DataBag, 4)
	gob.Register(new(node.Node))
	gob.Register(new(role.Role))
	gob.Register(new(environment.ChefEnvironment))
	gob.Register(new(client.Client))
	gob.Register(new(databag.DataBag))

	for i := 0; i < 4; i++ {
		nodes[i], _ = node.New(fmt.Sprintf("node%d", i))
		nodes[i].Default["baz"] = fmt.Sprintf("borb")
		nodes[i].Default["blurg"] = fmt.Sprintf("b%d", i)
		nodes[i].Save()
		roles[i], _ = role.New(fmt.Sprintf("role%d", i))
		roles[i].Save()
		envs[i], _ = environment.New(fmt.Sprintf("env%d", i))
		envs[i].Save()
		clients[i], _ = client.New(fmt.Sprintf("client%d", i))
		clients[i].Save()
		dbags[i], _ = databag.New(fmt.Sprintf("databag%d", i))
		dbags[i].Save()
		dbi := make(map[string]interface{})
		dbi["id"] = fmt.Sprintf("dbi%d", i)
		dbi["foo"] = fmt.Sprintf("dbag_item_%d", i)
		dbags[i].NewDBItem(dbi)
	}
	node1 = nodes[0]
	node2 = nodes[1]
	node3 = nodes[2]
	node4 = nodes[3]
	role1 = roles[0]
	role2 = roles[1]
	role3 = roles[2]
	role4 = roles[3]
	env1 = envs[0]
	env2 = envs[1]
	env3 = envs[2]
	env4 = envs[3]
	client1 = clients[0]
	client2 = clients[1]
	client3 = clients[2]
	client4 = clients[3]
	dbag1 = dbags[0]
	dbag2 = dbags[1]
	dbag3 = dbags[2]
	dbag4 = dbags[3]

	/* Make this function return something so the compiler's happy building
	 * the tests. */
	return 1
}

var v = makeSearchItems()

var searcher = &TrieSearch{}

func TestFoo(t *testing.T) {
	return
}

/* Only basic search tests are here. The stronger tests are handled in
 * chef-pedant, but these tests are meant to check basic search functionality.
 */

func TestSearchNode(t *testing.T) {
	n, _ := searcher.Search("node", "name:node1", 1000, "id ASC", 0, nil)
	if len(n) == 0 || n[0]["name"] != "node1" {
		t.Errorf("nothing returned from search")
	}
}

func TestSearchNodeAll(t *testing.T) {
	n, _ := searcher.Search("node", "*:*", 1000, "id ASC", 0, nil)
	if len(n) != 4 {
		t.Errorf("Incorrect number of items returned, expected 4, got %d :: %v", len(n), n)
	}
}

func TestSearchNodeFalse(t *testing.T) {
	n, _ := searcher.Search("node", "foo:bar AND NOT foo:bar", 1000, "id ASC", 0, nil)
	if len(n) != 0 {
		t.Errorf("Incorrect number of items returned, expected 0, got %d", len(n))
	}
}

func TestSearchNodeAttr(t *testing.T) {
	n, _ := searcher.Search("node", "name:node1 AND NOT baz:urb", 1000, "id ASC", 0, nil)
	if len(n) != 1 {
		t.Errorf("Incorrect number of items returned, expected 1, got %d", len(n))
	}
}

func TestSearchNodeAttrExists(t *testing.T) {
	n, _ := searcher.Search("node", "name:node1 AND NOT baz:borb", 1000, "id ASC", 0, nil)
	if len(n) != 0 {
		t.Errorf("Incorrect number of items returned, expected 0, got %d", len(n))
	}
}

func TestSearchNodeAttrAndExists(t *testing.T) {
	n, _ := searcher.Search("node", "name:node1 AND baz:borb", 1000, "id ASC", 0, nil)
	if len(n) != 1 {
		t.Errorf("Incorrect number of items returned, expected 1, got %d", len(n))
	}
}

func TestSearchNodeAttrAndNotExists(t *testing.T) {
	n, _ := searcher.Search("node", "name:node1 AND baz:urb", 1000, "id ASC", 0, nil)
	if len(n) != 0 {
		t.Errorf("Incorrect number of items returned, expected 0, got %d", len(n))
	}
}

func TestSearchRole(t *testing.T) {
	r, _ := searcher.Search("role", "name:role1", 1000, "id ASC", 0, nil)
	if r[0]["name"] != "role1" {
		t.Errorf("nothing returned from search")
	}
}

func TestSearchRoleAll(t *testing.T) {
	n, _ := searcher.Search("role", "*:*", 1000, "id ASC", 0, nil)
	if len(n) != 4 {
		t.Errorf("Incorrect number of items returned, expected 4, got %d", len(n))
	}
}

func TestSearchEnv(t *testing.T) {
	e, _ := searcher.Search("environment", "name:env1", 1000, "id ASC", 0, nil)
	if e[0]["name"] != "env1" {
		t.Errorf("nothing returned from search")
	}
}

func TestSearchEnvAll(t *testing.T) {
	n, _ := searcher.Search("environment", "*:*", 1000, "id ASC", 0, nil)
	if len(n) != 4 {
		t.Errorf("Incorrect number of items returned, expected 4, got %d", len(n))
	}
}

func TestSearchClient(t *testing.T) {
	c, _ := searcher.Search("client", "name:client1", 1000, "id ASC", 0, nil)
	if c[0]["name"] != "client1" {
		t.Errorf("nothing returned from search")
	}
}

func TestSearchClientAll(t *testing.T) {
	n, _ := searcher.Search("client", "*:*", 1000, "id ASC", 0, nil)
	if len(n) != 4 {
		t.Errorf("Incorrect number of items returned, expected 4, got %d", len(n))
	}
}

func TestSearchDbag(t *testing.T) {
	d, _ := searcher.Search("databag1", "foo:dbag_item_1", 1000, "id ASC", 0, nil)
	if len(d) == 0 {
		t.Errorf("nothing returned from search")
	}
}

func TestSearchDbagAll(t *testing.T) {
	d, _ := searcher.Search("databag1", "*:*", 1000, "id ASC", 0, nil)
	if len(d) != 1 {
		t.Errorf("Incorrect number of items returned, expected 1, got %d", len(d))
	}
}

// Probably don't want this as an always test, but it's handy to have available.
/*
func TestEmbiggenSearch(t *testing.T) {
	for i := 4; i < 35000; i++ {
		n, _ := node.New(fmt.Sprintf("node%d", i))
		n.Save()
		r, _ := role.New(fmt.Sprintf("role%d", i))
		r.Save()
		e, _ := environment.New(fmt.Sprintf("env%d", i))
		e.Save()
		c, _ := client.New(fmt.Sprintf("client%d", i))
		c.Save()
		d, _ := databag.New(fmt.Sprintf("databag%d", i))
		d.Save()
		dbi := make(map[string]interface{})
		dbi["id"] = fmt.Sprintf("dbi%d", i)
		dbi["foo"] = fmt.Sprintf("dbag_item_%d", i)
		d.NewDBItem(dbi)
	}
	time.Sleep(1 * time.Second)
	n, _ := searcher.Search("client", "*:*", 1000, "id ASC", 0, nil)
	if len(n) != 35000 {
		t.Errorf("Incorrect number of items returned, expected 500, got %d", len(n))
	}
	c, _ := searcher.Search("node", "*:*", 1000, "id ASC", 0, nil)
	if len(c) != 35000 {
		t.Errorf("Incorrect number of nodes returned, expected 500, got %d", len(n))
	}
	e, _ := searcher.Search("environment", "name:env11666", 1000, "id ASC", 0, nil)
	if e[0].(*environment.ChefEnvironment).Name != "env11666" {
		t.Errorf("nothing returned from search")
	}
}
*/


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/maven-v4_0_0.xsd">
  <parent>
    <artifactId>samples</artifactId>
    <groupId>com.diegoschivo</groupId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>apache-lucene-sample1</artifactId>
  <packaging>jar</packaging>
  <name>Apache Lucene Sample 1</name>
  <build>
    <plugins>
      <plugin>
        <groupId>com.mycila.maven-license-plugin</groupId>
        <artifactId>maven-license-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  <dependencies>
      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
      </dependency>
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-queryparser</artifactId>
    </dependency>
    <!--
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-analyzers-common</artifactId>
    </dependency>
    -->
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-analyzers</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-demo</artifactId>
      <version>${lucene.version}</version>
    </dependency>
  </dependencies>
</project>


text:
default: build

build:
	go build -o bin/fusis

run:
	sudo bin/fusis balancer --bootstrap

docker:
	docker build -t fusis .

deps:
	go get -u github.com/kardianos/govendor
	govendor add +external
	govendor sync

clean:
	sudo rm -rf /etc/fusis

test:
	sudo -E go test $$(go list ./... | grep -v /vendor)

ci:
	./covertests.sh


text:
class Object;

class Physics
{
    public:
        Physics();
        void addObject(Object* object);
        void Gravity(float deltaTime);
        void Collision();

    private:
        std::vector<Object*> objects;
        int x = 1;
};
#endif


text:
package at.arz.ngs.resources.exceptionMapper;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import at.arz.ngs.api.exception.ActionInProgress;
import at.arz.ngs.resources.NgsApiError;

@Provider
public class ActionInProgressMapper
		implements ExceptionMapper<ActionInProgress> {

	@Override
	public Response toResponse(ActionInProgress e) {
		NgsApiError error = new NgsApiError(e.getClass().getSimpleName(), e.getMessage());
		return Response	.status(Response.Status.CONFLICT)
						.type(MediaType.APPLICATION_JSON)
						.type(MediaType.APPLICATION_XML)
						.entity(error)
						.build();
	}

}


text:
'use strict';

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'basicController',
    controllerAs: 'ctrl'
  });
}])


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />

    <title>Understanding the Navigation Tree</title>
    <link rel="StyleSheet" href="css/Managing%20Composition.css" type="text/css" media="all" />
    <link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" />

      Managing Sample Composition Annotations  > Understanding the Navigation Tree

Understanding the Navigation Tree

Once you submit or search and select an existing sample with the Samples menu option (see Samples Overview), the Navigation Tree heading displays in the left-hand panel of caNanoLab with the selected [Sample name]. The Navigation Tree comprises categories which you can use to add annotations to the sample. Each category is a button. When you click a button, tabs appear in the right hand panel to show corresponding subcategories. With appropriate permissions, on the tabs you can add annotations or publications relevant to the sample. The tabs also display annotations or publications that were already added to the open sample.

The following list provides a general description of how you can use each Navigation Tree category.

•

Sample Information: This displays after you click the sample name itself. It shows general and basic information about the sample entered during the submission process.

•

Composition: Composition annotations define nanomaterial and functionalizing entities such as nanoparticle type and components such as antibodies that performs sample functions. For more information, see [Sample] Composition Overview.

•

Characterizations:  Characterization annotations define essential characteristics determined through analytical methods: physico-chemical features relating to molecular weight or size, for example, or under in vitro conditions such as blood contact or toxicity, or in vivo conditions such as pharmacokinetics. These characterizations add physical characteristics to identify the material and structural properties of a sample. For more information, see Managing Sample Characterizations.

•

Publication: Publication tabs display publications such as articles, books chapters, reviews and reports that have already been added or can be added to a sample. You can also add publications using the Publications menu option.  See Adding Publications to a Sample.

See also [Sample] Composition Overview


text:
FOUNDATION_EXPORT double Pods_LIHImageSlider_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_LIHImageSlider_ExampleVersionString[];


text:
<?xml version="1.0" encoding="UTF-8"?>
<root>
	<category name="Controller Setup">
		<option name="Controller Configuration" offset="B3A" type="byte">
			<value value="0">Mouse+Keys</value>
			<value value="1">Joypad</value>
		</option>

		<category name="Joypad Settings">
			<option name="Joypad Invert Left Stick X" offset="B44" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
		</category>

		<category name="Mouse Settings">
			<option name="Mouse Sensitivity" offset="B14" type="long">N/A</option>
			<option name="Invert Mouse Vertically" offset="B18" type="byte">
				<value value="0">On</value>
				<value value="1">Off</value>
			</option>
			<option name="Steer With Mouse" offset="B19" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
			<option name="Fly With Mouse" offset="B1A" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
		</category>
	</category>

	<category name="Audio Setup">
		<option name="Radio" offset="B1C" type="byte">
			<value value="0">Muted</value>
			<value value="64">Full Volume</value>
		</option>
		<option name="SFX" offset="B1B" type="byte">
			<value value="0">Muted</value>
			<value value="64">Full Volume</value>
		</option>
		<option name="Radio EQ" offset="B1F" type="byte">
			<value value="0">Off</value>
			<value value="1">On</value>
		</option>
		<option name="Radio Auto-Tune" offset="B1E" type="byte">
			<value value="0">Off</value>
			<value value="1">On</value>
		</option>

		<category name="User Track Options">
			<option name="Radio Play Mode" offset="B41" type="byte">
				<value value="0">Radio</value>
				<value value="1">Random</value>
				<value value="2">Sequential</value>
			</option>
			<option name="Automatic Media Scan" offset="B25" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
		</category>

		<option name="Radio Station" offset="B1D" type="byte">
			<value value="1">Playback FM</value>
			<value value="2">K Rose</value>
			<value value="3">K-DST</value>
			<value value="4">Bounce FM</value>
			<value value="5">SF-UR</value>
			<value value="6">Radio Los Santos</value>
			<value value="7">Radio X</value>
			<value value="8">CSR 103.9</value>
			<value value="9">K-JAH West</value>
			<value value="10">Master Sounds 98.3</value>
			<value value="11">WCTR Talk Radio</value>
			<value value="12">User Track Player</value>
			<value value="13">Radio Off</value>
		</option>
	</category>

	<category name="Display Setup">
		<option name="Brightness" offset="B20" type="word"></option>
		<option name="Legend" offset="B4A" type="byte">
			<value value="0">Off</value>
			<value value="1">On</value>
		</option>
		<option name="Radar Mode" offset="B3D" type="byte">
			<value value="0">Maps + Blips</value>
			<value value="1">Blips Only</value>
			<value value="2">Off</value>
		</option>
		<option name="HUD Mode" offset="B3C" type="byte">
			<value value="0">Off</value>
			<value value="1">On</value>
		</option>
		<option name="Subtitles" offset="B33" type="byte">
			<value value="0">Off</value>
			<value value="1">On</value>
		</option>
		<option name="Store Gallery Photos" offset="B42" type="byte">
			<value value="0">Off</value>
			<value value="1">On</value>
		</option>

		<category name="Advanced">
			<option name="Draw Distance" offset="B30" type="word"></option>
			<option name="Frame Limiter" offset="B35" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
			<option name="Wide Screen" offset="B34" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
			<option name="Visual FX Quality" offset="B2A" type="byte">
				<value value="0">Low</value>
				<value value="1">Medium</value>
				<value value="2">High</value>
				<value value="3">Very High</value>
			</option>
			<option name="Mip Mapping" offset="B24" type="byte">
				<value value="0">Off</value>
				<value value="1">On</value>
			</option>
			<option name="Anti Aliasing" offset="B26" type="byte">
				<value value="1">Off</value>
				<value value="2">1</value>
				<value value="3">2</value>
				<value value="4">3</value>
			</option>
			<option name="Resolution" offset="B36" type="byte">
				<value value="1">640 x 480, 16 Bit</value>
				<value value="2">Unknown (2)</value>
				<value value="3">720 x 576, 16 Bit</value>
				<value value="4">800 x 600, 16 Bit</value>
				<value value="5">Unknown (5)</value>
				<value value="6">Unknown (6)</value>
				<value value="7">1024 x 768, 16 Bit</value>
				<value value="8">640 x 480, 32 Bit</value>
				<value value="9">Unknown (9)</value>
				<value value="10">720 x 576, 32 Bit</value>
				<value value="11">800 x 600, 32 Bit</value>
				<value value="12">Unknown (C)</value>
				<value value="13">Unknown (D)</value>
				<value value="14">1024 x 768, 32 Bit</value>
				<value value="15">Unknown (F)</value>
				<value value="16">1280 x 800, 32 Bit</value>
				<value value="17">Unknown (11)</value>
				<value value="18">Unknown (12)</value>
				<value value="19">Unknown (13)</value>
				<value value="20">Unknown (14)</value>
				<value value="21">Unknown (15)</value>
				<value value="22">Unknown (16)</value>
				<value value="23">Unknown (17)</value>
				<value value="24">Unknown (18)</value>
				<value value="25">Unknown (19)</value>
				<value value="26">Unknown (1A)</value>
				<value value="27">1280 x 1024, 32 Bit</value>
			</option>
		</category>
	</category>

	<option name="Language" offset="B3B" type="byte">
		<value value="0">English</value>
		<value value="4">Spanish</value>
	</option>
</root>


text:
<?php
require_once( 'auth_tutorial7.php' );

use cascade_ws_AOHS      as aohs;
use cascade_ws_constants as c;
use cascade_ws_asset     as a;
use cascade_ws_property  as p;
use cascade_ws_utility   as u;
use cascade_ws_exception as e;

try
{
    $pcs = $cascade->getAsset(
        a\PageConfigurationSet::TYPE, "255a2bd18b7ffe3b00a7e343711b563e" );
    $pc  = $pcs->getPageConfiguration( "Desktop" );
    //u\DebugUtility::dump( $pc->toStdClass() );
    //$pc->display();
    //$pc->dump();
    echo u\StringUtility::boolToString( $pc->getDefaultConfiguration() ), BR;

    echo u\StringUtility::getCoalescedString( $pc->getFormatId() ), BR;
    echo u\StringUtility::getCoalescedString( $pc->getFormatPath() ), BR;
    echo u\StringUtility::boolToString( $pc->getFormatRecycled() ), BR;

    echo $pc->getId(), BR;
    echo $pc->getName(), BR;
    echo u\StringUtility::boolToString( $pc->getIncludeXMLDeclaration() ), BR;
    echo $pc->getOutputExtension(), BR;

    //u\DebugUtility::dump( $pc->getPageRegion( "DEFAULT" ) );
    //u\DebugUtility::dump( $pc->getPageRegionNames() );
    //u\DebugUtility::dump( $pc->getPageRegions() );
    //u\DebugUtility::dump( $pc->getPageRegionBlock( "DEFAULT" ) );
    //u\DebugUtility::dump( $pc->getPageRegionFormat( "DEFAULT" ) );

    //echo u\StringUtility::boolToString( $pc->getPublishable() ), BR;
    //echo $pc->getSerializationType(), BR;
    //$pc->getTemplate()->dump();
    echo $pc->getTemplateId(), BR;
    echo $pc->getTemplatePath(), BR;
    echo u\StringUtility::boolToString( $pc->hasPageRegion( "LOGO" ) ), BR;
    //u\DebugUtility::dump( $pc->setDefaultConfiguration( true )->toStdClass() );

    /*
    u\DebugUtility::dump( $pc->setFormat(
        $cascade->getAsset( a\XsltFormat::TYPE, "255a4cec8b7ffe3b00a7e3433e083063" )
    )->toStdClass() );
    */

    //u\DebugUtility::dump( $pc->setIncludeXMLDeclaration( true )->toStdClass() );
    //u\DebugUtility::dump( $pc->setOutputExtension( ".html" )->toStdClass() );
    //u\DebugUtility::dump( $pc->setPageRegionBlock( "SEARCH PRINT" )->toStdClass() );
    //u\DebugUtility::dump( $pc->setPageRegionFormat( "LAST MODIFIED" )->toStdClass() );
    //u\DebugUtility::dump( $pc->setPublishable( false )->toStdClass() );
    //u\DebugUtility::dump( $pc->setRegionNoBlock( "SEARCH PRINT", true )->toStdClass() );
    //u\DebugUtility::dump( $pc->setRegionNoFormat( "SEARCH PRINT", true )->toStdClass() );
    //u\DebugUtility::dump( $pc->setSerializationType( "XML" )->toStdClass() );

    u\DebugUtility::dump( $pc->setSerializationType( "XML" )->toStdClass() );
}
catch( \Exception $e )
{
    echo S_PRE . $e . E_PRE;
}
catch( \Error $er )
{
    echo S_PRE . $er . E_PRE;
}
?>


text:
// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd.
// Released under the MIT license, see LICENSE.

#pragma once

namespace nbind {

class Int64 {};

template <typename ArgType>
static ArgType int64FromWire(WireType arg, void(init)(const Nan::FunctionCallbackInfo<v8::Value> &args)) {
	Nan::HandleScope();

	auto target = Nan::To<v8::Object>(arg).ToLocalChecked();
	auto fromJS = target->Get(Nan::New<v8::String>("fromJS").ToLocalChecked());

	if(!fromJS->IsFunction()) throw(std::runtime_error("Type mismatch"));

	ArgType storage = 0;

	// TODO: cache this for a speedup (replace init param).
	auto storageTemplate = Nan::New<v8::ObjectTemplate>();
	storageTemplate->SetInternalFieldCount(1);
	Nan::SetCallAsFunctionHandler(storageTemplate, init);

	auto instance = Nan::NewInstance(storageTemplate).ToLocalChecked();
	Nan::SetInternalFieldPointer(instance, 0, &storage);

	// TODO: cache this for a speedup.
	cbFunction converter(v8::Local<v8::Function>::Cast(fromJS));
	converter.callMethod<void>(target, instance);

	return(storage);
}

// Fast code path for 32-bit types.

template <int size> struct Int64Converter {
	template <typename ArgType>
	static inline WireType uint64ToWire(ArgType arg) {
		return(Nan::New<v8::Uint32>(static_cast<uint32_t>(arg)));
	}

	template <typename ArgType>
	static inline WireType int64ToWire(ArgType arg) {
		return(Nan::New<v8::Int32>(static_cast<int32_t>(arg)));
	}

	template <typename ArgType>
	static void uint64Init(const Nan::FunctionCallbackInfo<v8::Value> &args) {
		ArgType &storage = *static_cast<ArgType *>(Nan::GetInternalFieldPointer(args.Holder(), 0));

		unsigned int argc = args.Length();
		if(argc > 0) storage = Nan::To<unsigned int>(args[0]).FromJust();

		args.GetReturnValue().Set(Nan::Undefined());
	}

	template <typename ArgType>
	static void int64Init(const Nan::FunctionCallbackInfo<v8::Value> &args) {
		ArgType &storage = *static_cast<ArgType *>(Nan::GetInternalFieldPointer(args.Holder(), 0));

		unsigned int argc = args.Length();
		if(argc > 0) storage = Nan::To<unsigned int>(args[0]).FromJust();
		if(argc > 2 && Nan::To<bool>(args[2]).FromJust()) storage = -storage;

		args.GetReturnValue().Set(Nan::Undefined());
	}
};

// Handle 64-bit types.

template<> struct Int64Converter<8> {
	template <typename ArgType>
	static inline WireType uint64ToWire(ArgType arg) {
		if(arg <= 0xffffffffU) {
			// Number fits in uint32_t.
			return(Nan::New<v8::Uint32>(static_cast<uint32_t>(arg)));
		} else if(arg <= 0x20000000000000ULL) {
			// Number fits in double.
			return(Nan::New<v8::Number>(static_cast<double>(arg)));
		}

		cbFunction *jsConstructor = BindClass<Int64>::getInstance().getValueConstructorJS();

		if(jsConstructor != nullptr) {
			// Construct custom bignum object from high and low 32-bit halves.
			v8::Local<v8::Value> output = Nan::Undefined();
			cbOutput construct(*jsConstructor, &output);

			construct(
				static_cast<uint32_t>(arg),
				static_cast<uint32_t>(arg >> 32),
				false
			);

			return(output);
		} else {
			// Int64 JavaScript class is missing or not registered.
			// Just cast to double then.
			return(Nan::New<v8::Number>(static_cast<double>(arg)));
		}
	}

	template <typename ArgType>
	static inline WireType int64ToWire(ArgType arg) {
		if(arg >= -0x80000000 && arg <= 0x7fffffff) {
			return(Nan::New<v8::Int32>(static_cast<int32_t>(arg)));
		} else if(arg >= -0x20000000000000LL && arg <= 0x20000000000000LL) {
			return(Nan::New<v8::Number>(static_cast<double>(arg)));
		}

		cbFunction *jsConstructor = BindClass<Int64>::getInstance().getValueConstructorJS();

		if(jsConstructor != nullptr) {
			v8::Local<v8::Value> output = Nan::Undefined();
			cbOutput construct(*jsConstructor, &output);

			bool sign = arg < 0;
			if(sign) arg = -arg;

			construct(
				static_cast<uint32_t>(arg),
				static_cast<uint32_t>(static_cast<uint64_t>(arg) >> 32),
				sign
			);

			return(output);
		} else {
			// Int64 JavaScript class is missing or not registered.
			return(Nan::New<v8::Number>(static_cast<double>(arg)));
		}
	}

	template <typename ArgType>
	static void uint64Init(const Nan::FunctionCallbackInfo<v8::Value> &args) {
		ArgType &storage = *static_cast<ArgType *>(Nan::GetInternalFieldPointer(args.Holder(), 0));

		unsigned int argc = args.Length();
		if(argc > 0) storage = Nan::To<unsigned int>(args[0]).FromJust();
		if(argc > 1) storage += static_cast<uint64_t>(Nan::To<unsigned int>(args[1]).FromJust()) << 32;

		args.GetReturnValue().Set(Nan::Undefined());
	}

	template <typename ArgType>
	static void int64Init(const Nan::FunctionCallbackInfo<v8::Value> &args) {
		ArgType &storage = *static_cast<ArgType *>(Nan::GetInternalFieldPointer(args.Holder(), 0));

		unsigned int argc = args.Length();
		if(argc > 0) storage = Nan::To<unsigned int>(args[0]).FromJust();
		if(argc > 1) storage += static_cast<uint64_t>(Nan::To<unsigned int>(args[1]).FromJust()) << 32;
		if(argc > 2 && Nan::To<bool>(args[2]).FromJust()) storage = -storage;

		args.GetReturnValue().Set(Nan::Undefined());
	}
};

#define DEFINE_INT64_BINDING_TYPE(ArgType, encode, decode)  \
template <> struct BindingType<ArgType> {                   \
	typedef ArgType Type;                                   \
	                                                        \
	static inline bool checkType(WireType arg) {            \
		return(true);                                       \
	}                                                       \
	                                                        \
	static inline WireType toWireType(Type arg) {           \
		return(Int64Converter<sizeof(Type)>::encode(arg));  \
	}                                                       \
	                                                        \
	static inline Type fromWireType(WireType arg) {         \
		if(arg->IsObject()) {                               \
			return(int64FromWire<ArgType>(arg, Int64Converter<sizeof(Type)>::decode<ArgType>)); \
		} else {                                            \
			return(static_cast<Type>(Nan::To<double>(arg).FromJust()));  \
		}                                                   \
	}                                                       \
};                                                          \
                                                            \
template <> struct BindingType<StrictType<ArgType>> : public BindingType<ArgType> { \
	static inline bool checkType(WireType arg) {            \
		/* TODO: check type of object (bound to Int64?) */  \
		return(arg->IsNumber() || arg->IsObject());         \
	}                                                       \
}

// Handle possibly 64-bit types.
// Types detected to fit in 32 bits automatically use a faster code path.

DEFINE_INT64_BINDING_TYPE(unsigned long, uint64ToWire, uint64Init);
DEFINE_INT64_BINDING_TYPE(unsigned long long, uint64ToWire, uint64Init);
DEFINE_INT64_BINDING_TYPE(signed long, int64ToWire, int64Init);
DEFINE_INT64_BINDING_TYPE(signed long long, int64ToWire, int64Init);

} // namespace


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.math;

import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.xpack.ql.expression.Literal;
import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor;
import org.elasticsearch.xpack.ql.expression.gen.processor.Processor;
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
import org.elasticsearch.xpack.sql.SqlTestUtils;
import org.elasticsearch.xpack.sql.expression.function.scalar.Processors;

import static org.elasticsearch.xpack.ql.tree.Source.EMPTY;

public class BinaryMathProcessorTests extends AbstractWireSerializingTestCase<BinaryMathProcessor> {
    public static BinaryMathProcessor randomProcessor() {
        return new BinaryMathProcessor(
                new ConstantProcessor(randomLong()),
                new ConstantProcessor(randomLong()),
                randomFrom(BinaryMathProcessor.BinaryMathOperation.values()));
    }

    @Override
    protected BinaryMathProcessor createTestInstance() {
        return randomProcessor();
    }

    @Override
    protected Reader<BinaryMathProcessor> instanceReader() {
        return BinaryMathProcessor::new;
    }

    @Override
    protected NamedWriteableRegistry getNamedWriteableRegistry() {
        return new NamedWriteableRegistry(Processors.getNamedWriteables());
    }

    public void testAtan2() {
        Processor ba = new ATan2(EMPTY, l(1), l(1)).makePipe().asProcessor();
        assertEquals(0.7853981633974483d, ba.process(null));
    }

    public void testPower() {
        Processor ba = new Power(EMPTY, l(2), l(2)).makePipe().asProcessor();
        assertEquals(4d, ba.process(null));
    }

    public void testRoundWithValidInput() {
        assertEquals(123.0, new Round(EMPTY, l(123), l(3)).makePipe().asProcessor().process(null));
        assertEquals(123.5, new Round(EMPTY, l(123.45), l(1)).makePipe().asProcessor().process(null));
        assertEquals(123.0, new Round(EMPTY, l(123.45), l(0)).makePipe().asProcessor().process(null));
        assertEquals(123.0, new Round(EMPTY, l(123.45), null).makePipe().asProcessor().process(null));
        assertEquals(-100.0, new Round(EMPTY, l(-123), l(-2)).makePipe().asProcessor().process(null));
        assertEquals(-120.0, new Round(EMPTY, l(-123.45), l(-1)).makePipe().asProcessor().process(null));
        assertEquals(-124.0, new Round(EMPTY, l(-123.5), l(0)).makePipe().asProcessor().process(null));
        assertEquals(-123.0, new Round(EMPTY, l(-123.45), null).makePipe().asProcessor().process(null));
    }

    public void testRoundFunctionWithEdgeCasesInputs() {
        assertNull(new Round(EMPTY, l(null), l(3)).makePipe().asProcessor().process(null));
        assertEquals(-0.0, new Round(EMPTY, l(0), l(0)).makePipe().asProcessor().process(null));
        assertEquals((double) Long.MAX_VALUE, new Round(EMPTY, l(Long.MAX_VALUE), l(0))
                .makePipe().asProcessor().process(null));
        assertEquals(0.0, new Round(EMPTY, l(123.456), l(Integer.MAX_VALUE)).makePipe().asProcessor().process(null));
    }

    public void testRoundInputValidation() {
        SqlIllegalArgumentException siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Round(EMPTY, l(5), l("foobarbar")).makePipe().asProcessor().process(null));
        assertEquals("A number is required; received [foobarbar]", siae.getMessage());
        siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Round(EMPTY, l("bla"), l(0)).makePipe().asProcessor().process(null));
        assertEquals("A number is required; received [bla]", siae.getMessage());
        siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Round(EMPTY, l(123.34), l(0.1)).makePipe().asProcessor().process(null));
        assertEquals("An integer number is required; received [0.1] as second parameter", siae.getMessage());
    }

    public void testTruncateWithValidInput() {
        assertEquals(123.0, new Truncate(EMPTY, l(123), l(3)).makePipe().asProcessor().process(null));
        assertEquals(123.4, new Truncate(EMPTY, l(123.45), l(1)).makePipe().asProcessor().process(null));
        assertEquals(123.0, new Truncate(EMPTY, l(123.45), l(0)).makePipe().asProcessor().process(null));
        assertEquals(123.0, new Truncate(EMPTY, l(123.45), null).makePipe().asProcessor().process(null));
        assertEquals(-100.0, new Truncate(EMPTY, l(-123), l(-2)).makePipe().asProcessor().process(null));
        assertEquals(-120.0, new Truncate(EMPTY, l(-123.45), l(-1)).makePipe().asProcessor().process(null));
        assertEquals(-123.0, new Truncate(EMPTY, l(-123.5), l(0)).makePipe().asProcessor().process(null));
        assertEquals(-123.0, new Truncate(EMPTY, l(-123.45), null).makePipe().asProcessor().process(null));
    }

    public void testTruncateFunctionWithEdgeCasesInputs() {
        assertNull(new Truncate(EMPTY, l(null), l(3)).makePipe().asProcessor().process(null));
        assertEquals(0.0, new Truncate(EMPTY, l(0), l(0)).makePipe().asProcessor().process(null));
        assertEquals((double) Long.MAX_VALUE, new Truncate(EMPTY, l(Long.MAX_VALUE), l(0))
                .makePipe().asProcessor().process(null));
        assertEquals(Double.NaN, new Truncate(EMPTY, l(123.456), l(Integer.MAX_VALUE))
                .makePipe().asProcessor().process(null));
    }

    public void testTruncateInputValidation() {
        SqlIllegalArgumentException siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Truncate(EMPTY, l(5), l("foobarbar")).makePipe().asProcessor().process(null));
        assertEquals("A number is required; received [foobarbar]", siae.getMessage());
        siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Truncate(EMPTY, l("bla"), l(0)).makePipe().asProcessor().process(null));
        assertEquals("A number is required; received [bla]", siae.getMessage());
        siae = expectThrows(SqlIllegalArgumentException.class,
                () -> new Truncate(EMPTY, l(123.34), l(0.1)).makePipe().asProcessor().process(null));
        assertEquals("An integer number is required; received [0.1] as second parameter", siae.getMessage());
    }

    public void testHandleNull() {
        assertNull(new ATan2(EMPTY, l(null), l(3)).makePipe().asProcessor().process(null));
        assertNull(new Power(EMPTY, l(null), l(null)).makePipe().asProcessor().process(null));
    }

    private static Literal l(Object value) {
        return SqlTestUtils.literal(value);
    }
}


text:
const expect = require('chai').expect;
require('chai').should();

const capitalize = require('./');

describe('capitalize', () => {

    it('function exist', () => expect(capitalize).to.exist);

    it('should capitalise first char only', () => expect(capitalize('hello world')).to.equal('Hello world'));

    it('should capitalise first char of each word', () => expect(capitalize('hello world', true)).to.equal('Hello World'));

    it('should capitalise foreign language', () => expect(capitalize('á-char ü-char', true)).to.equal('Á-char Ü-char'));

    it('should return numbers as is', () => expect(capitalize('1234')).to.equal('1234'));

});


text:
package flow.twist.trackable;

import soot.Unit;

public interface PopFromStack {

	public Unit getCallSite();
}


text:
layout: post
date:	2010-01-02 11:28:00
title:  I wasnt even looking for the butterflies....
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
I realize that Namdapha must be a sort of butterly heaven during the season...because I went out of season, I wasn't even looking for any, and yet I just could not resist clicking some of the common ones!

Let's just start with the beautiful HIMALAYAN JESTER:

<lj-cut text="Here's a long Hanuman's tail of pics that will be of interest only to butterfly lovers (and I assure you there are NO rare finds in it!)">

the COMMON RING:

the COMMON TIT:

the FLUFFY TIT:

an "open" PUFFIN:

the same butterfly, with its wings closed:

I learnt why the COMMON CASTOR was called so, after seeing them in their hundreds amongst the castor plants (from which castor oil is made)!

the INDIAN RED ADMIRAL:

the METALLIC CERULEAN (this one really did have a lovely blue metallic sheen as it flew about, so naturally I could not get a single shot of it with its wings open. Show me a photographer trying to catch a flitting butterfly with a camera, and I will show you a frustrated person.)

the LIME EMIGRANT:

the PURPLE SAPPHIRE (what a lovely and tough name!)

this is another of the Sapphires:

this was one of the "easy" (that is, seen earlier, often enough to be remembered!) ones...the WHITE ORANGE-TIP:

I cannot understand why so many butterflies, such light and delicate creatures that live on sunshine and flowers and in utter peace, should be named after ranks in the armed forces. HOW can associate these creatures of light and air with war? But so it it is.

Here is the SERGEANT:

thank goodness, this one is named after PUNCHINELLO, one of the characters of the Harlequin opera:

sometimes we get back to the flowers, as with this GREY PANSY:

and sometimes the description is so true...this is the COMMON WANDERER:

but whoever called this one a PEACOCK PANSY has never seen a peacock, even though the "eyes" may have brought the bird to mind:

it was amazing how, as I walked, the butterflies folded themselves and just became leaves! Here's that self-same Peacock Pansy, with its wings closed...isn't it a dry, sere leaf?

some more flights of fancy inspired some butterflies being called Tigers, as with this CHESTNUT TIGER:

I could not find the id of this one:

here's the COMMON HEDGE BLUE:

back to the bird names...and where there is any chocolate in the CHOCOLATE ALBATROSS, I don't know!

this one's a COMMANDER...

My guide, Bidyut, said this one might be an ORANGE-AND-BLACK ROYAL but Karthik says it's more likely to be a RED FLASH:

Here it is with the orange colour not showing:

Here's Bidyut picking up the wing of an unfortunate butterfly, which has probably become some bird's lunch:

This is the GRASS JEWEL, which Bidyut told me was the smallest butterfly in the world!

Some of the MOTHS were lovely too; here's some variety of SCOPULA MOTH (thanks for the id, Kiran!) :

and a HAWK MOTH:

here's a moth case, after the pupa has matured and flown out:

We were looking at a dead Moth on the path, when Bidyut, our guide, cracked a great bilingual pun. "Look," he cried, " 'mauth' (death in Hindi) has truly come to this Moth!"

and a few un-id DRAGONFLIES:

</lj-cut>

I end with the WHITE STRIPED BARON:

I am not sure of many of the id's and would appreciate any help or corrections, please!

I have also decided that instead of hunting high and low for id's, I am just going to call these butterflies "Krishnamurthy", "Subramaniam", "Vahini" and so on!

I can only imagine what it must be like during the butterfly season in this remote corner of India!


text:
using System.Collections.Generic;
using WK.Orion.Platform.UserManagement.Core.Models.Projections.Interfaces;

namespace WK.Orion.Platform.UserManagement.Interfaces
{
    /// <summary>   Interface for iudf service. </summary>
    public interface IUserService
    {
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Gets an one. </summary>
        ///
        /// <param name="id">   The identifier. </param>
        ///
        /// <returns>   The one. </returns>
        ///-------------------------------------------------------------------------------------------------
        IOrionUserDto GetOne(long id);

        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Gets all items in this collection. </summary>
        ///
        /// <returns>
        ///     An enumerator that allows foreach to be used to process all items in this collection.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------
        IEnumerable<IOrionUserDto> GetAll();

        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Gets an i orion udf dto using the given item identifier. </summary>
        ///
        /// <param name="itemId">   The item identifier to get. </param>
        ///
        /// <returns>   An IOrionUserDto. </returns>
        ///-------------------------------------------------------------------------------------------------
        IOrionUserDto Get(long itemId);

        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Saves the given orion udf dto. </summary>
        ///
        /// <param name="orionUserDto">  The orion udf dto to save. </param>
        ///-------------------------------------------------------------------------------------------------
        void Save(IOrionUserDto orionUserDto);
    }
}


text:
FOUNDATION_EXPORT double Pods_FBPLUGIN_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_FBPLUGIN_ExampleVersionString[];