text:
using System.Threading.Tasks;
using Telegram.Bot.Tests.Integ.Framework;
using Telegram.Bot.Types;
using Xunit;

namespace Telegram.Bot.Tests.Integ.Other
{
    [Collection(Constants.TestCollections.BotCommands)]
    [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)]
    public class BotCommandsTests: IAsyncLifetime
    {
        readonly TestsFixture _fixture;
        BotCommandScope _scope;

        ITelegramBotClient BotClient => _fixture.BotClient;

        public BotCommandsTests(TestsFixture fixture)
        {
            _fixture = fixture;
        }

        [OrderedFact("Should set a new bot command list")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetMyCommands)]
        public async Task Should_Set_New_Bot_Command_List()
        {
            BotCommand[] commands =
            {
                new()
                {
                    Command = "start",
                    Description = "Start command"
                },
                new()
                {
                    Command = "help",
                    Description = "Help command"
                },
            };

            _scope = BotCommandScope.Default();

            await BotClient.SetMyCommandsAsync(
                commands: commands,
                scope: _scope
            );
        }

        [OrderedFact("Should get previously set bot command list")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetMyCommands)]
        public async Task Should_Get_Set_Bot_Commands()
        {
            BotCommand[] commands =
            {
                new()
                {
                    Command = "start",
                    Description = "Start command"
                },
                new()
                {
                    Command = "help",
                    Description = "Help command"
                },
            };

            _scope = BotCommandScope.Default();

            await _fixture.BotClient.SetMyCommandsAsync(
                commands: commands,
                scope: _scope
            );

            BotCommand[] currentCommands = await _fixture.BotClient.GetMyCommandsAsync();

            Assert.Equal(2, currentCommands.Length);
            Asserts.JsonEquals(commands, currentCommands);
        }

        [OrderedFact("Should delete bot command list")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetMyCommands)]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.DeleteMessage)]
        public async Task Should_Delete_Bot_Commands()
        {
            BotCommand[] commands =
            {
                new()
                {
                    Command = "start",
                    Description = "Start command"
                },
                new()
                {
                    Command = "help",
                    Description = "Help command"
                },
            };

            _scope = BotCommandScope.Default();

            await BotClient.SetMyCommandsAsync(
                commands: commands,
                scope: _scope
            );

            BotCommand[] setCommands = await BotClient.GetMyCommandsAsync();

            Assert.NotNull(setCommands);
            Asserts.JsonEquals(commands, setCommands);

            await BotClient.DeleteMyCommandsAsync(scope: _scope);

            BotCommand[] currentCommands = await BotClient.GetMyCommandsAsync(scope: _scope);

            Assert.NotNull(currentCommands);
            Assert.Empty(currentCommands);
        }

        [OrderedFact("Should set group scoped commands")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetMyCommands)]
        public async Task Should_Set_Group_Scoped_Commands()
        {
            BotCommand[] commands =
            {
                new()
                {
                    Command = "start",
                    Description = "Start command"
                },
                new()
                {
                    Command = "help",
                    Description = "Help command"
                },
            };

            _scope = BotCommandScope.AllGroupChats();

            await BotClient.SetMyCommandsAsync(
                commands: commands,
                scope: _scope
            );

            BotCommand[] newCommands = await BotClient.GetMyCommandsAsync(scope: _scope);

            Asserts.JsonEquals(commands, newCommands);
        }

        public Task InitializeAsync() => Task.CompletedTask;
        public async Task DisposeAsync() => await _fixture.BotClient.DeleteMyCommandsAsync(scope: _scope);
    }
}


text:
<?php

namespace Maghead\TableParser;

use Exception;
use Magsql\Driver\MySQLDriver;
use Magsql\Driver\BaseDriver;
use Magsql\Driver\PgSQLDriver;

class TypeInfoParser
{
    public static function parseTypeInfo($typeName, BaseDriver $driver = null)
    {
        $type = strtolower($typeName);

        $typeInfo = new TypeInfo();

        // Type name with precision
        if (preg_match('/^(
             double
            |float
            |decimal
            |numeric
            |int
            |integer
            |tinyint
            |smallint
            |mediumint
            |bigint
            |char
            |varchar
            |character\ varying
            |character
            |binary
            |varbinary
            ) (?: \(  (?:(\d+),(\d+)|(\d+))   \) )?\s*(unsigned)?/ix', $typeName, $matches)) {
            if (isset($matches[1]) && $matches[1] && isset($matches[2]) && isset($matches[3]) && $matches[2] && $matches[3]) {
                $typeInfo->type = strtolower($matches[1]);
                $typeInfo->length = intval($matches[2]);
                $typeInfo->precision = intval($matches[3]);
            } elseif (isset($matches[1]) && $matches[1] && isset($matches[4]) && $matches[4]) {
                $typeInfo->type = strtolower($matches[1]); // override the original type
                $typeInfo->length = intval($matches[4]);
            } elseif (isset($matches[1]) && $matches[1]) {
                $typeInfo->type = strtolower($matches[1]);
            }

            if (isset($matches[5]) && $matches[5]) {
                $typeInfo->unsigned = true;
            } else {
                $typeInfo->unsigned = false;
            }
        } elseif ($driver instanceof MySQLDriver && preg_match('/(enum|set)\((.*)\)/', $typeName, $matches)) {
            $typeInfo->type = strtolower($matches[1]);
            $values = array();
            $strvalues = explode(',', $matches[2]);
            foreach ($strvalues as $strvalue) {
                // looks like a string
                if (preg_match('/^([\'"])(.*)\\1$/', $strvalue, $matches)) {
                    $values[] = $matches[2];
                } elseif (is_numeric($strvalue)) {
                    $values[] = intval($strvalue);
                }
            }
            switch ($typeInfo->type) {
            case 'enum':
                $typeInfo->enum = $values;
                break;
            case 'set':
                $typeInfo->set = $values;
                break;
            }
        } else {
            // for type like: 'text' or 'blob'.. type name without length or decimals
            $typeInfo->type = strtolower($typeName);
        }

        // Canonicalization for PgSQL
        if ($driver instanceof PgSQLDriver) {
            if ($typeInfo->type === 'character varying') {
                $typeInfo->type = 'varchar';
            }
        } elseif ($driver instanceof MySQLDriver) {
            switch ($typeInfo->type) {
            case 'tinyint':
                if ($typeInfo->length == 1) {
                    $typeInfo->type = 'boolean';
                    $typeInfo->isa = 'bool';
                    $typeInfo->length = null;
                } elseif (
                    ($typeInfo->unsigned && $typeInfo->length == 3)
                    || (!$typeInfo->unsigned && $typeInfo->length == 4)
                ) {
                    $typeInfo->length = null;
                }
                break;
            case 'integer':
            case 'int':
                $typeInfo->type = 'int';
                if (($typeInfo->unsigned && $typeInfo->length == 10)
                    || (!$typeInfo->unsigned && $typeInfo->length == 11)) {
                    $typeInfo->length = null;
                }
                break;
            case 'smallint':
                if (($typeInfo->unsigned && $typeInfo->length == 5)
                    || (!$typeInfo->unsigned && $typeInfo->length == 6)) {
                    $typeInfo->length = null;
                }
                break;
            case 'mediumint':
                if (($typeInfo->unsigned && $typeInfo->length == 8)
                    || (!$typeInfo->unsigned && $typeInfo->length == 9)) {
                    $typeInfo->length = null;
                }
                break;
            case 'bigint':
                if (($typeInfo->unsigned && $typeInfo->length == 20)
                    || (!$typeInfo->unsigned && $typeInfo->length == 21)) {
                    $typeInfo->length = null;
                }
                break;
            }
        }

        // Update isa property
        if (!$typeInfo->isa) {
            if (in_array($typeInfo->type, ['char', 'varchar', 'text'])) {
                $typeInfo->isa = 'str';
            } elseif (preg_match('/int/', $typeInfo->type)) {
                $typeInfo->isa = 'int';
            } elseif (in_array($typeInfo->type, ['boolean', 'bool'])) {
                $typeInfo->isa = 'bool';
            } elseif (in_array($typeInfo->type, ['blob', 'binary'])) {
                $typeInfo->isa = 'str';
            } elseif ($typeInfo->type == 'double') {
                $typeInfo->isa = 'double';
            } elseif (in_array($typeInfo->type, ['float', 'decimal', 'numeric'])) {
                $typeInfo->isa = 'float';
            } elseif ($typeInfo->type == 'enum') {
                $typeInfo->isa = 'enum';
            } elseif ($typeInfo->type == 'set') {
                $typeInfo->isa = 'set';
            } elseif ($typeInfo->type == 'point') {
                $typeInfo->isa = 'point';
            } elseif ('datetime' === $typeInfo->type || 'date' === $typeInfo->type) {
                $typeInfo->isa = 'DateTime';
            } elseif (preg_match('/timestamp/', $typeInfo->type)) {
                // For postgresql, the 'timestamp' can be 'timestamp with timezone'
                $typeInfo->isa = 'DateTime';
            } elseif ('time' == $typeInfo->type) {
                // DateTime::createFromFormat('H:s','10:00')
                $typeInfo->isa = 'DateTime';
            } else {
                throw new Exception("Unknown type $type");
            }
        }

        return $typeInfo;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Customer\Test\Unit\Block\Adminhtml\Edit;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;

/**
 * Class UnlockButtonTest
 * @package Magento\Customer\Block\Adminhtml\Edit
 */
class UnlockButtonTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Customer\Model\CustomerRegistry
     */
    protected $customerRegistryMock;

    /**
     * @var  \Magento\Backend\Block\Widget\Context
     */
    protected $contextMock;

    /**
     * @var \Magento\Customer\Model\Customer
     */
    protected $customerModelMock;

    /**
     * Url Builder
     *
     * @var \Magento\Framework\UrlInterface
     */
    protected $urlBuilderMock;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $registryMock;

    /**
     * @var \Magento\Customer\Block\Adminhtml\Edit\UnlockButton
     */
    protected $block;

    protected function setUp()
    {
        $this->contextMock = $this->getMock(
            'Magento\Backend\Block\Widget\Context',
            [],
            [],
            '',
            false
        );
        $this->customerRegistryMock = $this->getMock(
            'Magento\Customer\Model\CustomerRegistry',
            ['retrieve'],
            [],
            '',
            false
        );
        $this->customerModelMock = $this->getMock(
            'Magento\Customer\Model\Customer',
            [],
            [],
            '',
            false
        );
        $this->registryMock = $this->getMock(
            'Magento\Framework\Registry',
            ['registry'],
            [],
            '',
            false
        );

        $this->urlBuilderMock = $this->getMockBuilder('Magento\Framework\UrlInterface')
            ->setMethods(['getUrl'])
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $this->contextMock->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlBuilderMock);
        $objectManagerHelper = new ObjectManagerHelper($this);

        $this->block = $objectManagerHelper->getObject(
            'Magento\Customer\Block\Adminhtml\Edit\UnlockButton',
            [
                'context' => $this->contextMock,
                'customerRegistry' => $this->customerRegistryMock,
                'urlBuilder' => $this->urlBuilderMock,
                'registry' => $this->registryMock
            ]
        );
    }

    /**
     * @param array $result
     * @param bool $expectedValue
     * @dataProvider getButtonDataProvider
     */
    public function testGetButtonData($result, $expectedValue)
    {
        $this->registryMock->expects($this->any())->method('registry')->willReturn(1);
        $this->customerRegistryMock->expects($this->once())->method('retrieve')->willReturn($this->customerModelMock);
        $this->customerModelMock->expects($this->once())->method('isCustomerLocked')->willReturn($expectedValue);
        $this->urlBuilderMock->expects($this->any())->method('getUrl')->willReturn('http://website.com/');

        $this->assertEquals($result, $this->block->getButtonData());
    }

    /**
     * @return array
     */
    public function getButtonDataProvider()
    {
        return [
            [
                'result' =>
                    [
                        'label' => new \Magento\Framework\Phrase('Unlock'),
                        'class' => 'unlock unlock-customer',
                        'on_click' => "location.href = 'http://website.com/';",
                        'sort_order' => 50,
                    ],
                'expectedValue' => 'true'
            ],
            ['result' => [], 'expectedValue' => false]
        ];
    }
}


text:
namespace Bond
{

void Token::SetStringValue(const StringView &str)
{
	mValue.mString.buffer = str.data();
	mValue.mString.length = str.length();
}

const char *Token::GetTokenName() const
{
	return GetTokenName(mTokenType);
}

const char *Token::GetTokenName(TokenType type)
{
	static const char *const TOKEN_NAMES[] =
	{
#define BOND_TOKEN_ITEM(item) #item,
		BOND_TOKEN_LIST
#undef BOND_TOKEN_ITEM
	};

	return TOKEN_NAMES[type];
}

TokenTypeSet::TokenTypeSet(
		const char *const typeName,
		Token::TokenType t0,
		Token::TokenType t1,
		Token::TokenType t2,
		Token::TokenType t3,
		Token::TokenType t4,
		Token::TokenType t5,
		Token::TokenType t6,
		Token::TokenType t7,
		Token::TokenType t8,
		Token::TokenType t9,
		Token::TokenType t10,
		Token::TokenType t11,
		Token::TokenType t12,
		Token::TokenType t13,
		Token::TokenType t14,
		Token::TokenType t15):
	mTypeName(typeName)
{
	for (auto &element: mBitField)
	{
		element = 0;
	}

	Add(t0);
	Add(t1);
	Add(t2);
	Add(t3);
	Add(t4);
	Add(t5);
	Add(t6);
	Add(t7);
	Add(t8);
	Add(t9);
	Add(t10);
	Add(t11);
	Add(t12);
	Add(t13);
	Add(t14);
	Add(t15);
}

const Token VOID_TOKEN("void", Token::KEY_VOID);
const Token BOOL_TOKEN("bool", Token::KEY_BOOL);
const Token CHAR_TOKEN("char", Token::KEY_CHAR);
const Token UCHAR_TOKEN("uchar", Token::KEY_UCHAR);
const Token INT_TOKEN("int", Token::KEY_INT);
const Token UINT_TOKEN("uint", Token::KEY_UINT);
const Token LONG_TOKEN("long", Token::KEY_LONG);
const Token ULONG_TOKEN("ulong", Token::KEY_ULONG);
const Token FLOAT_TOKEN("float", Token::KEY_FLOAT);
const Token DOUBLE_TOKEN("double", Token::KEY_DOUBLE);

const TokenTypeSet PRIMITIVE_TYPE_SPECIFIERS_TYPESET(
	"PRIMITIVE_TYPE_SPECIFIER",
	Token::KEY_BOOL,
	Token::KEY_CHAR,
	Token::KEY_UCHAR,
	Token::KEY_SHORT,
	Token::KEY_USHORT,
	Token::KEY_INT,
	Token::KEY_UINT,
	Token::KEY_LONG,
	Token::KEY_ULONG,
	Token::KEY_FLOAT,
	Token::KEY_DOUBLE,
	Token::KEY_VOID
);

const TokenTypeSet BOOLEAN_TYPE_SPECIFIERS_TYPESET(
	"BOOLEAN_TYPE_SPECIFIER",
	Token::KEY_BOOL
);

const TokenTypeSet CHAR_TYPE_SPECIFIERS_TYPESET(
	"CHAR_TYPE_SPECIFIER",
	Token::KEY_CHAR,
	Token::KEY_UCHAR
);

const TokenTypeSet INTEGER_TYPE_SPECIFIERS_TYPESET(
	"INTEGER_TYPE_SPECIFIER",
	Token::KEY_CHAR,
	Token::KEY_UCHAR,
	Token::KEY_SHORT,
	Token::KEY_USHORT,
	Token::KEY_INT,
	Token::KEY_UINT,
	Token::KEY_LONG,
	Token::KEY_ULONG
);

const TokenTypeSet SIGNED_INTEGER_TYPE_SPECIFIERS_TYPESET(
	"SIGNED_INTEGER_TYPE_SPECIFIER",
	Token::KEY_CHAR,
	Token::KEY_SHORT,
	Token::KEY_INT,
	Token::KEY_LONG
);

const TokenTypeSet UNSIGNED_INTEGER_TYPE_SPECIFIERS_TYPESET(
	"UNSIGNED_INTEGER_TYPE_SPECIFIER",
	Token::KEY_UCHAR,
	Token::KEY_USHORT,
	Token::KEY_UINT,
	Token::KEY_ULONG
);

const TokenTypeSet LEAST32_INTEGER_TYPE_SPECIFIERS_TYPESET(
	"LEAST32_TYPE_SPECIFIER",
	Token::KEY_INT,
	Token::KEY_UINT,
	Token::KEY_LONG,
	Token::KEY_ULONG
);

const TokenTypeSet MOST32_INTEGER_TYPE_SPECIFIERS_TYPESET(
	"MOST32_TYPE_SPECIFIER",
	Token::KEY_CHAR,
	Token::KEY_UCHAR,
	Token::KEY_SHORT,
	Token::KEY_USHORT,
	Token::KEY_INT,
	Token::KEY_UINT
);

const TokenTypeSet LONG_INTEGER_TYPE_SPECIFIERS_TYPESET(
	"LONG_TYPE_SPECIFIER",
	Token::KEY_LONG,
	Token::KEY_ULONG
);

const TokenTypeSet NUMERIC_TYPE_SPECIFIERS_TYPESET(
	"NUMERIC_TYPE_SPECIFIER",
	Token::KEY_CHAR,
	Token::KEY_UCHAR,
	Token::KEY_SHORT,
	Token::KEY_USHORT,
	Token::KEY_INT,
	Token::KEY_UINT,
	Token::KEY_LONG,
	Token::KEY_ULONG,
	Token::KEY_FLOAT,
	Token::KEY_DOUBLE
);

const TokenTypeSet VOID_TYPE_SPECIFIERS_TYPESET(
	"VOID_TYPE_SPECIFIER",
	Token::KEY_VOID
);

const TokenTypeSet TYPE_DESCRIPTORS_TYPESET(
	"TYPE_DESCRIPTOR",
	Token::OP_STAR,
	Token::OBRACKET
);

const TokenTypeSet MOST32_INTEGER_CONSTANTS_TYPESET(
	"MOST32_INTEGER_CONSTANT",
	Token::CONST_CHAR,
	Token::CONST_INT,
	Token::CONST_UINT
);

const TokenTypeSet SIGNED_INTEGER_CONSTANTS_TYPESET(
	"SIGNED_INTEGER_CONSTANT",
	Token::CONST_CHAR,
	Token::CONST_INT,
	Token::CONST_LONG
);

const TokenTypeSet JUMP_KEYWORDS_TYPESET(
	"JUMP_KEYWORDS",
	Token::KEY_BREAK,
	Token::KEY_CONTINUE,
	Token::KEY_RETURN
);

const TokenTypeSet SWITCH_LABELS_TYPESET(
	"SWITCH_LABEL",
	Token::KEY_CASE,
	Token::KEY_DEFAULT
);

const TokenTypeSet ASSIGNMENT_OPERATORS_TYPESET(
	"ASSIGNMENT_OPERATOR",
	Token::ASSIGN,
	Token::ASSIGN_LEFT,
	Token::ASSIGN_RIGHT,
	Token::ASSIGN_PLUS,
	Token::ASSIGN_MINUS,
	Token::ASSIGN_MULT,
	Token::ASSIGN_DIV,
	Token::ASSIGN_MOD,
	Token::ASSIGN_AND,
	Token::ASSIGN_OR,
	Token::ASSIGN_XOR
);

const TokenTypeSet EQUALITY_OPERATORS_TYPESET(
	"EQUALITY_OPERATOR",
	Token::OP_EQUAL,
	Token::OP_NOT_EQUAL
);

const TokenTypeSet RELATIONAL_OPERATORS_TYPESET(
	"RELATIONAL_OPERATOR",
	Token::OP_LT,
	Token::OP_LTE,
	Token::OP_GT,
	Token::OP_GTE
);

const TokenTypeSet SHIFT_OPERATORS_TYPESET(
	"SHIFT_OPERATOR",
	Token::OP_LEFT,
	Token::OP_RIGHT
);

const TokenTypeSet ADDITIVE_OPERATORS_TYPESET(
	"ADDITIVE_OPERATOR",
	Token::OP_PLUS,
	Token::OP_MINUS
);

const TokenTypeSet MULTIPLICATIVE_OPERATORS_TYPESET(
	"MULTIPLICATIVE_OPERATOR",
	Token::OP_STAR,
	Token::OP_DIV,
	Token::OP_MOD
);

const TokenTypeSet UNARY_OPERATORS_TYPESET(
	"UNARY_OPERATOR",
	Token::OP_PLUS,
	Token::OP_MINUS,
	Token::OP_STAR,
	Token::OP_INC,
	Token::OP_DEC,
	Token::OP_NOT,
	Token::OP_AMP,
	Token::OP_BIT_NOT
);

const TokenTypeSet POSTFIX_OPERATORS_TYPESET(
	"POSTFIX_OPERATOR",
	Token::OP_INC,
	Token::OP_DEC,
	Token::OP_ARROW,
	Token::OPAREN,
	Token::OBRACKET,
	Token::PERIOD
);

const TokenTypeSet PROPERTYOF_OPERATORS_TYPESET(
	"PROPERTYOF_OPERATOR",
	Token::KEY_ALIGNOF,
	Token::KEY_SIZEOF
);

const TokenTypeSet CONSTANT_LITERALS_TYPESET(
	"CONSTANT_LITERAL",
	Token::CONST_BOOL,
	Token::CONST_CHAR,
	Token::CONST_INT,
	Token::CONST_UINT,
	Token::CONST_LONG,
	Token::CONST_ULONG,
	Token::CONST_FLOAT,
	Token::CONST_DOUBLE,
	Token::CONST_STRING,
	Token::CONST_NULL
);

const TokenTypeSet BLOCK_DELIMITERS_TYPESET(
	"BLOCK_DELIMITER",
	Token::CBRACE,
	Token::END
);

const TokenTypeSet DECLARATION_DELIMITERS_TYPESET(
	"DECLARATION_DELIMITER",
	Token::KEY_ENUM,
	Token::KEY_NAMESPACE,
	Token::KEY_NATIVE,
	Token::KEY_STRUCT,
	Token::CBRACE,
	Token::SEMICOLON,
	Token::END
);

const TokenTypeSet INCLUDE_AND_DECLARATION_DELIMITERS_TYPESET(
	"INCLUDE_AND_DECLARATION_DELIMITER",
	Token::KEY_ENUM,
	Token::KEY_INCLUDE,
	Token::KEY_NAMESPACE,
	Token::KEY_NATIVE,
	Token::KEY_STRUCT,
	Token::CBRACE,
	Token::SEMICOLON,
	Token::END
);

const TokenTypeSet ENUM_DELIMITERS_TYPESET(
	"ENUM_DELIMITER",
	Token::CBRACE,
	Token::SEMICOLON,
	Token::END
);

const TokenTypeSet ENUMERATOR_DELIMITERS_TYPESET(
	"ENUMERATOR_DELIMITER",
	Token::CBRACE,
	Token::SEMICOLON,
	Token::COMMA
);

const TokenTypeSet STRUCT_MEMBER_DELIMITERS_TYPESET(
	"STRUCT_MEMBER_DELIMITER",
	Token::CBRACE,
	Token::SEMICOLON
);

const TokenTypeSet INITIALIZER_DELIMITERS_TYPESET(
	"INITIALIZER_DELIMITER",
	Token::OBRACE,
	Token::CBRACE,
	Token::COMMA
);

const TokenTypeSet SWITCH_SECTION_DELIMITERS_TYPESET(
	"SWITCH_SECTION_DELIMITER",
	Token::KEY_CASE,
	Token::KEY_DEFAULT,
	Token::CBRACE,
	Token::END
);

const TokenTypeSet STATEMENT_DELIMITERS_TYPESET(
	"STATEMENT_DELIMITER",
	Token::KEY_BREAK,
	Token::KEY_CASE,
	Token::KEY_CONTINUE,
	Token::KEY_DEFAULT,
	Token::KEY_DO,
	Token::KEY_IF,
	Token::KEY_FOR,
	Token::KEY_RETURN,
	Token::KEY_SWITCH,
	Token::KEY_WHILE,
	Token::OBRACE,
	Token::CBRACE,
	Token::SEMICOLON
);

const TokenTypeSet LABEL_DELIMITERS_TYPESET(
	"LABEL_DELIMITER",
	Token::KEY_BREAK,
	Token::KEY_CASE,
	Token::KEY_CONTINUE,
	Token::KEY_DEFAULT,
	Token::KEY_DO,
	Token::KEY_IF,
	Token::KEY_FOR,
	Token::KEY_RETURN,
	Token::KEY_SWITCH,
	Token::KEY_WHILE,
	Token::OBRACE,
	Token::CBRACE,
	Token::SEMICOLON,
	Token::COLON
);

}


text:
package org.apache.kafka.common.requests;

import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.protocol.ApiKeys;
import org.apache.kafka.common.protocol.Errors;
import org.apache.kafka.common.protocol.types.ArrayOf;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.protocol.types.Schema;
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.record.RecordBatch;
import org.apache.kafka.common.utils.CollectionUtils;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.kafka.common.protocol.CommonFields.ERROR_CODE;
import static org.apache.kafka.common.protocol.CommonFields.PARTITION_ID;
import static org.apache.kafka.common.protocol.CommonFields.THROTTLE_TIME_MS;
import static org.apache.kafka.common.protocol.CommonFields.TOPIC_NAME;
import static org.apache.kafka.common.protocol.types.Type.INT64;

/**
 * This wrapper supports both v0 and v1 of ProduceResponse.
 */
public class ProduceResponse extends AbstractResponse {

    private static final String RESPONSES_KEY_NAME = "responses";

    // topic level field names
    private static final String PARTITION_RESPONSES_KEY_NAME = "partition_responses";

    public static final long INVALID_OFFSET = -1L;

    /**
     * Possible error code:
     *
     * CORRUPT_MESSAGE (2)
     * UNKNOWN_TOPIC_OR_PARTITION (3)
     * NOT_LEADER_FOR_PARTITION (6)
     * MESSAGE_TOO_LARGE (10)
     * INVALID_TOPIC (17)
     * RECORD_LIST_TOO_LARGE (18)
     * NOT_ENOUGH_REPLICAS (19)
     * NOT_ENOUGH_REPLICAS_AFTER_APPEND (20)
     * INVALID_REQUIRED_ACKS (21)
     * TOPIC_AUTHORIZATION_FAILED (29)
     * UNSUPPORTED_FOR_MESSAGE_FORMAT (43)
     * INVALID_PRODUCER_EPOCH (47)
     * CLUSTER_AUTHORIZATION_FAILED (31)
     * TRANSACTIONAL_ID_AUTHORIZATION_FAILED (53)
     */

    private static final String BASE_OFFSET_KEY_NAME = "base_offset";
    private static final String LOG_APPEND_TIME_KEY_NAME = "log_append_time";
    private static final String LOG_START_OFFSET_KEY_NAME = "log_start_offset";

    private static final Field.Int64 LOG_START_OFFSET_FIELD = new Field.Int64(LOG_START_OFFSET_KEY_NAME,
            "The start offset of the log at the time this produce response was created", INVALID_OFFSET);

    private static final Schema PRODUCE_RESPONSE_V0 = new Schema(
            new Field(RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                    TOPIC_NAME,
                    new Field(PARTITION_RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                            PARTITION_ID,
                            ERROR_CODE,
                            new Field(BASE_OFFSET_KEY_NAME, INT64))))))));

    private static final Schema PRODUCE_RESPONSE_V1 = new Schema(
            new Field(RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                    TOPIC_NAME,
                    new Field(PARTITION_RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                            PARTITION_ID,
                            ERROR_CODE,
                            new Field(BASE_OFFSET_KEY_NAME, INT64))))))),
            THROTTLE_TIME_MS);

    /**
     * PRODUCE_RESPONSE_V2 added a timestamp field in the per partition response status.
     * The timestamp is log append time if the topic is configured to use log append time. Or it is NoTimestamp when create
     * time is used for the topic.
     */
    private static final Schema PRODUCE_RESPONSE_V2 = new Schema(
            new Field(RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                    TOPIC_NAME,
                    new Field(PARTITION_RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                            PARTITION_ID,
                            ERROR_CODE,
                            new Field(BASE_OFFSET_KEY_NAME, INT64),
                            new Field(LOG_APPEND_TIME_KEY_NAME, INT64, "The timestamp returned by broker after appending " +
                                    "the messages. If CreateTime is used for the topic, the timestamp will be -1. " +
                                    "If LogAppendTime is used for the topic, the timestamp will be " +
                                    "the broker local time when the messages are appended."))))))),
            THROTTLE_TIME_MS);

    private static final Schema PRODUCE_RESPONSE_V3 = PRODUCE_RESPONSE_V2;

    /**
     * The body of PRODUCE_RESPONSE_V4 is the same as PRODUCE_RESPONSE_V3.
     * The version number is bumped up to indicate that the client supports KafkaStorageException.
     * The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 3
     */
    private static final Schema PRODUCE_RESPONSE_V4 = PRODUCE_RESPONSE_V3;

    /**
     * Add in the log_start_offset field to the partition response to filter out spurious OutOfOrderSequencExceptions
     * on the client.
     */
    public static final Schema PRODUCE_RESPONSE_V5 = new Schema(
            new Field(RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                    TOPIC_NAME,
                    new Field(PARTITION_RESPONSES_KEY_NAME, new ArrayOf(new Schema(
                            PARTITION_ID,
                            ERROR_CODE,
                            new Field(BASE_OFFSET_KEY_NAME, INT64),
                            new Field(LOG_APPEND_TIME_KEY_NAME, INT64, "The timestamp returned by broker after appending " +
                                    "the messages. If CreateTime is used for the topic, the timestamp will be -1. " +
                                    "If LogAppendTime is used for the topic, the timestamp will be the broker local " +
                                    "time when the messages are appended."),
                            LOG_START_OFFSET_FIELD)))))),
            THROTTLE_TIME_MS);

    /**
     * The version number is bumped to indicate that on quota violation brokers send out responses before throttling.
     */
    private static final Schema PRODUCE_RESPONSE_V6 = PRODUCE_RESPONSE_V5;

    /**
     * V7 bumped up to indicate ZStandard capability. (see KIP-110)
     */
    private static final Schema PRODUCE_RESPONSE_V7 = PRODUCE_RESPONSE_V6;

    public static Schema[] schemaVersions() {
        return new Schema[]{PRODUCE_RESPONSE_V0, PRODUCE_RESPONSE_V1, PRODUCE_RESPONSE_V2, PRODUCE_RESPONSE_V3,
            PRODUCE_RESPONSE_V4, PRODUCE_RESPONSE_V5, PRODUCE_RESPONSE_V6, PRODUCE_RESPONSE_V7};
    }

    private final Map<TopicPartition, PartitionResponse> responses;
    private final int throttleTimeMs;

    /**
     * Constructor for Version 0
     * @param responses Produced data grouped by topic-partition
     */
    public ProduceResponse(Map<TopicPartition, PartitionResponse> responses) {
        this(responses, DEFAULT_THROTTLE_TIME);
    }

    /**
     * Constructor for the latest version
     * @param responses Produced data grouped by topic-partition
     * @param throttleTimeMs Time in milliseconds the response was throttled
     */
    public ProduceResponse(Map<TopicPartition, PartitionResponse> responses, int throttleTimeMs) {
        this.responses = responses;
        this.throttleTimeMs = throttleTimeMs;
    }

    /**
     * Constructor from a {@link Struct}.
     */
    public ProduceResponse(Struct struct) {
        responses = new HashMap<>();
        for (Object topicResponse : struct.getArray(RESPONSES_KEY_NAME)) {
            Struct topicRespStruct = (Struct) topicResponse;
            String topic = topicRespStruct.get(TOPIC_NAME);
            for (Object partResponse : topicRespStruct.getArray(PARTITION_RESPONSES_KEY_NAME)) {
                Struct partRespStruct = (Struct) partResponse;
                int partition = partRespStruct.get(PARTITION_ID);
                Errors error = Errors.forCode(partRespStruct.get(ERROR_CODE));
                long offset = partRespStruct.getLong(BASE_OFFSET_KEY_NAME);
                long logAppendTime = partRespStruct.getLong(LOG_APPEND_TIME_KEY_NAME);
                long logStartOffset = partRespStruct.getOrElse(LOG_START_OFFSET_FIELD, INVALID_OFFSET);
                TopicPartition tp = new TopicPartition(topic, partition);
                responses.put(tp, new PartitionResponse(error, offset, logAppendTime, logStartOffset));
            }
        }
        this.throttleTimeMs = struct.getOrElse(THROTTLE_TIME_MS, DEFAULT_THROTTLE_TIME);
    }

    @Override
    protected Struct toStruct(short version) {
        Struct struct = new Struct(ApiKeys.PRODUCE.responseSchema(version));

        Map<String, Map<Integer, PartitionResponse>> responseByTopic = CollectionUtils.groupPartitionDataByTopic(responses);
        List<Struct> topicDatas = new ArrayList<>(responseByTopic.size());
        for (Map.Entry<String, Map<Integer, PartitionResponse>> entry : responseByTopic.entrySet()) {
            Struct topicData = struct.instance(RESPONSES_KEY_NAME);
            topicData.set(TOPIC_NAME, entry.getKey());
            List<Struct> partitionArray = new ArrayList<>();
            for (Map.Entry<Integer, PartitionResponse> partitionEntry : entry.getValue().entrySet()) {
                PartitionResponse part = partitionEntry.getValue();
                short errorCode = part.error.code();
                // If producer sends ProduceRequest V3 or earlier, the client library is not guaranteed to recognize the error code
                // for KafkaStorageException. In this case the client library will translate KafkaStorageException to
                // UnknownServerException which is not retriable. We can ensure that producer will update metadata and retry
                // by converting the KafkaStorageException to NotLeaderForPartitionException in the response if ProduceRequest version <= 3
                if (errorCode == Errors.KAFKA_STORAGE_ERROR.code() && version <= 3)
                    errorCode = Errors.NOT_LEADER_FOR_PARTITION.code();
                Struct partStruct = topicData.instance(PARTITION_RESPONSES_KEY_NAME)
                        .set(PARTITION_ID, partitionEntry.getKey())
                        .set(ERROR_CODE, errorCode)
                        .set(BASE_OFFSET_KEY_NAME, part.baseOffset);
                if (partStruct.hasField(LOG_APPEND_TIME_KEY_NAME))
                    partStruct.set(LOG_APPEND_TIME_KEY_NAME, part.logAppendTime);
                partStruct.setIfExists(LOG_START_OFFSET_FIELD, part.logStartOffset);
                partitionArray.add(partStruct);
            }
            topicData.set(PARTITION_RESPONSES_KEY_NAME, partitionArray.toArray());
            topicDatas.add(topicData);
        }
        struct.set(RESPONSES_KEY_NAME, topicDatas.toArray());
        struct.setIfExists(THROTTLE_TIME_MS, throttleTimeMs);

        return struct;
    }

    public Map<TopicPartition, PartitionResponse> responses() {
        return this.responses;
    }

    @Override
    public int throttleTimeMs() {
        return this.throttleTimeMs;
    }

    @Override
    public Map<Errors, Integer> errorCounts() {
        Map<Errors, Integer> errorCounts = new HashMap<>();
        for (PartitionResponse response : responses.values())
            updateErrorCounts(errorCounts, response.error);
        return errorCounts;
    }

    public static final class PartitionResponse {
        public Errors error;
        public long baseOffset;
        public long logAppendTime;
        public long logStartOffset;

        public PartitionResponse(Errors error) {
            this(error, INVALID_OFFSET, RecordBatch.NO_TIMESTAMP, INVALID_OFFSET);
        }

        public PartitionResponse(Errors error, long baseOffset, long logAppendTime, long logStartOffset) {
            this.error = error;
            this.baseOffset = baseOffset;
            this.logAppendTime = logAppendTime;
            this.logStartOffset = logStartOffset;
        }

        @Override
        public String toString() {
            StringBuilder b = new StringBuilder();
            b.append('{');
            b.append("error: ");
            b.append(error);
            b.append(",offset: ");
            b.append(baseOffset);
            b.append(",logAppendTime: ");
            b.append(logAppendTime);
            b.append(", logStartOffset: ");
            b.append(logStartOffset);
            b.append('}');
            return b.toString();
        }
    }

    public static ProduceResponse parse(ByteBuffer buffer, short version) {
        return new ProduceResponse(ApiKeys.PRODUCE.responseSchema(version).read(buffer));
    }

    @Override
    public boolean shouldClientThrottle(short version) {
        return version >= 6;
    }
}


text:
package com.sun.xml.internal.ws.commons.xmlutil;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.logging.Logger;
import com.sun.xml.internal.ws.api.message.Message;
import com.sun.xml.internal.ws.api.message.Messages;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.util.xml.XmlUtil;

import javax.xml.stream.*;
import javax.xml.xpath.XPathFactoryConfigurationException;
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;

/**
 * Utility class that provides conversion of different XML representations
 * from/to various other formats
 *
 * @author Marek Potociar
 */
public final class Converter {

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

    private Converter() {
        // prevents instantiation
    }
    private static final Logger LOGGER = Logger.getLogger(Converter.class);
    private static final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    private static final AtomicBoolean logMissingStaxUtilsWarning = new AtomicBoolean(false);

    /**
     * Converts a throwable to String
     *
     * @param throwable
     * @return String representation of throwable
     */
    public static String toString(Throwable throwable) {
        if (throwable == null) {
            return "[ No exception ]";
        }

        StringWriter stringOut = new StringWriter();
        throwable.printStackTrace(new PrintWriter(stringOut));

        return stringOut.toString();
    }

    public static String toString(Packet packet) {
        if (packet == null) {
            return "[ Null packet ]";
        } else if (packet.getMessage() == null) {
                return "[ Empty packet ]";
        }

        return toString(packet.getMessage());
    }

    public static String toStringNoIndent(Packet packet) {
        if (packet == null) {
            return "[ Null packet ]";
        } else if (packet.getMessage() == null) {
                return "[ Empty packet ]";
        }

        return toStringNoIndent(packet.getMessage());
    }

    public static String toString(Message message) {
        return toString(message, true);
    }

    public static String toStringNoIndent(Message message) {
        return toString(message, false);
    }

    private static String toString(Message message, boolean createIndenter) {
        if (message == null) {
            return "[ Null message ]";
        }
        StringWriter stringOut = null;
        try {
            stringOut = new StringWriter();
            XMLStreamWriter writer = null;
            try {
                writer = xmlOutputFactory.createXMLStreamWriter(stringOut);
                if (createIndenter) {
                    writer = createIndenter(writer);
                }
                message.copy().writeTo(writer);
            } catch (Exception e) { // WSIT-1596 - Message Dumping should not affect other processing
                LOGGER.log(Level.WARNING, "Unexpected exception occured while dumping message", e);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (XMLStreamException ignored) {
                        LOGGER.fine("Unexpected exception occured while closing XMLStreamWriter", ignored);
                    }
                }
            }
            return stringOut.toString();
        } finally {
            if (stringOut != null) {
                try {
                    stringOut.close();
                } catch (IOException ex) {
                    LOGGER.finest("An exception occured when trying to close StringWriter", ex);
                }
            }
        }
    }

    public static byte[] toBytes(Message message, String encoding) throws XMLStreamException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            if (message != null) {
                XMLStreamWriter xsw = xmlOutputFactory.createXMLStreamWriter(baos, encoding);
                try {
                    message.writeTo(xsw);
                } finally {
                    try {
                        xsw.close();
                    } catch (XMLStreamException ex) {
                        LOGGER.warning("Unexpected exception occured while closing XMLStreamWriter", ex);
                    }
                }
            }

            return baos.toByteArray();
        } finally {
            try {
                baos.close();
            } catch (IOException ex) {
                LOGGER.warning("Unexpected exception occured while closing ByteArrayOutputStream", ex);
            }
        }
    }

    /**
     * Converts JAX-WS RI message represented as input stream back to Message
     * object.
     *
     * @param dataStream message data stream
     * @param encoding message data stream encoding
     *
     * @return {@link com.sun.xml.internal.ws.api.message.Message} object created from the data stream
     */
    public static Message toMessage(@NotNull InputStream dataStream, String encoding) throws XMLStreamException {
        XMLStreamReader xsr = XmlUtil.newXMLInputFactory(true).createXMLStreamReader(dataStream, encoding);
        return Messages.create(xsr);
    }

    public static String messageDataToString(final byte[] data, final String encoding) {
        try {
            return toString(toMessage(new ByteArrayInputStream(data), encoding));
            // closing ByteArrayInputStream has no effect, so ignoring the redundant call
        } catch (XMLStreamException ex) {
            LOGGER.warning("Unexpected exception occured while converting message data to string", ex);
            return "[ Message Data Conversion Failed ]";
        }
    }

    /**
     * Wraps {@link javax.xml.stream.XMLStreamWriter} by an indentation engine if possible.
     *
     * <p>
     * We can do this only when we have <tt>stax-utils.jar</tt> in the class path.
     */
    private static XMLStreamWriter createIndenter(XMLStreamWriter writer) {
        try {
            Class<?> clazz = Converter.class.getClassLoader().loadClass("javanet.staxutils.IndentingXMLStreamWriter");
            Constructor<?> c = clazz.getConstructor(XMLStreamWriter.class);
            writer = XMLStreamWriter.class.cast(c.newInstance(writer));
        } catch (Exception ex) {
            // if stax-utils.jar is not in the classpath, this will fail
            // so, we'll just have to do without indentation
            if (logMissingStaxUtilsWarning.compareAndSet(false, true)) {
                LOGGER.log(Level.WARNING, "Put stax-utils.jar to the classpath to indent the dump output", ex);
            }
        }
        return writer;
    }
}


text:
var DomUI = function(options) {
    for (var key in options) {
        this[key] = options[key];
    }
};

(function(exports) {

    var proto = {

        constructor: DomUI,

        containerId: "ui-container",
        container: null,

        init: function() {
            this.tapListeners = this.tapListeners || {};
            this.container = this.$id(this.containerId);
            this.uiList = document.querySelectorAll("#" + this.containerId + " > div");
        },

        $id: function(id) {
            return document.getElementById(id);
        },

        showContainer: function() {
            this.container.style.visibility = "visible";
            this.container.style.left = "0px";
            this.container.style.top = "0px";
        },

        hideContainer: function() {
            this.container.style.visibility = "hidden";
            this.container.style.left = "-120%";
            this.container.style.top = "-120%";
        },

        show: function(id, mask) {
            this.showContainer();
            var ui = this.$id(id);
            for (var i = 0, len = this.uiList.length; i < len; i++) {
                var _ui = this.uiList[i];
                if (_ui != ui) {
                    _ui.style.display = "none";
                }
            }
            ui.style.display = "block";

            if (mask) {
                this.container.classList.add("ui-mask");
            } else {
                this.container.classList.remove("ui-mask");
            }
        },

        hide: function(id) {
            this.hideContainer();
            var ui = this.$id(id);
            ui.style.display = "none";
        },

        onTouchMove: function(event) {
            var dom = this.lastButton
            if (dom) {
                dom.style.transform = "scale(1,1)"
                dom.style.webkitTransform = "scale(1,1)"
                this.lastButton = null;
                // dom.touched = false;
            }
        },
        onTouchStart: function(event) {
            var dom = event.target;
            var id = dom.id;
            var fn = this.tapListeners[id];
            if (fn && !dom.touched) {
                dom.style.transform = "scale(0.9,0.9)"
                dom.style.webkitTransform = "scale(0.9,0.9)"
                dom.touched = true;
                this.lastButton = dom;
                return true;
            }
            if (this.container.contains(dom)){
                return true;
            }
        },
        onTouchTap: function(event) {
            var dom = event.target;
            var id = dom.id;
            var fn = this.tapListeners[id];
            if (fn) {
                dom.style.transform = "scale(1,1)"
                dom.style.webkitTransform = "scale(1,1)"
                dom.touched = false;
                fn(event);
                this.lastButton = null;
                return true;
            }
            if (this.container.contains(dom)){
                return true;
            }
        },
        onTouchEnd: function(event) {
            var dom = event.target;
            var id = dom.id;
            var fn = this.tapListeners[id];
            if (fn) {
                dom.style.transform = "scale(1,1)"
                dom.style.webkitTransform = "scale(1,1)"
                dom.touched = false;
                this.lastButton = null;
                return true;
            }
            if (this.container.contains(dom)){
                return true;
            }
        },

    };

    for (var p in proto) {
        DomUI.prototype[p] = proto[p];
    }

    if (typeof module != "undefined") {
        module.exports = DomUI;
    }

}());


text:
<article <?php post_class('full'); ?>>

      <?php echo roots_title(); ?>

    <?php get_template_part('templates/book-partials/cover'); ?>
    <?php get_template_part('templates/book-partials/library-status'); ?>

    <?php get_template_part('templates/book-partials/meta1'); ?>

      <?php get_template_part('templates/book-partials/cover'); ?>
      <?php get_template_part('templates/book-partials/library-status'); ?>

    <?php get_template_part('templates/book-partials/review'); ?>
    <?php get_template_part('templates/book-partials/quote'); ?>
    <?php get_template_part('templates/book-partials/more'); ?>
    <?php get_template_part('templates/book-partials/icon-nav'); ?>
    <?php get_template_part('templates/book-partials/meta2'); ?>
    <?php get_template_part('templates/book-partials/lsb-supported'); ?>

    <?php get_template_part('templates/book-partials/embeds'); ?>


text: [Repo del curso](https://github.com/sinaptica/curso-git)


text:
package com.appfeel.cordova.admob;

import android.annotation.SuppressLint;
import android.util.Log;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;

@SuppressLint("DefaultLocale")
public class AdMobAdsAdListener extends AdListener {
  private String adType = "";
  private AdMobAds admobAds;
  private IAdLoadedAvailable iAdLoadedAvailable;

  public interface IAdLoadedAvailable {
    void onAdLoaded(String adType);

    void onAdOpened(String adType);
  }

  public AdMobAdsAdListener(String adType, AdMobAds admobAds, IAdLoadedAvailable iAdLoadedAvailable) {
    this.adType = adType;
    this.admobAds = admobAds;
    this.iAdLoadedAvailable = iAdLoadedAvailable;
  }

  @Override
  public void onAdLoaded() {
    iAdLoadedAvailable.onAdLoaded(adType);
    Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad loaded");
    String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdLoaded, { 'adType': '%s' });", adType);
    admobAds.webView.loadUrl(event);
  }

  @Override
  public void onAdFailedToLoad(int errorCode) {
    String reason = getErrorReason(errorCode);
    Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": fail to load ad (" + reason + ")");
    String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdFailedToLoad, { 'adType': '%s', 'error': %d, 'reason': '%s' });", adType, errorCode, reason);
    admobAds.webView.loadUrl(event);
  }

  /** Gets a string error reason from an error code. */
  public String getErrorReason(int errorCode) {
    String errorReason = "Unknown";
    switch (errorCode) {
    case AdRequest.ERROR_CODE_INTERNAL_ERROR:
      errorReason = "Internal error";
      break;
    case AdRequest.ERROR_CODE_INVALID_REQUEST:
      errorReason = "Invalid request";
      break;
    case AdRequest.ERROR_CODE_NETWORK_ERROR:
      errorReason = "Network Error";
      break;
    case AdRequest.ERROR_CODE_NO_FILL:
      errorReason = "No fill";
      break;
    }
    return errorReason;
  }

  @Override
  public void onAdOpened() {
    iAdLoadedAvailable.onAdOpened(adType);
    Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad opened");
    String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdOpened, { 'adType': '%s' });", adType);
    admobAds.webView.loadUrl(event);
  }

  @Override
  public void onAdLeftApplication() {
    Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": left application");
    String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdLeftApplication, { 'adType': '%s' });", adType);
    admobAds.webView.loadUrl(event);
  }

  @Override
  public void onAdClosed() {
    Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad closed after clicking on it");
    String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdClosed, { 'adType': '%s' });", adType);
    admobAds.webView.loadUrl(event);
  }
}


text:
import {AdTracker, getExistingAds} from './ad-tracker';
import {AdStrategy} from './ad-strategy';
import {user} from '../../../src/log';
import {xhrFor} from '../../../src/services';
import {getAdNetworkConfig} from './ad-network-config';
import {isExperimentOn} from '../../../src/experiments';
import {getAttributesFromConfigObj} from './attributes';
import {getPlacementsFromConfigObj} from './placement';

/** @const */
const TAG = 'amp-auto-ads';

export class AmpAutoAds extends AMP.BaseElement {

  /** @override */
  buildCallback() {
    user().assert(isExperimentOn(self, 'amp-auto-ads'), 'Experiment is off');

    const type = this.element.getAttribute('type');
    user().assert(type, 'Missing type attribute');

    const adNetwork = getAdNetworkConfig(type, this.element);
    user().assert(adNetwork, 'No AdNetworkConfig for type: ' + type);

    if (!adNetwork.isEnabled(this.win)) {
      return;
    }

    this.getConfig_(adNetwork.getConfigUrl()).then(configObj => {
      if (!configObj) {
        return;
      }

      const placements = getPlacementsFromConfigObj(this.win, configObj);
      const attributes = Object.assign(adNetwork.getAttributes(),
          getAttributesFromConfigObj(configObj));
      const adTracker =
          new AdTracker(getExistingAds(this.win), adNetwork.getAdConstraints());
      new AdStrategy(placements, attributes, adTracker).run();
    });
  }

  /** @override */
  isLayoutSupported() {
    return true;
  }

  /**
   * Tries to load an auto-ads configuration from the given URL. This uses a
   * non-credentialed request.
   * @param {string} configUrl
   * @return {!Promise<!JSONType>}
   * @private
   */
  getConfig_(configUrl) {
    // Non-credentialed request
    const xhrInit = {
      mode: 'cors',
      method: 'GET',
      credentials: 'omit',
      requireAmpResponseSourceOrigin: false,
    };
    return xhrFor(this.win)
        .fetchJson(configUrl, xhrInit)
        .catch(reason => {
          user().error(TAG, 'amp-auto-ads config xhr failed: ' + reason);
          return null;
        });
  }
}

AMP.registerElement('amp-auto-ads', AmpAutoAds);


text:
export default {
  dialPlaceholder: "Inserir nome ou número"
};

// @key: @#@"dialPlaceholder"@#@ @source: @#@"Enter Name or Number"@#@


text:
            <input id="overlay-search" class="no-border overlay-search bg-transparent" placeholder="Search..." autocomplete="off" spellcheck="false">

                    <input id="checkboxn" type="checkbox" value="1" checked="checked">
                     Search within page

Press enter to search

                suggestions :

Pages Search Results

ice cream on pages

via john smith

T

ice cream related topics

via pages

ice cream music

via pagesmix

ice cream on facebook

via facebook

Tweats on ice cream

via twitter

Circles on ice cream

via google plus


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>ag-netbeans-modules</artifactId>
        <groupId>org.modelinglab.actiongui.netbeans</groupId>
        <version>0.1.2</version>
    </parent>
    <groupId>org.modelinglab.actiongui.netbeans.dtm</groupId>
    <artifactId>dtm</artifactId>

    <packaging>pom</packaging>

    <name>ActionGUI DTM Modules</name>

    <modules>
        <module>dtm-file</module>
        <module>dtm-language</module>
        <module>dtm-braces-matcher</module>
    </modules>
</project>


text:
"""Climate platform for Advantage Air integration."""
from __future__ import annotations

import logging
from typing import Any

from homeassistant.components.climate import (
    FAN_AUTO,
    FAN_HIGH,
    FAN_LOW,
    FAN_MEDIUM,
    ClimateEntity,
    ClimateEntityFeature,
    HVACMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, PRECISION_WHOLE, TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import (
    ADVANTAGE_AIR_STATE_CLOSE,
    ADVANTAGE_AIR_STATE_OFF,
    ADVANTAGE_AIR_STATE_ON,
    ADVANTAGE_AIR_STATE_OPEN,
    DOMAIN as ADVANTAGE_AIR_DOMAIN,
)
from .entity import AdvantageAirAcEntity, AdvantageAirZoneEntity

ADVANTAGE_AIR_HVAC_MODES = {
    "heat": HVACMode.HEAT,
    "cool": HVACMode.COOL,
    "vent": HVACMode.FAN_ONLY,
    "dry": HVACMode.DRY,
    "myauto": HVACMode.AUTO,
}
HASS_HVAC_MODES = {v: k for k, v in ADVANTAGE_AIR_HVAC_MODES.items()}

AC_HVAC_MODES = [
    HVACMode.OFF,
    HVACMode.COOL,
    HVACMode.HEAT,
    HVACMode.FAN_ONLY,
    HVACMode.DRY,
]

ADVANTAGE_AIR_FAN_MODES = {
    "autoAA": FAN_AUTO,
    "low": FAN_LOW,
    "medium": FAN_MEDIUM,
    "high": FAN_HIGH,
}
HASS_FAN_MODES = {v: k for k, v in ADVANTAGE_AIR_FAN_MODES.items()}
FAN_SPEEDS = {FAN_LOW: 30, FAN_MEDIUM: 60, FAN_HIGH: 100}

ZONE_HVAC_MODES = [HVACMode.OFF, HVACMode.HEAT_COOL]

PARALLEL_UPDATES = 0

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up AdvantageAir climate platform."""

    instance = hass.data[ADVANTAGE_AIR_DOMAIN][config_entry.entry_id]

    entities: list[ClimateEntity] = []
    if aircons := instance["coordinator"].data.get("aircons"):
        for ac_key, ac_device in aircons.items():
            entities.append(AdvantageAirAC(instance, ac_key))
            for zone_key, zone in ac_device["zones"].items():
                # Only add zone climate control when zone is in temperature control
                if zone["type"] != 0:
                    entities.append(AdvantageAirZone(instance, ac_key, zone_key))
    async_add_entities(entities)

class AdvantageAirAC(AdvantageAirAcEntity, ClimateEntity):
    """AdvantageAir AC unit."""

    _attr_temperature_unit = TEMP_CELSIUS
    _attr_target_temperature_step = PRECISION_WHOLE
    _attr_max_temp = 32
    _attr_min_temp = 16
    _attr_fan_modes = [FAN_AUTO, FAN_LOW, FAN_MEDIUM, FAN_HIGH]
    _attr_hvac_modes = AC_HVAC_MODES
    _attr_supported_features = (
        ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.FAN_MODE
    )

    def __init__(self, instance: dict[str, Any], ac_key: str) -> None:
        """Initialize an AdvantageAir AC unit."""
        super().__init__(instance, ac_key)
        if self._ac.get("myAutoModeEnabled"):
            self._attr_hvac_modes = AC_HVAC_MODES + [HVACMode.AUTO]

    @property
    def target_temperature(self) -> float:
        """Return the current target temperature."""
        return self._ac["setTemp"]

    @property
    def hvac_mode(self) -> HVACMode | None:
        """Return the current HVAC modes."""
        if self._ac["state"] == ADVANTAGE_AIR_STATE_ON:
            return ADVANTAGE_AIR_HVAC_MODES.get(self._ac["mode"])
        return HVACMode.OFF

    @property
    def fan_mode(self) -> str | None:
        """Return the current fan modes."""
        return ADVANTAGE_AIR_FAN_MODES.get(self._ac["fan"])

    async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
        """Set the HVAC Mode and State."""
        if hvac_mode == HVACMode.OFF:
            await self.aircon(
                {self.ac_key: {"info": {"state": ADVANTAGE_AIR_STATE_OFF}}}
            )
        else:
            await self.aircon(
                {
                    self.ac_key: {
                        "info": {
                            "state": ADVANTAGE_AIR_STATE_ON,
                            "mode": HASS_HVAC_MODES.get(hvac_mode),
                        }
                    }
                }
            )

    async def async_set_fan_mode(self, fan_mode: str) -> None:
        """Set the Fan Mode."""
        await self.aircon(
            {self.ac_key: {"info": {"fan": HASS_FAN_MODES.get(fan_mode)}}}
        )

    async def async_set_temperature(self, **kwargs: Any) -> None:
        """Set the Temperature."""
        temp = kwargs.get(ATTR_TEMPERATURE)
        await self.aircon({self.ac_key: {"info": {"setTemp": temp}}})

class AdvantageAirZone(AdvantageAirZoneEntity, ClimateEntity):
    """AdvantageAir Zone control."""

    _attr_temperature_unit = TEMP_CELSIUS
    _attr_target_temperature_step = PRECISION_WHOLE
    _attr_max_temp = 32
    _attr_min_temp = 16
    _attr_hvac_modes = ZONE_HVAC_MODES
    _attr_supported_features = ClimateEntityFeature.TARGET_TEMPERATURE

    def __init__(self, instance: dict[str, Any], ac_key: str, zone_key: str) -> None:
        """Initialize an AdvantageAir Zone control."""
        super().__init__(instance, ac_key, zone_key)
        self._attr_name = self._zone["name"]
        self._attr_unique_id = (
            f'{self.coordinator.data["system"]["rid"]}-{ac_key}-{zone_key}'
        )

    @property
    def hvac_mode(self) -> HVACMode:
        """Return the current state as HVAC mode."""
        if self._zone["state"] == ADVANTAGE_AIR_STATE_OPEN:
            return HVACMode.HEAT_COOL
        return HVACMode.OFF

    @property
    def current_temperature(self) -> float:
        """Return the current temperature."""
        return self._zone["measuredTemp"]

    @property
    def target_temperature(self) -> float:
        """Return the target temperature."""
        return self._zone["setTemp"]

    async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
        """Set the HVAC Mode and State."""
        if hvac_mode == HVACMode.OFF:
            await self.aircon(
                {
                    self.ac_key: {
                        "zones": {self.zone_key: {"state": ADVANTAGE_AIR_STATE_CLOSE}}
                    }
                }
            )
        else:
            await self.aircon(
                {
                    self.ac_key: {
                        "zones": {self.zone_key: {"state": ADVANTAGE_AIR_STATE_OPEN}}
                    }
                }
            )

    async def async_set_temperature(self, **kwargs: Any) -> None:
        """Set the Temperature."""
        temp = kwargs.get(ATTR_TEMPERATURE)
        await self.aircon({self.ac_key: {"zones": {self.zone_key: {"setTemp": temp}}}})


text:
FarmBot
=======

All things FarmBot, from the backend to the frontend to the microcontroller firmware to the decision support system.


text:
package org.jf.dexlib2.writer.builder;

import com.google.common.collect.*;

import org.jf.dexlib2.iface.*;
import org.jf.dexlib2.writer.*;
import org.jf.dexlib2.writer.builder.BuilderEncodedValues.*;

import java.util.*;
import java.util.Map.*;
import java.util.concurrent.*;

import javax.annotation.*;

class BuilderAnnotationPool implements AnnotationSection<BuilderStringReference, BuilderTypeReference,
        BuilderAnnotation, BuilderAnnotationElement, BuilderEncodedValue> {
    @Nonnull
    private final BuilderContext context;
    @Nonnull
    private final ConcurrentMap<Annotation, BuilderAnnotation> internedItems =
            Maps.newConcurrentMap();

    BuilderAnnotationPool(@Nonnull BuilderContext context) {
        this.context = context;
    }

    @Nonnull
    public BuilderAnnotation internAnnotation(@Nonnull Annotation annotation) {
        BuilderAnnotation ret = internedItems.get(annotation);
        if (ret != null) {
            return ret;
        }

        BuilderAnnotation dexBuilderAnnotation = new BuilderAnnotation(
                annotation.getVisibility(),
                context.typePool.internType(annotation.getType()),
                context.internAnnotationElements(annotation.getElements()));
        ret = internedItems.putIfAbsent(dexBuilderAnnotation, dexBuilderAnnotation);
        return ret == null ? dexBuilderAnnotation : ret;
    }

    @Override
    public int getVisibility(@Nonnull BuilderAnnotation key) {
        return key.visibility;
    }

    @Nonnull
    @Override
    public BuilderTypeReference getType(@Nonnull BuilderAnnotation key) {
        return key.type;
    }

    @Nonnull
    @Override
    public Collection<? extends BuilderAnnotationElement> getElements(@Nonnull BuilderAnnotation key) {
        return key.elements;
    }

    @Nonnull
    @Override
    public BuilderStringReference getElementName(@Nonnull BuilderAnnotationElement element) {
        return element.name;
    }

    @Nonnull
    @Override
    public BuilderEncodedValue getElementValue(@Nonnull BuilderAnnotationElement element) {
        return element.value;
    }

    @Override
    public int getItemOffset(@Nonnull BuilderAnnotation key) {
        return key.offset;
    }

    @Nonnull
    @Override
    public Collection<? extends Entry<? extends BuilderAnnotation, Integer>> getItems() {
        return new BuilderMapEntryCollection<BuilderAnnotation>(internedItems.values()) {
            @Override
            protected int getValue(@Nonnull BuilderAnnotation key) {
                return key.offset;
            }

            @Override
            protected int setValue(@Nonnull BuilderAnnotation key, int value) {
                int prev = key.offset;
                key.offset = value;
                return prev;
            }
        };
    }
}


text:
using System;
using System.Collections.Generic;
#if NET_45
using System.Collections.ObjectModel;
#endif
using System.Threading.Tasks;

namespace Octokit
{
    /// <summary>
    /// Used to paginate through API response results.
    /// </summary>
    /// <remarks>
    /// This is meant to be internal, but I factored it out so we can change our mind more easily later.
    /// </remarks>
    public class ApiPagination : IApiPagination
    {
        public async Task<IReadOnlyList<T>> GetAllPages<T>(Func<Task<IReadOnlyPagedCollection<T>>> getFirstPage)
        {
            Ensure.ArgumentNotNull(getFirstPage, "getFirstPage");

            var page = await getFirstPage().ConfigureAwait(false);
            var allItems = new List<T>(page);
            while ((page = await page.GetNextPage().ConfigureAwait(false)) != null)
            {
                allItems.AddRange(page);
            }
            return new ReadOnlyCollection<T>(allItems);
        }
    }
}


text:
import XRegExp from 'xregexp/lib/xregexp';
import build from 'xregexp/lib/addons/build';

build(XRegExp);

// This function makes it easy to build regular expressions that look more like formal grammars.
// See here for more info:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals
// http://xregexp.com/api/#build
export default XRegExp.tag('xngm');
/* Usage Example:

    import regex from './regex';
    const sub = /inner/;
    const outer = regex`
      # comments start with #
      before

      # whitespace is insignificant, match it with \s
      \s

      # a reference to the 'sub' regex
      ${sub}

      \s

      # groups are not captured by default
      (after | after2)

      \s

      # this group is captured
      (?<name> after2 )
      $
    `;
    outer.exec('before inner after after2'); // ['before inner after after2', 'after2']
*/


text:
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;

namespace Client.Renderer.Particles
{
	using System;
	using Microsoft.Xna.Framework;

	/// <summary>
	/// The main component in charge of displaying particles.
	/// </summary>
	public abstract class ParticleSystem : DrawableGameComponent
	{
		#region Fields

		// Settings class controls the appearance and animation of this particle system.
		ParticleSettings settings = new ParticleSettings();
		object settingNewParameterLocker = new object();

		// For loading the effect and particle texture.
		ContentManager content;

		// Custom effect for drawing particles. This computes the particle
		// animation entirely in the vertex shader: no per-particle CPU work required!
		Effect particleEffect;

		// Shortcuts for accessing frequently changed effect parameters.
		EffectParameter effectViewParameter;
		EffectParameter effectProjectionParameter;
		EffectParameter effectViewportScaleParameter;
		EffectParameter effectTimeParameter;
		EffectParameter effectMinColorParameter;
		EffectParameter effectMaxColorParameter;

		// An array of particles, treated as a circular queue.
		ParticleVertex[] particles;

		// A vertex buffer holding our particles. This contains the same data as
		// the particles array, but copied across to where the GPU can access it.
		DynamicVertexBuffer vertexBuffer;

		// Index buffer turns sets of four vertices into particle quads (pairs of triangles).
		IndexBuffer indexBuffer;

		// The particles array and vertex buffer are treated as a circular queue.
		// Initially, the entire contents of the array are free, because no particles
		// are in use. When a new particle is created, this is allocated from the
		// beginning of the array. If more than one particle is created, these will
		// always be stored in a consecutive block of array elements. Because all
		// particles last for the same amount of time, old particles will always be
		// removed in order from the start of this active particle region, so the
		// active and free regions will never be intermingled. Because the queue is
		// circular, there can be times when the active particle region wraps from the
		// end of the array back to the start. The queue uses modulo arithmetic to
		// handle these cases. For instance with a four entry queue we could have:
		//
		//      0
		//      1 - first active particle
		//      2
		//      3 - first free particle
		//
		// In this case, particles 1 and 2 are active, while 3 and 4 are free.
		// Using modulo arithmetic we could also have:
		//
		//      0
		//      1 - first free particle
		//      2
		//      3 - first active particle
		//
		// Here, 3 and 0 are active, while 1 and 2 are free.
		//
		// But wait! The full story is even more complex.
		//
		// When we create a new particle, we add them to our managed particles array.
		// We also need to copy this new data into the GPU vertex buffer, but we don't
		// want to do that straight away, because setting new data into a vertex buffer
		// can be an expensive operation. If we are going to be adding several particles
		// in a single frame, it is faster to initially just store them in our managed
		// array, and then later upload them all to the GPU in one single call. So our
		// queue also needs a region for storing new particles that have been added to
		// the managed array but not yet uploaded to the vertex buffer.
		//
		// Another issue occurs when old particles are retired. The CPU and GPU run
		// asynchronously, so the GPU will often still be busy drawing the previous
		// frame while the CPU is working on the next frame. This can cause a
		// synchronization problem if an old particle is retired, and then immediately
		// overwritten by a new one, because the CPU might try to change the contents
		// of the vertex buffer while the GPU is still busy drawing the old data from
		// it. Normally the graphics driver will take care of this by waiting until
		// the GPU has finished drawing inside the VertexBuffer.SetData call, but we
		// don't want to waste time waiting around every time we try to add a new
		// particle! To avoid this delay, we can specify the SetDataOptions.NoOverwrite
		// flag when we write to the vertex buffer. This basically means "I promise I
		// will never try to overwrite any data that the GPU might still be using, so
		// you can just go ahead and update the buffer straight away". To keep this
		// promise, we must avoid reusing vertices immediately after they are drawn.
		//
		// So in total, our queue contains four different regions:
		//
		// Vertices between firstActiveParticle and firstNewParticle are actively
		// being drawn, and exist in both the managed particles array and the GPU
		// vertex buffer.
		//
		// Vertices between firstNewParticle and firstFreeParticle are newly created,
		// and exist only in the managed particles array. These need to be uploaded
		// to the GPU at the start of the next draw call.
		//
		// Vertices between firstFreeParticle and firstRetiredParticle are free and
		// waiting to be allocated.
		//
		// Vertices between firstRetiredParticle and firstActiveParticle are no longer
		// being drawn, but were drawn recently enough that the GPU could still be
		// using them. These need to be kept around for a few more frames before they
		// can be reallocated.

		int firstActiveParticle;
		int firstNewParticle;
		int firstFreeParticle;
		int firstRetiredParticle;

		// Store the current time, in seconds.
		float currentTime;

		// Count how many times Draw has been called. This is used to know
		// when it is safe to retire old particles back into the free list.
		int drawCounter;

		// Shared random number generator.
		static Random random = new Random();

		#endregion

		#region Initialization

		/// <summary>
		/// Constructor.
		/// </summary>
		protected ParticleSystem(Game game, ContentManager content)
			: base(game)
		{
			this.content = content;
		}

		/// <summary>
		/// Initializes the component.
		/// </summary>
		public override void Initialize()
		{
			InitializeSettings(settings);

			// Allocate the particle array, and fill in the corner fields (which never change).
			particles = new ParticleVertex[settings.MaxParticles * 4];

			for (int i = 0; i < settings.MaxParticles; i++)
			{
				particles[i * 4 + 0].Corner = new Short2(-1, -1);
				particles[i * 4 + 1].Corner = new Short2(1, -1);
				particles[i * 4 + 2].Corner = new Short2(1, 1);
				particles[i * 4 + 3].Corner = new Short2(-1, 1);
			}

			base.Initialize();
		}

		/// <summary>
		/// Derived particle system classes should override this method
		/// and use it to initalize their tweakable settings.
		/// </summary>
		protected abstract void InitializeSettings(ParticleSettings settings);

		/// <summary>
		/// Loads graphics for the particle system.
		/// </summary>
		protected override void LoadContent()
		{
			LoadParticleEffect();

			// Create a dynamic vertex buffer.
			vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ParticleVertex.VertexDeclaration,
												   settings.MaxParticles * 4, BufferUsage.WriteOnly);

			// Create and populate the index buffer.
			ushort[] indices = new ushort[settings.MaxParticles * 6];

			for (int i = 0; i < settings.MaxParticles; i++)
			{
				indices[i * 6 + 0] = (ushort)(i * 4 + 0);
				indices[i * 6 + 1] = (ushort)(i * 4 + 1);
				indices[i * 6 + 2] = (ushort)(i * 4 + 2);

				indices[i * 6 + 3] = (ushort)(i * 4 + 0);
				indices[i * 6 + 4] = (ushort)(i * 4 + 2);
				indices[i * 6 + 5] = (ushort)(i * 4 + 3);
			}

			indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly);

			indexBuffer.SetData(indices);
		}

		/// <summary>
		/// Helper for loading and initializing the particle effect.
		/// </summary>
		void LoadParticleEffect()
		{
			Effect effect = content.Load<Effect>(@"Effects\Particle");

			// If we have several particle systems, the content manager will return
			// a single shared effect instance to them all. But we want to preconfigure
			// the effect with parameters that are specific to this particular
			// particle system. By cloning the effect, we prevent one particle system
			// from stomping over the parameter settings of another.

			particleEffect = effect.Clone();

			EffectParameterCollection parameters = particleEffect.Parameters;

			// Set the values of parameters that do not change.
			parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds);
			parameters["DurationRandomness"].SetValue(settings.DurationRandomness);
			parameters["Gravity"].SetValue(settings.Gravity);
			parameters["EndVelocity"].SetValue(settings.EndVelocity);
			parameters["MinColor"].SetValue(settings.MinColor.ToVector4());
			parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4());

			parameters["RotateSpeed"].SetValue(
				new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed));

			parameters["StartSize"].SetValue(
				new Vector2(settings.MinStartSize, settings.MaxStartSize));

			parameters["EndSize"].SetValue(
				new Vector2(settings.MinEndSize, settings.MaxEndSize));

			// Look up shortcuts for parameters that change every frame.
			effectViewParameter = parameters["View"];
			effectProjectionParameter = parameters["Projection"];
			effectViewportScaleParameter = parameters["ViewportScale"];
			effectTimeParameter = parameters["CurrentTime"];
			effectMinColorParameter = parameters["MinColor"];
			effectMaxColorParameter = parameters["MaxColor"];

			// Load the particle texture, and set it onto the effect.
			Texture2D texture = content.Load<Texture2D>(settings.TexturePath);

			parameters["Texture"].SetValue(texture);
		}

		#endregion

		#region Update and Draw

		/// <summary>
		/// Updates the particle system.
		/// </summary>
		public override void Update(GameTime gameTime)
		{
			if (gameTime == null)
				throw new ArgumentNullException("gameTime");

			currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

			RetireActiveParticles();
			FreeRetiredParticles();

			// If we let our timer go on increasing for ever, it would eventually
			// run out of floating point precision, at which point the particles
			// would render incorrectly. An easy way to prevent this is to notice
			// that the time value doesn't matter when no particles are being drawn,
			// so we can reset it back to zero any time the active queue is empty.

			if (firstActiveParticle == firstFreeParticle)
				currentTime = 0;

			if (firstRetiredParticle == firstActiveParticle)
				drawCounter = 0;
		}

		/// <summary>
		/// Helper for checking when active particles have reached the end of
		/// their life. It moves old particles from the active area of the queue
		/// to the retired section.
		/// </summary>
		void RetireActiveParticles()
		{
			float particleDuration = (float)settings.Duration.TotalSeconds;

			while (firstActiveParticle != firstNewParticle)
			{
				// Is this particle old enough to retire?
				// We multiply the active particle index by four, because each
				// particle consists of a quad that is made up of four vertices.
				float particleAge = currentTime - particles[firstActiveParticle * 4].Time;

				if (particleAge < particleDuration)
					break;

				// Remember the time at which we retired this particle.
				particles[firstActiveParticle * 4].Time = drawCounter;

				// Move the particle from the active to the retired queue.
				firstActiveParticle++;

				if (firstActiveParticle >= settings.MaxParticles)
					firstActiveParticle = 0;
			}
		}

		/// <summary>
		/// Helper for checking when retired particles have been kept around long
		/// enough that we can be sure the GPU is no longer using them. It moves
		/// old particles from the retired area of the queue to the free section.
		/// </summary>
		void FreeRetiredParticles()
		{
			while (firstRetiredParticle != firstActiveParticle)
			{
				// Has this particle been unused long enough that
				// the GPU is sure to be finished with it?
				// We multiply the retired particle index by four, because each
				// particle consists of a quad that is made up of four vertices.
				int age = drawCounter - (int)particles[firstRetiredParticle * 4].Time;

				// The GPU is never supposed to get more than 2 frames behind the CPU.
				// We add 1 to that, just to be safe in case of buggy drivers that
				// might bend the rules and let the GPU get further behind.
				if (age < 3)
					break;

				// Move the particle from the retired to the free queue.
				firstRetiredParticle++;

				if (firstRetiredParticle >= settings.MaxParticles)
					firstRetiredParticle = 0;
			}
		}

		/// <summary>
		/// Draws the particle system.
		/// </summary>
		public override void Draw(GameTime gameTime)
		{
			GraphicsDevice device = GraphicsDevice;

			// Restore the vertex buffer contents if the graphics device was lost.
			if (vertexBuffer.IsContentLost)
			{
				vertexBuffer.SetData(particles);
			}

			// If there are any particles waiting in the newly added queue,
			// we'd better upload them to the GPU ready for drawing.
			if (firstNewParticle != firstFreeParticle)
			{
				AddNewParticlesToVertexBuffer();
			}

			// If there are any active particles, draw them now!
			if (firstActiveParticle != firstFreeParticle)
			{
				device.BlendState = settings.BlendState;
				device.DepthStencilState = DepthStencilState.DepthRead;

				// Set an effect parameter describing the viewport frameSize. This is
				// needed to convert particle sizes into screen space point sizes.
				effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f));

				// Set an effect parameter describing the current time. All the vertex
				// shader particle animation is keyed off this value.
				effectTimeParameter.SetValue(currentTime);

				// Set the particle vertex and index buffer.
				device.SetVertexBuffer(vertexBuffer);
				device.Indices = indexBuffer;

				// Wait until particle effect parameters aren't updated.
				lock (settingNewParameterLocker) { }

				// Activate the particle effect.
				foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes)
				{
					pass.Apply();

					if (firstActiveParticle < firstFreeParticle)
					{
						// If the active particles are all in one consecutive range,
						// we can draw them all in a single call.
						device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
													 firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4,
													 firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2);
					}
					else
					{
						// If the active particle range wraps past the end of the queue
						// back to the start, we must split them over two draw calls.
						device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
													 firstActiveParticle * 4, (settings.MaxParticles - firstActiveParticle) * 4,
													 firstActiveParticle * 6, (settings.MaxParticles - firstActiveParticle) * 2);

						if (firstFreeParticle > 0)
						{
							device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
														 0, firstFreeParticle * 4,
														 0, firstFreeParticle * 2);
						}
					}
				}

				// Reset some of the renderstates that we changed,
				// so as not to mess up any other subsequent drawing.
				device.DepthStencilState = DepthStencilState.Default;
			}

			drawCounter++;
		}

		/// <summary>
		/// Helper for uploading new particles from our managed
		/// array to the GPU vertex buffer.
		/// </summary>
		void AddNewParticlesToVertexBuffer()
		{
			int stride = ParticleVertex.SizeInBytes;

			if (firstNewParticle < firstFreeParticle)
			{
				// If the new particles are all in one consecutive range,
				// we can upload them all in a single call.
				vertexBuffer.SetData(firstNewParticle * stride * 4, particles,
									 firstNewParticle * 4,
									 (firstFreeParticle - firstNewParticle) * 4,
									 stride, SetDataOptions.NoOverwrite);
			}
			else
			{
				// If the new particle range wraps past the end of the queue
				// back to the start, we must split them over two upload calls.
				vertexBuffer.SetData(firstNewParticle * stride * 4, particles,
									 firstNewParticle * 4,
									 (settings.MaxParticles - firstNewParticle) * 4,
									 stride, SetDataOptions.NoOverwrite);

				if (firstFreeParticle > 0)
				{
					vertexBuffer.SetData(0, particles,
										 0, firstFreeParticle * 4,
										 stride, SetDataOptions.NoOverwrite);
				}
			}

			// Move the particles we just uploaded from the new to the active queue.
			firstNewParticle = firstFreeParticle;
		}

		#endregion

		#region Public Methods

		/// <summary>
		/// Sets the camera view and projection matrices
		/// that will be used to draw this particle system.
		/// </summary>
		public void SetCamera(Matrix view, Matrix projection)
		{
			effectViewParameter.SetValue(view);
			effectProjectionParameter.SetValue(projection);
		}

		public void SetMinColor(Color color)
		{
			if (effectMinColorParameter == null)
				settings.MinColor = color;
			else
				effectMinColorParameter.SetValue(color.ToVector4());
		}

		public void SetMaxColor(Color color)
		{
			if (effectMinColorParameter == null)
				settings.MaxColor = color;
			else
				effectMaxColorParameter.SetValue(color.ToVector4());
		}

		public Color GetMinColor()
		{
			if (effectMinColorParameter == null)
				return settings.MinColor;
			else
				return new Color(effectMinColorParameter.GetValueVector4());
		}

		public Color GetMaxColor()
		{
			if (effectMaxColorParameter == null)
				return settings.MaxColor;
			else
				return new Color(effectMaxColorParameter.GetValueVector4());
		}

		/// <summary>
		/// Adds a new particle to the system.
		/// </summary>
		public void AddParticle(Vector3 position, Vector3 velocity)
		{
			// Figure out where in the circular queue to allocate the new particle.
			int nextFreeParticle = firstFreeParticle + 1;

			if (nextFreeParticle >= settings.MaxParticles)
				nextFreeParticle = 0;

			// If there are no free particles, we just have to give up.
			if (nextFreeParticle == firstRetiredParticle)
				return;

			// Adjust the input velocity based on how much
			// this particle system wants to be affected by it.
			velocity *= settings.EmitterVelocitySensitivity;

			// Add in some random amount of horizontal velocity.
			float horizontalVelocity = MathHelper.Lerp(settings.MinHorizontalVelocity,
													   settings.MaxHorizontalVelocity,
													   (float)random.NextDouble());

			double horizontalAngle = random.NextDouble() * MathHelper.TwoPi;

			velocity.X += horizontalVelocity * (float)Math.Cos(horizontalAngle);
			velocity.Z += horizontalVelocity * (float)Math.Sin(horizontalAngle);

			// Add in some random amount of vertical velocity.
			velocity.Y += MathHelper.Lerp(settings.MinVerticalVelocity,
										  settings.MaxVerticalVelocity,
										  (float)random.NextDouble());

			// Choose four random control values. These will be used by the vertex
			// shader to give each particle a different frameSize, rotation, and color.
			Color randomValues = new Color((byte)random.Next(255),
										   (byte)random.Next(255),
										   (byte)random.Next(255),
										   (byte)random.Next(255));

			// Fill in the particle vertex structure.
			for (int i = 0; i < 4; i++)
			{
				particles[firstFreeParticle * 4 + i].Position = position;
				particles[firstFreeParticle * 4 + i].Velocity = velocity;
				particles[firstFreeParticle * 4 + i].Random = randomValues;
				particles[firstFreeParticle * 4 + i].Time = currentTime;
			}

			firstFreeParticle = nextFreeParticle;
		}

		#endregion
	}
}


text:
<?php

namespace DvsaEntitiesTest\Entity;

use DvsaEntities\Entity\Configuration;

/**
 * Class ConfigurationTest.
 */
class ConfigurationTest extends \PHPUnit\Framework\TestCase
{
    public function testInitialState()
    {
        $configuration = new Configuration();
        $this->assertNull($configuration->getKey());
        $this->assertNull($configuration->getValue());
    }

    public function testSetsPropertiesCorrectly()
    {
        $data = [
            'key' => 'thekey',
            'value' => 'thevalue',
        ];

        $configuration = new Configuration();
        $configuration->setKey($data['key'])
            ->setValue($data['value']);

        $this->assertEquals($data['key'], $configuration->getKey());
        $this->assertEquals($data['value'], $configuration->getValue());
    }
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
function triggerEvent(elem, eventName, eventType) {
    var event = document.createEvent(eventType);
    event.initEvent(eventName, true, true);
    elem.dispatchEvent(event);
}
exports.triggerEvent = triggerEvent;
var BlogComponent = (function () {
    function BlogComponent() {
        this.dragOne = new core_1.EventEmitter();
        this.dragTwo = new core_1.EventEmitter();
        this.dragOneTwo = new core_1.EventEmitter();
        this.dropOne = new core_1.EventEmitter();
        this.dropTwo = new core_1.EventEmitter();
        this.dropOneTwo = new core_1.EventEmitter();
    }
    // tslint:disable-next-line
    BlogComponent.prototype.dragOneSuccessCallback = function ($event) {
        console.log('dragOneSuccessCallback');
        this.dragOne.emit($event);
    };
    // tslint:disable-next-line
    BlogComponent.prototype.dragTwoSuccessCallback = function ($event) {
        console.log('dragTwoSuccessCallback');
        this.dragOne.emit($event);
    };
    // tslint:disable-next-line
    BlogComponent.prototype.dragOneTwoSuccessCallback = function ($event) {
        console.log('dragOneTwoSuccessCallback');
        this.dragOneTwo.emit($event);
    };
    // tslint:disable-next-line
    BlogComponent.prototype.dropOneSuccessCallback = function ($event) {
        console.log('dropOneSuccessCallback');
        this.dropOne.emit($event);
    };
    // tslint:disable-next-line
    BlogComponent.prototype.dropTwoSuccessCallback = function ($event) {
        console.log('dropTwoSuccessCallback');
        this.dropTwo.emit($event);
    };
    // tslint:disable-next-line
    BlogComponent.prototype.dropOneTwoSuccessCallback = function ($event) {
        console.log('dropOneTwoSuccessCallback');
        this.dropOneTwo.emit($event);
    };
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], BlogComponent.prototype, "dragOne", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], BlogComponent.prototype, "dragTwo", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], BlogComponent.prototype, "dragOneTwo", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], BlogComponent.prototype, "dropOne", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], BlogComponent.prototype, "dropTwo", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], BlogComponent.prototype, "dropOneTwo", void 0);
    BlogComponent = __decorate([
        core_1.Component({
            // selector: 'container',
            templateUrl: 'app/blog/blog-component.html'
        }),
        __metadata('design:paramtypes', [])
    ], BlogComponent);
    return BlogComponent;
}());
exports.BlogComponent = BlogComponent;
//# sourceMappingURL=blog.component.js.map


text:
class CreateDictionaries < ActiveRecord::Migration
  def change
    create_table :dictionaries do |t|
      t.string :name
      t.text :config
      t.string :config_md5
      t.timestamps :null => false
    end
  end
end


text:
<?php

namespace App\Http\Requests\Book;

use App\Http\Requests\Request;
use Illuminate\Contracts\Validation\Validator;

/**
 * Class UserCreateRequest
 *
 * @package App\Http\Requests\User
 */
class BookCreateRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Declaration an attributes
     *
     * @var array
     */
    protected $attrs = [
        'kode_buku'    => 'Kode buku',
        'judul'   => 'Judul',
        'pengarang' => 'Pengarang',
    ];

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'kode_buku'    => 'required|max:225',
            'judul'   => 'required|max:225',
            'pengarang' => 'required|max:60',
        ];
    }

    /**
     * @param $validator
     *
     * @return mixed
     */
    public function validator($validator)
    {
        return $validator->make($this->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attrs);
    }

}


text:
package gov.nist.javax.sip.parser.ims;

public class SecurityServerParser
  extends SecurityAgreeParser{
  // Constructors

  public SecurityServerParser(java.lang.String arg1){
    super((java.lang.String) null);
  }
  protected SecurityServerParser(gov.nist.javax.sip.parser.Lexer arg1){
    super((java.lang.String) null);
  }
  // Methods

  public gov.nist.javax.sip.header.SIPHeader parse() throws java.text.ParseException{
    return (gov.nist.javax.sip.header.SIPHeader) null;
  }
}