text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
    switch (arguments.length) {
        case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
        case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
        case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
    }
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var di_1 = require('angular2/di');
var lang_1 = require('angular2/src/facade/lang');
var collection_1 = require('angular2/src/facade/collection');
var ComponentUrlMapper = (function () {
    function ComponentUrlMapper() {
    }
    // Returns the base URL to the component source file.
    // The returned URL could be:
    // - an absolute URL,
    // - a path relative to the application
    ComponentUrlMapper.prototype.getUrl = function (component) { return './'; };
    ComponentUrlMapper = __decorate([
        di_1.Injectable(),
        __metadata('design:paramtypes', [])
    ], ComponentUrlMapper);
    return ComponentUrlMapper;
})();
exports.ComponentUrlMapper = ComponentUrlMapper;
var RuntimeComponentUrlMapper = (function (_super) {
    __extends(RuntimeComponentUrlMapper, _super);
    function RuntimeComponentUrlMapper() {
        _super.call(this);
        this._componentUrls = collection_1.MapWrapper.create();
    }
    RuntimeComponentUrlMapper.prototype.setComponentUrl = function (component, url) {
        collection_1.MapWrapper.set(this._componentUrls, component, url);
    };
    RuntimeComponentUrlMapper.prototype.getUrl = function (component) {
        var url = collection_1.MapWrapper.get(this._componentUrls, component);
        if (lang_1.isPresent(url))
            return url;
        return _super.prototype.getUrl.call(this, component);
    };
    return RuntimeComponentUrlMapper;
})(ComponentUrlMapper);
exports.RuntimeComponentUrlMapper = RuntimeComponentUrlMapper;
exports.__esModule = true;
//# sourceMappingURL=component_url_mapper.js.map


text:
package eu.arkitech.logback.amqp.accessors;

import com.google.common.base.Objects;
import eu.arkitech.logback.common.Callbacks;

public class AmqpRawConsumerConfiguration
		extends AmqpRawAccessorConfiguration
{
	public AmqpRawConsumerConfiguration ()
	{
		this (null, null, null, null, null, null, null, null, null, null);
	}

	public AmqpRawConsumerConfiguration (final AmqpRawConsumerConfiguration override, final AmqpRawConsumerConfiguration overriden)
	{
		super (override, overriden);
		this.exchange = Objects.firstNonNull (override.exchange, overriden.exchange);
		this.queue = Objects.firstNonNull (override.queue, overriden.queue);
		this.routingKey = Objects.firstNonNull (override.routingKey, overriden.routingKey);
	}

	public AmqpRawConsumerConfiguration (final String host, final Integer port, final String virtualHost, final String username, final String password, final String exchange, final String queue, final String routingKey, final Callbacks callbacks, final Object monitor)
	{
		super (host, port, virtualHost, username, password, callbacks, monitor);
		this.exchange = exchange;
		this.queue = queue;
		this.routingKey = routingKey;
	}

	public final String exchange;
	public final String queue;
	public final String routingKey;
	public static final String defaultExchange = "logging";
	public static final String defaultRoutingKey = "#";
}

redpajama_set_name: RedPajamaGithub


text:
@class OA2AccessGrant;
@class GHSignUpForm;

@interface GHAuthController : NSObject

+ (GHAuthController *)sharedInstance;
+ (BOOL)isAuthorized;
+ (BOOL)storeAccessGrant:(OA2AccessGrant *)accessGrant;
+ (OA2AccessGrant *)fetchAccessGrant;
+ (BOOL)deleteAccessGrant;

- (void)sendRequestToSignIn:(NSString *)username password:(NSString *)password delegate:(id<GHAuthControllerDelegate>)delegate;
- (void)sendRequestToSignUp:(GHSignUpForm *)signUpForm delegate:(id<GHAuthControllerDelegate>)delegate;

@end


text:
#ifndef __UOBJECT_H__
#define __UOBJECT_H__

#include "utypes.h"

/**
 * \file
 * \brief C++ API: Common ICU base class UObject.
 */

/**
 * @{
 * \def U_NO_THROW
 *         Define this to define the throw() specification so
 *                 certain functions do not throw any exceptions
 *
 *         UMemory operator new methods should have the throw() specification
 *         appended to them, so that the compiler adds the additional NULL check
 *         before calling constructors. Without, if operator new returns NULL the
 *         constructor is still called, and if the constructor references member
 *         data, (which it typically does), the result is a segmentation violation.
 *
 * @stable ICU 4.2
 */
#ifndef U_NO_THROW
#define U_NO_THROW throw()
#endif

/** @} */

/*===========================================================================*/
/* UClassID-based RTTI */
/*===========================================================================*/

/**
 * UClassID is used to identify classes without using the compiler's RTTI.
 * This was used before C++ compilers consistently supported RTTI.
 * ICU 4.6 requires compiler RTTI to be turned on.
 *
 * Each class hierarchy which needs
 * to implement polymorphic clone() or operator==() defines two methods,
 * described in detail below.  UClassID values can be compared using
 * operator==(). Nothing else should be done with them.
 *
 * \par
 * getDynamicClassID() is declared in the base class of the hierarchy as
 * a pure virtual.  Each concrete subclass implements it in the same way:
 *
 * \code
 *      class Base {
 *      public:
 *          virtual UClassID getDynamicClassID() const = 0;
 *      }
 *
 *      class Derived {
 *      public:
 *          virtual UClassID getDynamicClassID() const
 *            { return Derived::getStaticClassID(); }
 *      }
 * \endcode
 *
 * Each concrete class implements getStaticClassID() as well, which allows
 * clients to test for a specific type.
 *
 * \code
 *      class Derived {
 *      public:
 *          static UClassID U_EXPORT2 getStaticClassID();
 *      private:
 *          static char fgClassID;
 *      }
 *
 *      // In Derived.cpp:
 *      UClassID Derived::getStaticClassID()
 *        { return (UClassID)&Derived::fgClassID; }
 *      char Derived::fgClassID = 0; // Value is irrelevant
 * \endcode
 * @stable ICU 2.0
 */
typedef void* UClassID;

U_NAMESPACE_BEGIN

/**
 * UMemory is the common ICU base class.
 * All other ICU C++ classes are derived from UMemory (starting with ICU 2.4).
 *
 * This is primarily to make it possible and simple to override the
 * C++ memory management by adding new/delete operators to this base class.
 *
 * To override ALL ICU memory management, including that from plain C code,
 * replace the allocation functions declared in cmemory.h
 *
 * UMemory does not contain any virtual functions.
 * Common "boilerplate" functions are defined in UObject.
 *
 * @stable ICU 2.4
 */
class U_COMMON_API UMemory {
public:

/* test versions for debugging shaper heap memory problems */
#ifdef SHAPER_MEMORY_DEBUG
    static void * NewArray(int size, int count);
    static void * GrowArray(void * array, int newSize );
    static void   FreeArray(void * array );
#endif

#if U_OVERRIDE_CXX_ALLOCATION
    /**
     * Override for ICU4C C++ memory management.
     * simple, non-class types are allocated using the macros in common/cmemory.h
     * (uprv_malloc(), uprv_free(), uprv_realloc());
     * they or something else could be used here to implement C++ new/delete
     * for ICU4C C++ classes
     * @stable ICU 2.4
     */
    static void * U_EXPORT2 operator new(size_t size) U_NO_THROW;

    /**
     * Override for ICU4C C++ memory management.
     * See new().
     * @stable ICU 2.4
     */
    static void * U_EXPORT2 operator new[](size_t size) U_NO_THROW;

    /**
     * Override for ICU4C C++ memory management.
     * simple, non-class types are allocated using the macros in common/cmemory.h
     * (uprv_malloc(), uprv_free(), uprv_realloc());
     * they or something else could be used here to implement C++ new/delete
     * for ICU4C C++ classes
     * @stable ICU 2.4
     */
    static void U_EXPORT2 operator delete(void *p) U_NO_THROW;

    /**
     * Override for ICU4C C++ memory management.
     * See delete().
     * @stable ICU 2.4
     */
    static void U_EXPORT2 operator delete[](void *p) U_NO_THROW;

#if U_HAVE_PLACEMENT_NEW
    /**
     * Override for ICU4C C++ memory management for STL.
     * See new().
     * @stable ICU 2.6
     */
    static inline void * U_EXPORT2 operator new(size_t, void *ptr) U_NO_THROW { return ptr; }

    /**
     * Override for ICU4C C++ memory management for STL.
     * See delete().
     * @stable ICU 2.6
     */
    static inline void U_EXPORT2 operator delete(void *, void *) U_NO_THROW {}
#endif /* U_HAVE_PLACEMENT_NEW */
#if U_HAVE_DEBUG_LOCATION_NEW
    /**
      * This method overrides the MFC debug version of the operator new
      *
      * @param size   The requested memory size
      * @param file   The file where the allocation was requested
      * @param line   The line where the allocation was requested
      */
    static void * U_EXPORT2 operator new(size_t size, const char* file, int line) U_NO_THROW;
    /**
      * This method provides a matching delete for the MFC debug new
      *
      * @param p      The pointer to the allocated memory
      * @param file   The file where the allocation was requested
      * @param line   The line where the allocation was requested
      */
    static void U_EXPORT2 operator delete(void* p, const char* file, int line) U_NO_THROW;
#endif /* U_HAVE_DEBUG_LOCATION_NEW */
#endif /* U_OVERRIDE_CXX_ALLOCATION */

    /*
     * Assignment operator not declared. The compiler will provide one
     * which does nothing since this class does not contain any data members.
     * API/code coverage may show the assignment operator as present and
     * untested - ignore.
     * Subclasses need this assignment operator if they use compiler-provided
     * assignment operators of their own. An alternative to not declaring one
     * here would be to declare and empty-implement a protected or public one.
    UMemory &UMemory::operator=(const UMemory &);
     */
};

/**
 * UObject is the common ICU "boilerplate" class.
 * UObject inherits UMemory (starting with ICU 2.4),
 * and all other public ICU C++ classes
 * are derived from UObject (starting with ICU 2.2).
 *
 * UObject contains common virtual functions like for ICU's "poor man's RTTI".
 * It does not contain default implementations of virtual methods
 * like getDynamicClassID to allow derived classes such as Format
 * to declare these as pure virtual.
 *
 * The clone() function is not available in UObject because it is not
 * implemented by all ICU classes.
 * Many ICU services provide a clone() function for their class trees,
 * defined on the service's C++ base class, and all subclasses within that
 * service class tree return a pointer to the service base class
 * (which itself is a subclass of UObject).
 * This is because some compilers do not support covariant (same-as-this)
 * return types; cast to the appropriate subclass if necessary.
 *
 * @stable ICU 2.2
 */
class U_COMMON_API UObject : public UMemory {
public:
    /**
     * Destructor.
     *
     * @stable ICU 2.2
     */
    virtual ~UObject();

    /**
     * ICU4C "poor man's RTTI", returns a UClassID for the actual ICU class.
     *
     * @stable ICU 2.2
     */
    virtual UClassID getDynamicClassID() const;  // Android patch: tiny part of ICU 51's r32776

protected:
    // the following functions are protected to prevent instantiation and
    // direct use of UObject itself

    // default constructor
    // commented out because UObject is abstract (see getDynamicClassID)
    // inline UObject() {}

    // copy constructor
    // commented out because UObject is abstract (see getDynamicClassID)
    // inline UObject(const UObject &other) {}

#if 0
    // TODO Sometime in the future. Implement operator==().
    // (This comment inserted in 2.2)
    // some or all of the following "boilerplate" functions may be made public
    // in a future ICU4C release when all subclasses implement them

    // assignment operator
    // (not virtual, see "Taligent's Guide to Designing Programs" pp.73..74)
    // commented out because the implementation is the same as a compiler's default
    // UObject &operator=(const UObject &other) { return *this; }

    // comparison operators
    virtual inline UBool operator==(const UObject &other) const { return this==&other; }
    inline UBool operator!=(const UObject &other) const { return !operator==(other); }

    // clone() commented out from the base class:
    // some compilers do not support co-variant return types
    // (i.e., subclasses would have to return UObject * as well, instead of SubClass *)
    // see also UObject class documentation.
    // virtual UObject *clone() const;
#endif

    /*
     * Assignment operator not declared. The compiler will provide one
     * which does nothing since this class does not contain any data members.
     * API/code coverage may show the assignment operator as present and
     * untested - ignore.
     * Subclasses need this assignment operator if they use compiler-provided
     * assignment operators of their own. An alternative to not declaring one
     * here would be to declare and empty-implement a protected or public one.
    UObject &UObject::operator=(const UObject &);
     */

// Future implementation for RTTI that support subtyping. [alan]
//
//  public:
//     /**
//      * @internal
//      */
//     static UClassID getStaticClassID();
//
//     /**
//      * @internal
//      */
//     UBool instanceOf(UClassID type) const;
};

#ifndef U_HIDE_INTERNAL_API
/**
 * This is a simple macro to add ICU RTTI to an ICU object implementation.
 * This does not go into the header. This should only be used in *.cpp files.
 *
 * @param myClass The name of the class that needs RTTI defined.
 * @internal
 */
#define UOBJECT_DEFINE_RTTI_IMPLEMENTATION(myClass) \
    UClassID U_EXPORT2 myClass::getStaticClassID() { \
        static char classID = 0; \
        return (UClassID)&classID; \
    } \
    UClassID myClass::getDynamicClassID() const \
    { return myClass::getStaticClassID(); }

/**
 * This macro adds ICU RTTI to an ICU abstract class implementation.
 * This macro should be invoked in *.cpp files.  The corresponding
 * header should declare getStaticClassID.
 *
 * @param myClass The name of the class that needs RTTI defined.
 * @internal
 */
#define UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(myClass) \
    UClassID U_EXPORT2 myClass::getStaticClassID() { \
        static char classID = 0; \
        return (UClassID)&classID; \
    }

/**
 * This is a simple macro to express that a class and its subclasses do not offer
 * ICU's "poor man's RTTI".
 * Beginning with ICU 4.6, ICU requires C++ compiler RTTI.
 * This does not go into the header. This should only be used in *.cpp files.
 * Use this with a private getDynamicClassID() in an immediate subclass of UObject.
 *
 * @param myClass The name of the class that needs RTTI defined.
 * @internal
 */
#define UOBJECT_DEFINE_NO_RTTI_IMPLEMENTATION(myClass) \
    UClassID myClass::getDynamicClassID() const { return NULL; }

// /**
//  * This macro adds ICU RTTI to an ICU concrete class implementation.
//  * This macro should be invoked in *.cpp files.  The corresponding
//  * header should declare getDynamicClassID and getStaticClassID.
//  *
//  * @param myClass The name of the class that needs RTTI defined.
//  * @param myParent The name of the myClass's parent.
//  * @internal
//  */
/*#define UOBJECT_DEFINE_RTTI_IMPLEMENTATION(myClass, myParent) \
    UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(myClass, myParent) \
    UClassID myClass::getDynamicClassID() const { \
        return myClass::getStaticClassID(); \
    }
*/
#endif  /* U_HIDE_INTERNAL_API */

U_NAMESPACE_END

#endif


text:
<?php

namespace Elcodi\Fixtures\DataFixtures\ORM\Zone;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

use Elcodi\Bundle\CoreBundle\DataFixtures\ORM\Abstracts\AbstractFixture;
use Elcodi\Component\Core\Services\ObjectDirector;

/**
 * Class ZoneData
 */
class ZoneData extends AbstractFixture
{
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        /**
         * @var ObjectDirector $zoneDirector
         */
        $zones = $this->parseYaml(dirname(__FILE__) . '/zones.yml');
        $zoneDirector = $this->getDirector('zone');
        $zoneCollection = new ArrayCollection();

        foreach ($zones as $zoneName => $locations) {
            $zoneCode = strtolower(trim(preg_replace('~[^a-zA-Z\d]{1}~', '', $zoneName)));
            $zone = $zoneDirector
                ->create()
                ->setName($zoneName)
                ->setCode($zoneCode)
                ->setLocations($locations);

            $zoneCollection->add($zone);
            $this->setReference('zone-' . $zoneCode, $zone);
            $zoneDirector->save($zone);
        }

        $this->setReference('zone-collection', $zoneCollection);
    }
}


text:
namespace Poco {
namespace JS {
namespace Core {

class JSCore_API ConsoleWrapper: public Wrapper
	/// JavaScript wrapper for Poco::Logger, presenting
	/// a Console-style interface as known from web browsers.
{
public:
	ConsoleWrapper();
		/// Creates the ConsoleWrapper for the root logger.

	~ConsoleWrapper();
		/// Destroys the ConsoleWrapper.

	// Wrapper
	v8::Handle<v8::ObjectTemplate> objectTemplate(v8::Isolate* pIsolate);

protected:
	static void trace(const v8::FunctionCallbackInfo<v8::Value>& args);
	static void assert(const v8::FunctionCallbackInfo<v8::Value>& args);
	static void log(const v8::FunctionCallbackInfo<v8::Value>& args);
	static void debug(const v8::FunctionCallbackInfo<v8::Value>& args);
	static void info(const v8::FunctionCallbackInfo<v8::Value>& args);
	static void error(const v8::FunctionCallbackInfo<v8::Value>& args);
	static void warn(const v8::FunctionCallbackInfo<v8::Value>& args);
};

} } } // namespace Poco::JS::Core

#endif // JS_Core_ConsoleWrapper_INCLUDED


text:
namespace app { namespace Fuse { namespace Animations { struct Change__Fuse_Triggers_StateTransition; } } }
namespace app { namespace Fuse { namespace Animations { struct CreateStateParams; } } }

namespace app {
namespace Fuse {
namespace Animations {

struct DiscreteTrackChangeState__Fuse_Triggers_StateTransition;

struct DiscreteTrackChangeState__Fuse_Triggers_StateTransition__uType : ::app::Fuse::Animations::TrackAnimatorState__uType
{
};

DiscreteTrackChangeState__Fuse_Triggers_StateTransition__uType* DiscreteTrackChangeState__Fuse_Triggers_StateTransition__typeof();

void DiscreteTrackChangeState__Fuse_Triggers_StateTransition___ObjInit_2(DiscreteTrackChangeState__Fuse_Triggers_StateTransition* __this, ::app::Fuse::Animations::Change__Fuse_Triggers_StateTransition* animator, ::app::Fuse::Animations::CreateStateParams* p);
void DiscreteTrackChangeState__Fuse_Triggers_StateTransition__Disable(DiscreteTrackChangeState__Fuse_Triggers_StateTransition* __this);
DiscreteTrackChangeState__Fuse_Triggers_StateTransition* DiscreteTrackChangeState__Fuse_Triggers_StateTransition__New_1(::uStatic* __this, ::app::Fuse::Animations::Change__Fuse_Triggers_StateTransition* animator, ::app::Fuse::Animations::CreateStateParams* p);
void DiscreteTrackChangeState__Fuse_Triggers_StateTransition__SeekObjectValue(DiscreteTrackChangeState__Fuse_Triggers_StateTransition* __this, ::uObject* value, float strength);

struct DiscreteTrackChangeState__Fuse_Triggers_StateTransition : ::app::Fuse::Animations::TrackAnimatorState
{
    ::uStrong< ::uObject*> mixHandle;
    ::uStrong< ::app::Fuse::Animations::Change__Fuse_Triggers_StateTransition*> Animator_1;

    void _ObjInit_2(::app::Fuse::Animations::Change__Fuse_Triggers_StateTransition* animator, ::app::Fuse::Animations::CreateStateParams* p) { DiscreteTrackChangeState__Fuse_Triggers_StateTransition___ObjInit_2(this, animator, p); }
};

}}}

#endif


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.WebJobs.Extensions.ServiceBus.Config;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.Scale;
using Microsoft.Azure.WebJobs.Host.TestCommon;
using Microsoft.Azure.WebJobs.ServiceBus.Listeners;
using Microsoft.Azure.WebJobs.ServiceBus.Tests;
using Microsoft.Extensions.Azure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;

namespace Microsoft.Azure.WebJobs.ServiceBus.UnitTests.Listeners
{
    public class ServiceBusListenerTests
    {
        private readonly ServiceBusListener _listener;
        private readonly Mock<ITriggeredFunctionExecutor> _mockExecutor;
        private readonly Mock<MessagingProvider> _mockMessagingProvider;
        private readonly Mock<ServiceBusClientFactory> _mockClientFactory;
        private readonly Mock<MessageProcessor> _mockMessageProcessor;
        private readonly TestLoggerProvider _loggerProvider;
        private readonly LoggerFactory _loggerFactory;
        private readonly string _functionId = "test-functionid";
        private readonly string _entityPath = "test-entity-path";
        private readonly string _testConnection = "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=abc123=";
        private readonly Mock<IConcurrencyThrottleManager> _mockConcurrencyThrottleManager;
        private readonly ServiceBusClient _client;

        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock<ITriggeredFunctionExecutor>(MockBehavior.Strict);

            _client = new ServiceBusClient(_testConnection);
            ServiceBusProcessor processor = _client.CreateProcessor(_entityPath);
            ServiceBusReceiver receiver = _client.CreateReceiver(_entityPath);
            var configuration = ConfigurationUtilities.CreateConfiguration(new KeyValuePair<string, string>("connection", _testConnection));

            ServiceBusOptions config = new ServiceBusOptions
            {
                ExceptionHandler = ExceptionReceivedHandler
            };
            _mockMessageProcessor = new Mock<MessageProcessor>(MockBehavior.Strict, processor);

            _mockMessagingProvider = new Mock<MessagingProvider>(new OptionsWrapper<ServiceBusOptions>(config));
            _mockClientFactory = new Mock<ServiceBusClientFactory>(configuration, Mock.Of<AzureComponentFactory>(), _mockMessagingProvider.Object, new AzureEventSourceLogForwarder(new NullLoggerFactory()), new OptionsWrapper<ServiceBusOptions>(new ServiceBusOptions()));
            _mockMessagingProvider
                .Setup(p => p.CreateMessageProcessor(It.IsAny<ServiceBusClient>(), _entityPath, It.IsAny<ServiceBusProcessorOptions>()))
                .Returns(_mockMessageProcessor.Object);

            _mockMessagingProvider
                    .Setup(p => p.CreateBatchMessageReceiver(It.IsAny<ServiceBusClient>(), _entityPath, default))
                    .Returns(receiver);

            _loggerFactory = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            var concurrencyOptions = new OptionsWrapper<ConcurrencyOptions>(new ConcurrencyOptions());
            _mockConcurrencyThrottleManager = new Mock<IConcurrencyThrottleManager>(MockBehavior.Strict);
            var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, _mockConcurrencyThrottleManager.Object);

            _listener = new ServiceBusListener(
                _functionId,
                ServiceBusEntityType.Queue,
                _entityPath,
                false,
                config.AutoCompleteMessages,
                _mockExecutor.Object,
                config,
                "connection",
                _mockMessagingProvider.Object,
                _loggerFactory,
                false,
                _mockClientFactory.Object,
                concurrencyManager);
        }

        [Test]
        [Category("DynamicConcurrency")]
        public void ConcurrencyUpdateManager_UpdatesProcessorConcurrency()
        {
            var concurrencyOptions = new OptionsWrapper<ConcurrencyOptions>(new ConcurrencyOptions { DynamicConcurrencyEnabled = true });
            var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, _mockConcurrencyThrottleManager.Object);
            _mockConcurrencyThrottleManager.Setup(p => p.GetStatus()).Returns(new ConcurrencyThrottleAggregateStatus { State = ThrottleState.Disabled });
            ServiceBusProcessor processor = _client.CreateProcessor(_entityPath);
            Lazy<MessageProcessor> messageProcessor = new Lazy<MessageProcessor>(() => new MessageProcessor(processor));
            ILogger logger = _loggerFactory.CreateLogger("test");
            ServiceBusListener.ConcurrencyUpdateManager concurrencyUpdateManager = new ServiceBusListener.ConcurrencyUpdateManager(concurrencyManager, messageProcessor, null, false, _functionId, logger);

            // when no messages are being processed, concurrency is not adjusted
            Assert.AreEqual(1, processor.MaxConcurrentCalls);
            SetFunctionCurrentConcurrency(concurrencyManager, _functionId, 10);
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(1, processor.MaxConcurrentCalls);

            // ensure processor concurrency is adjusted up
            concurrencyUpdateManager.MessageProcessed();
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(10, processor.MaxConcurrentCalls);

            // ensure processor concurrency is adjusted down
            SetFunctionCurrentConcurrency(concurrencyManager, _functionId, 5);
            concurrencyUpdateManager.MessageProcessed();
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(5, processor.MaxConcurrentCalls);
        }

        [Test]
        [Category("DynamicConcurrency")]
        public void ConcurrencyUpdateManager_Sessions_UpdatesProcessorConcurrency()
        {
            var concurrencyOptions = new OptionsWrapper<ConcurrencyOptions>(new ConcurrencyOptions { DynamicConcurrencyEnabled = true });
            var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, _mockConcurrencyThrottleManager.Object);
            _mockConcurrencyThrottleManager.Setup(p => p.GetStatus()).Returns(new ConcurrencyThrottleAggregateStatus { State = ThrottleState.Disabled });
            ServiceBusSessionProcessor sessionProcessor = _client.CreateSessionProcessor(_entityPath, new ServiceBusSessionProcessorOptions { MaxConcurrentSessions = 1, MaxConcurrentCallsPerSession = 1 });
            Lazy<SessionMessageProcessor> sessionMessageProcessor = new Lazy<SessionMessageProcessor>(() => new SessionMessageProcessor(sessionProcessor));
            ILogger logger = _loggerFactory.CreateLogger("test");
            ServiceBusListener.ConcurrencyUpdateManager concurrencyUpdateManager = new ServiceBusListener.ConcurrencyUpdateManager(concurrencyManager, null, sessionMessageProcessor, true, _functionId, logger);

            // when no messages are being processed, concurrency is not adjusted
            Assert.AreEqual(1, sessionProcessor.MaxConcurrentSessions);
            Assert.AreEqual(1, sessionProcessor.MaxConcurrentCallsPerSession);
            SetFunctionCurrentConcurrency(concurrencyManager, _functionId, 10);
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(1, sessionProcessor.MaxConcurrentSessions);
            Assert.AreEqual(1, sessionProcessor.MaxConcurrentCallsPerSession);

            // ensure processor concurrency is adjusted up
            concurrencyUpdateManager.MessageProcessed();
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(10, sessionProcessor.MaxConcurrentSessions);
            Assert.AreEqual(1, sessionProcessor.MaxConcurrentCallsPerSession);

            // ensure processor concurrency is adjusted down
            SetFunctionCurrentConcurrency(concurrencyManager, _functionId, 5);
            concurrencyUpdateManager.MessageProcessed();
            concurrencyUpdateManager.UpdateConcurrency();
            Assert.AreEqual(5, sessionProcessor.MaxConcurrentSessions);
            Assert.AreEqual(1, sessionProcessor.MaxConcurrentCallsPerSession);
        }

        [Test]
        public async Task ProcessMessageAsync_Success()
        {
            var message = ServiceBusModelFactory.ServiceBusReceivedMessage(
                messageId: Guid.NewGuid().ToString(),
                sequenceNumber: 1,
                deliveryCount: 55,
                enqueuedTime: DateTimeOffset.Now,
                lockedUntil: DateTimeOffset.Now);
            var receiver = new Mock<ServiceBusReceiver>().Object;
            var args = new ProcessMessageEventArgs(message, receiver, CancellationToken.None);
            _mockMessageProcessor.Setup(p => p.BeginProcessingMessageAsync(It.IsAny<ServiceBusMessageActions>(), message, It.IsAny<CancellationToken>())).ReturnsAsync(true);

            FunctionResult result = new FunctionResult(true);
            _mockExecutor.Setup(p => p.TryExecuteAsync(It.Is<TriggeredFunctionData>(q => ((ServiceBusTriggerInput)q.TriggerValue).Messages[0] == message), It.IsAny<CancellationToken>())).ReturnsAsync(result);

            _mockMessageProcessor.Setup(p => p.CompleteProcessingMessageAsync(It.IsAny<ServiceBusMessageActions>(), message, result, It.IsAny<CancellationToken>())).Returns(Task.FromResult(0));

            await _listener.ProcessMessageAsync(args);

            _mockMessageProcessor.VerifyAll();
            _mockExecutor.VerifyAll();
            _mockMessageProcessor.VerifyAll();
        }

        [Test]
        public async Task ProcessMessageAsync_BeginProcessingReturnsFalse_MessageNotProcessed()
        {
            var message = ServiceBusModelFactory.ServiceBusReceivedMessage(messageId: Guid.NewGuid().ToString());
            var receiver = new Mock<ServiceBusReceiver>().Object;

            _mockMessageProcessor.Setup(p => p.BeginProcessingMessageAsync(
                It.IsAny<ServiceBusMessageActions>(),
                message,
                It.IsAny<CancellationToken>())).ReturnsAsync(false);
            var args = new ProcessMessageEventArgs(message, receiver, CancellationToken.None);

            await _listener.ProcessMessageAsync(args);

            _mockMessageProcessor.VerifyAll();
        }

        [Test]
        public void GetMonitor_ReturnsExpectedValue()
        {
            IScaleMonitor scaleMonitor = _listener.GetMonitor();

            Assert.AreEqual(typeof(ServiceBusScaleMonitor), scaleMonitor.GetType());
            Assert.AreEqual(scaleMonitor.Descriptor.Id, $"{_functionId}-ServiceBusTrigger-{_entityPath}".ToLower());

            var scaleMonitor2 = _listener.GetMonitor();

            Assert.AreSame(scaleMonitor, scaleMonitor2);
        }

        private Task ExceptionReceivedHandler(ProcessErrorEventArgs eventArgs)
        {
            return Task.CompletedTask;
        }

        private void SetFunctionCurrentConcurrency(ConcurrencyManager concurrencyManager, string functionId, int concurrency)
        {
            var concurrencyStatus = concurrencyManager.GetStatus(functionId);
            var propertyInfo = typeof(ConcurrencyStatus).GetProperty("CurrentConcurrency", BindingFlags.Instance | BindingFlags.Public);
            propertyInfo.SetValue(concurrencyStatus, concurrency);
        }
    }
}


text:
//////////////////// Includes /////////////////////////////////////////////////

#include "stdafx.h"
#include "AAPrecession.h"
#include <cmath>
using namespace std;

//////////////////// Implementation ///////////////////////////////////////////

CAA2DCoordinate CAAPrecession::AdjustPositionUsingUniformProperMotion(double t, double Alpha, double Delta, double PMAlpha, double PMDelta) noexcept
{
  CAA2DCoordinate value;
  value.X = CAACoordinateTransformation::MapTo0To24Range(Alpha + ((PMAlpha*t)/3600));
  value.Y = CAACoordinateTransformation::MapToMinus90To90Range(Delta + ((PMDelta*t)/3600));
  return value;
}

CAA2DCoordinate CAAPrecession::AdjustPositionUsingMotionInSpace(double r, double DeltaR, double t, double Alpha, double Delta, double PMAlpha, double PMDelta) noexcept
{
  //Convert DeltaR from km/s to Parsecs / Year
  DeltaR /= 977792;

  //Convert from seconds of time to Radians / Year
  PMAlpha /= 13751;

  //Convert from seconds of arc to Radians / Year
  PMDelta /= 206265;

  const double rDeltaR{r*DeltaR};

  //Now convert to radians
  Alpha = CAACoordinateTransformation::HoursToRadians(Alpha);
  const double cosAlpha{cos(Alpha)};
  const double sinAlpha{sin(Alpha)};
  Delta = CAACoordinateTransformation::DegreesToRadians(Delta);
  const double cosDelta{cos(Delta)};

  double x{r*cosDelta*cosAlpha};
  double y{r*cosDelta*sinAlpha};
  double z{r*sin(Delta)};

  const double DeltaX{(x/rDeltaR) - (z*PMDelta*cosAlpha) - (y*PMAlpha)};
  const double DeltaY{(y/rDeltaR) - (z*PMDelta*sinAlpha) + (x*PMAlpha)};
  const double DeltaZ{(z/rDeltaR) + (r*PMDelta*cosDelta)};

  x += t*DeltaX;
  y += t*DeltaY;
  z += t*DeltaZ;

  CAA2DCoordinate value;
  value.X = CAACoordinateTransformation::MapTo0To24Range(CAACoordinateTransformation::RadiansToHours(atan2(y, x)));
  value.Y = CAACoordinateTransformation::RadiansToDegrees(atan2(z, sqrt((x*x) + (y*y))));
  return value;
}

CAA2DCoordinate CAAPrecession::PrecessEquatorial(double Alpha, double Delta, double JD0, double JD) noexcept
{
  const double T{(JD0 - 2451545)/36525};
  const double Tsquared{T*T};
  const double t{(JD - JD0)/36525};
  const double tsquared{t*t};
  const double tcubed{tsquared*t};

  //Now convert to radians
  Alpha = CAACoordinateTransformation::HoursToRadians(Alpha);
  Delta = CAACoordinateTransformation::DegreesToRadians(Delta);
  const double cosDelta{cos(Delta)};
  const double sinDelta{sin(Delta)};

  const double sigma{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((2306.2181 + (1.39656*T) - (0.000139*Tsquared))*t) + ((0.30188 - (0.000344*T))*tsquared) + (0.017998*tcubed)))};
  const double zeta{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((2306.2181 + (1.39656*T) - (0.000139*Tsquared))*t) + ((1.09468 + (0.000066*T))*tsquared) + (0.018203*tcubed)))};
  const double phi{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((2004.3109 - (0.8533*T) - (0.000217*Tsquared))*t) - ((0.42665 + (0.000217*T))*tsquared) - (0.041833*tcubed)))};
  const double cosphi{cos(phi)};
  const double sinphi{sin(phi)};
  const double cosAlphaplussigma{cos(Alpha + sigma)};
  const double A{cosDelta*sin(Alpha + sigma)};
  const double B{(cosphi*cosDelta*cosAlphaplussigma) - (sinphi*sinDelta)};
  const double C{(sinphi*cosDelta*cosAlphaplussigma) + (cosphi * sinDelta)};

  CAA2DCoordinate value;
  value.X = CAACoordinateTransformation::MapTo0To24Range(CAACoordinateTransformation::RadiansToHours(atan2(A, B) + zeta));
  value.Y = CAACoordinateTransformation::RadiansToDegrees(asin(C));
  return value;
}

CAA2DCoordinate CAAPrecession::PrecessEquatorialFK4(double Alpha, double Delta, double JD0, double JD) noexcept
{
  const double T{(JD0 - 2415020.3135)/36524.2199};
  const double t{(JD - JD0)/36524.2199};
  const double tsquared{t*t};
  const double tcubed{tsquared*t};

  //Now convert to radians
  Alpha = CAACoordinateTransformation::HoursToRadians(Alpha);
  Delta = CAACoordinateTransformation::DegreesToRadians(Delta);
  const double cosDelta{cos(Delta)};
  const double sinDelta{sin(Delta)};

  const double sigma{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((2304.250 + (1.396*T))*t) + (0.302*tsquared) + (0.018*tcubed)))};
  const double zeta{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, (0.791*tsquared) + (0.001*tcubed))) + sigma};
  const double phi{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((2004.682 - (0.853*T))*t) - (0.426*tsquared) - (0.042*tcubed)))};
  const double cosphi{cos(phi)};
  const double sinphi{sin(phi)};
  const double cosAlphaplussigma{cos(Alpha + sigma)};
  const double A{cosDelta*sin(Alpha + sigma)};
  const double B{(cosphi*cosDelta*cosAlphaplussigma) - (sinphi*sinDelta)};
  const double C{(sinphi*cosDelta*cosAlphaplussigma) + (cosphi*sinDelta)};

  const double DeltaAlpha{CAACoordinateTransformation::DMSToDegrees(0, 0, 0.0775 + (0.0850*T))};
  CAA2DCoordinate value;
  value.X = CAACoordinateTransformation::MapTo0To24Range(CAACoordinateTransformation::RadiansToHours(atan2(A, B) + zeta) + DeltaAlpha);
  value.Y = CAACoordinateTransformation::RadiansToDegrees(asin(C));
  return value;
}

CAA2DCoordinate CAAPrecession::PrecessEcliptic(double Lambda, double Beta, double JD0, double JD) noexcept
{
  const double T{(JD0 - 2451545)/36525};
  const double Tsquared{T*T};
  const double t{(JD - JD0)/36525};
  const double tsquared{t*t};
  const double tcubed{tsquared*t};

  //Now convert to radians
  Lambda = CAACoordinateTransformation::DegreesToRadians(Lambda);
  Beta = CAACoordinateTransformation::DegreesToRadians(Beta);
  const double cosBeta{cos(Beta)};
  const double sinBeta{sin(Beta)};

  const double eta{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((47.0029 - (0.06603*T) + (0.000598*Tsquared))*t) + ((-0.03302 + (0.000598*T))*tsquared) + (0.00006*tcubed)))};
  const double coseta{cos(eta)};
  const double sineta{sin(eta)};
  const double pi{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, (174.876384*3600) + (3289.4789*T) + (0.60622*Tsquared) - ((869.8089 + (0.50491*T))*t) + (0.03536*tsquared)))};
  const double sinpiminusLambda{sin(pi - Lambda)};
  const double p{CAACoordinateTransformation::DegreesToRadians(CAACoordinateTransformation::DMSToDegrees(0, 0, ((5029.0966 + (2.22226*T) - (0.000042*Tsquared))*t) + ((1.11113 - (0.000042*T))*tsquared) - (0.000006*tcubed)))};
  const double A{(coseta*cosBeta*sinpiminusLambda) - (sineta*sinBeta)};
  const double B{cosBeta*cos(pi - Lambda)};
  const double C{(coseta*sinBeta) + (sineta*cosBeta*sinpiminusLambda)};

  CAA2DCoordinate value;
  value.X = CAACoordinateTransformation::MapTo0To360Range(CAACoordinateTransformation::RadiansToDegrees(p + pi - atan2(A, B)));
  value.Y = CAACoordinateTransformation::RadiansToDegrees(asin(C));
  return value;
}

CAA2DCoordinate CAAPrecession::EquatorialPMToEcliptic(double Alpha, double Delta, double Beta, double PMAlpha, double PMDelta, double Epsilon) noexcept
{
  //Convert to radians
  Epsilon = CAACoordinateTransformation::DegreesToRadians(Epsilon);
  const double sinEpsilon{sin(Epsilon)};
  const double cosEpsilon{cos(Epsilon)};
  Alpha = CAACoordinateTransformation::HoursToRadians(Alpha);
  const double cosAlpha{cos(Alpha)};
  const double sinAlpha{sin(Alpha)};
  Delta = CAACoordinateTransformation::DegreesToRadians(Delta);
  const double cosDelta{cos(Delta)};
  const double sinDelta{sin(Delta)};
  Beta = CAACoordinateTransformation::DegreesToRadians(Beta);
  const double cosBeta{cos(Beta)};

  CAA2DCoordinate value;
  value.X = ((PMDelta*sinEpsilon*cosAlpha) + (PMAlpha*cosDelta*((cosEpsilon*cosDelta) + (sinEpsilon*sinDelta*sinAlpha))))/(cosBeta*cosBeta);
  value.Y = (PMDelta*((cosEpsilon*cosDelta) + (sinEpsilon*sinDelta*sinAlpha)) - (PMAlpha*sinEpsilon*cosAlpha*cosDelta))/cosBeta;
  return value;
}


text:
<?php

namespace ekstazi\crud\params;

use yii\db\BaseActiveRecord;

class RedirectTo
{

    public static function byPk($route)
    {
        return function (BaseActiveRecord $model) use ($route) {
            $pk = $model->getPrimaryKey();
            if (is_array($pk))
                $route = $route + $pk;
            else
                $route['id'] = $pk;

            return $route;
        };
    }

    public static function callback($function)
    {
        return $function;
    }

    public static function route($route)
    {
        return $route;
    }

    public static function build($redirectTo, $model)
    {
        return (is_callable($redirectTo))
            ? call_user_func($redirectTo, $model)
            : $redirectTo;
    }
}


text:
package net.ssehub.easy.varModel.model.filter;

import net.ssehub.easy.varModel.model.AbstractProjectVisitor;
import net.ssehub.easy.varModel.model.Attribute;
import net.ssehub.easy.varModel.model.Comment;
import net.ssehub.easy.varModel.model.Constraint;
import net.ssehub.easy.varModel.model.FreezeBlock;
import net.ssehub.easy.varModel.model.OperationDefinition;
import net.ssehub.easy.varModel.model.PartialEvaluationBlock;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.ProjectInterface;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.DerivedDatatype;
import net.ssehub.easy.varModel.model.datatypes.Enum;
import net.ssehub.easy.varModel.model.datatypes.EnumLiteral;
import net.ssehub.easy.varModel.model.datatypes.OrderedEnum;
import net.ssehub.easy.varModel.model.datatypes.Reference;
import net.ssehub.easy.varModel.model.datatypes.Sequence;
import net.ssehub.easy.varModel.model.datatypes.Set;

/**
 * Abstract super class for finding all toplevel <tt>DecisionVariableDeclaration</tt>'s of a {@link Project}.
 * @author El-Sharkawy
 *
 */
abstract class AbstractDeclarationFinder extends AbstractProjectVisitor {

    /**
     * Sole constructor for this class.
     * @param project The project where the visiting shall start
     * @param filterType Specifies whether project imports shall be considered or not.
     */
    protected AbstractDeclarationFinder(Project project, FilterType filterType) {
        super(project, filterType);
    }

    @Override
    public void visitEnum(Enum eenum) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitOrderedEnum(OrderedEnum eenum) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitCompound(Compound compound) {
        // Not needed method, since this class should only find top-level DecisionVariableDeclarations
        // in case that also compounds shall be visited, please visit the attributeAssignments in compound
    }

    @Override
    public void visitDerivedDatatype(DerivedDatatype datatype) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitEnumLiteral(EnumLiteral literal) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitReference(Reference reference) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitSequence(Sequence sequence) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitSet(Set set) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitAttribute(Attribute attribute) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitConstraint(Constraint constraint) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitFreezeBlock(FreezeBlock freeze) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitOperationDefinition(OperationDefinition opdef) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitPartialEvaluationBlock(PartialEvaluationBlock block) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitProjectInterface(ProjectInterface iface) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }

    @Override
    public void visitComment(Comment comment) {
        // Not needed method, since this class should only find DecisionVariableDeclaration
    }
}


text:
require_relative '../../spec_helper'

describe Screp::Screp do

  describe "Parsing" do

    let :table do
      screp = Screp::Screp.new(silent: true)
      screp.scrape('spec/fixtures/table.html')
      screp
    end

    describe "#method_missing" do
      it "raises error if it or nokogiri doesn't handle the method" do
        expect {
          table.dummy_method
        }.to raise_error NoMethodError
      end
    end

    describe "#count" do
      it "finds the correct count" do
        table.count('tr').should == 3
      end
    end

    describe "#first" do
      it "finds the correct node" do
        table.first('td') do
          content.should == 'row1 col1'
        end
      end

      it "doesn't require a block" do
        table.first('td').content.should == 'row1 col1'
      end
    end

    describe "#last" do
      it "finds the correct node" do
        table.last 'td' do
          content.should == 'row3 col2'
        end
      end
      it "doesn't require a block" do
        table.last('td').content.should == 'row3 col2'
      end
    end

    describe "#each" do

      it "cycles through each node in order" do
        expected_content =
          ['row1 col1row1 col2',
            'row2 col1row2 col2',
            'row3 col1row3 col2']

        actual_content = []

        table.each 'tr' do
          actual_content << content.strip
        end

        actual_content.should == expected_content
      end

      it "passes correct indices" do
        expected_indices = [0,1,2]
        actual_indices = []

        table.each 'tr' do |row_index|
          actual_indices << row_index
        end

        actual_indices.should == expected_indices

      end

      it "can process a specified node" do
        expected_content =
          ['row2 col1row2 col2']

        actual_content = []

        table.each 'tr', 1 do
          actual_content << content.strip
        end

        actual_content.should == expected_content
      end

      it "can process a specified range" do

        expected_content =
          ['row1 col1row1 col2',
            'row2 col1row2 col2']
        actual_content = []

        table.each 'tr', 0..1 do
          actual_content << content.strip
        end

        actual_content.should == expected_content
      end

      it "can process an end range" do

        expected_content =
          ['row2 col1row2 col2',
            'row3 col1row3 col2']
        actual_content = []

        table.each 'tr', 1..-1 do
          actual_content << content.strip
        end

        actual_content.should == expected_content
      end

      it "is able to nest" do

        expected_content =
          ['row2 col1', 'row2 col2']

        actual_content = []

        table.each 'tr', 1 do
          each 'td' do
            actual_content << content.strip
          end
        end

        actual_content.should == expected_content
      end
    end

  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:width="0.8dp"
        android:height="0.8dp"/>
    <solid android:color="@color/divider_color" />
</shape>


text:
#if !defined( _${library_name_upper_case}_HUFFMAN_TREE_H )
#define _${library_name_upper_case}_HUFFMAN_TREE_H

#include <common.h>
#include <types.h>

#include "${library_name}_bit_stream.h"
#include "${library_name}_libcerror.h"

#if defined( __cplusplus )
extern "C" {
#endif

typedef struct ${library_name}_huffman_tree ${library_name}_huffman_tree_t;

struct ${library_name}_huffman_tree
{
	/* The maximum number of bits allowed for a Huffman code
	 */
	uint8_t maximum_code_size;

	/* The symbols array
	 */
	uint16_t *symbols;

	/* The code size counts array
	 */
	int *code_size_counts;
};

int ${library_name}_huffman_tree_initialize(
     ${library_name}_huffman_tree_t **huffman_tree,
     int number_of_symbols,
     uint8_t maximum_code_size,
     libcerror_error_t **error );

int ${library_name}_huffman_tree_free(
     ${library_name}_huffman_tree_t **huffman_tree,
     libcerror_error_t **error );

int ${library_name}_huffman_tree_build(
     ${library_name}_huffman_tree_t *huffman_tree,
     const uint8_t *code_sizes_array,
     int number_of_code_sizes,
     libcerror_error_t **error );

int ${library_name}_huffman_tree_get_symbol_from_bit_stream(
     ${library_name}_huffman_tree_t *huffman_tree,
     ${library_name}_bit_stream_t *bit_stream,
     uint16_t *symbol,
     libcerror_error_t **error );

#if defined( __cplusplus )
}
#endif

#endif /* !defined( _${library_name_upper_case}_HUFFMAN_TREE_H ) */


text:
This method is used to remove records from the database.  Define the type through the generic.

## Removing Records

In certain situations you may want to programmatically remove records from OrientDB.  Using the `Delete<T>()` method you can remove the instance as part of a transaction.

### Syntax

```
OTransaction.Delete<T>(T typedObject)
```
- **`typedObject`** Defines the object you want to remove.  The object must be of the same type as defined in the `T` generic.

### Example

For instance, say that you want to create a function for removing records from the database.

```csharp
public void removeDocument(OTransaction trx, ODocument document)
{
   // REMOVE RECORD
   trx.Delete<ODocument>(document);
}
```


text:
#ifndef __tcode_io_timer_h__
#define __tcode_io_timer_h__

#include <tcode/time/timespan.hpp>
#include <tcode/time/timestamp.hpp>
#include <tcode/function.hpp>
#include <atomic>

namespace tcode { namespace io {

    class engine;
	/*!
		@class timer
		@brief
	*/
    class timer {
    public:
        struct id;

		//! ctor
        timer( io::engine& e );

		//! dtor
        ~timer( void );

		//! relative callback time now() + ts
        timer& due_time( const tcode::timespan& ts );
		//! absolute callback time
        timer& due_time( const tcode::timestamp& ts );
		//! repeat tick if 0 call once
        timer& repeat( const tcode::timespan& ts );
		//! callback function
        timer& callback( const tcode::function<void (const std::error_code& ) >& cb );

		//! fire timer
        void fire( void );
		//! cancel timer
        void cancel( void );
    private:
        timer::id* _id;
    };

}}

#endif


text:
```swift
extension Array where Element: Comparable {
  mutating func quickSort() {
    quickSortHelper(left: 0, right: count-1)
  }

  private mutating func quickSortHelper(left left: Int, right: Int) {

    if left >= right {
      let p = Partition(left: left, right: right)
      quickSortHelper(left: left, right: p-1)
      quickSortHelper(left: p+1, right: right)
    }
  }

  mutating func Partition(left left: Int, right: Int) -> Int {

    let pivot = self[right]
    var partition = left
    for index in left..<right {
      if self[index] < pivot {
        if partition != index {
          swap(&self[partition], &self[index])
        }

        partition++
      }
    }
    if partition != right {
      swap(&self[partition], &self[right])
    }
    return partition
  }
}
```

###Merge Sort
```swift
extension Array where Element: Comparable {

  mutating func mergeSort() {
    mergeSortHelper(0, right: self.count - 1)
  }

  private mutating func mergeSortHelper(left: Int, right: Int) {
    if left < right {
      let mid = (left + right) / 2
      mergeSortHelper(left, right: mid)
      mergeSortHelper(mid+1, right: right)
      merge(left, leftEnd: mid, rightStart: mid+1, rightEnd: right)
    }
  }

  private mutating func merge(leftStart: Int, leftEnd: Int, rightStart: Int, rightEnd: Int) {

    var result = [Element](count: (rightEnd - leftStart) + 1, repeatedValue: self.first!)
    var index = 0

    var left = leftStart
    var right  = rightStart

    while left <= leftEnd && right <= rightEnd{
      if self[left] < self[right] {
        result[index++] = self[left++]
      } else {
        result[index++] = self[right++]
      }
    }

    while left <= leftEnd {
      result[index++] = self[left++]
    }

    while right <= rightEnd {
      result[index++] = self[right++]
    }

    index = 0
    for i in leftStart...rightEnd {
      self[i] = result[index++]
    }
  }
}
```


text:
require "redisplay/field/hash"
require "redisplay/field/list"
require "redisplay/field/set"
require "redisplay/field/string"
require "redisplay/field/zset"

module Redisplay
  module Field

    def self.included(base)
      base.attr_accessor :value
    end

    def self.new(key)
      type = Redisplay.redis.type(key)
      type[0] = type[0,1].upcase
      Redisplay::Field.const_get(type).new(key)
    rescue
      nil
    end

    def to_s
      @value.to_s
    end

  end
end


text:
When a new release is promoted to either the beta or stable channel, the
corresponding field in `infra/config/lib/release_branches/branches.json` should
be kept up to date, and re-generate the repository's config by executing
`infra/config/main.star`.

## Updating ProtoBuf

After editing the protobuf, run the script:

```
$ ./compile_proto.sh
```

And check in the updated `branches.bin` file.


text:
/*! @file error.h */

#ifndef __XMLBUS_ERROR_H__
#define __XMLBUS_ERROR_H__

#ifdef __cplusplus
extern "C" {
#endif

#include <libxml/parser.h>
#include <xmlbus/xmlbusexports.h>

#define XMLBUS_ERRORS_LOCATION  __FILE__,__LINE__,__FUNCTION__
#define XMLBUS_OK NULL
#define XMLBUS_GENERIC_ERROR 1

typedef	struct xmlbus_error_struct {
	const char *file;
	int line;
	const char *func;
	unsigned long errorCode;
	xmlChar *msg;
	struct xmlbus_error_struct* next;
} xmlbusError, *xmlbusErrorPtr;

/**
* @brief Creates the first or adds another error object (struct) to this error stack
*
* xmlbusError:
* @param file:        the error location filename (__FILE__).
* @param line:        the error location line number (__LINE__).
* @param func:        the error location function (__FUNCTION__).
* @param errorCode:       the error code.
* @param msg:         the error message in printf format.
* @param ...:         the parameters for the @msg.
* @return xmlbusErrorPtr containing the error information
*
*/
XMLBUSPUBFUN xmlbusErrorPtr XMLBUSCALL xmlbusErrorAdd(xmlbusErrorPtr cur,
				   const char* file,
				   int line,
				   const char* func,
				   unsigned long errorCode,
				   const xmlChar* msg,
				   ...);

/**
 * @brief Free the complete stack of errors
 *
 * Free the complete stack of errors as given by the xmlbusError structure and the structure itself.
 * NOTE: If you give a xmlbusError pointer of an xmlbusError structure that is not the first, it will free only
 * the ones after the given one and the given one itself.
 *
 * @param xmlbusErrorPtr pointer to the first xmlbusError structure of the full stack
 */
XMLBUSPUBFUN void XMLBUSCALL xmlbusErrorFree(xmlbusErrorPtr err);

/**
 * @brief get a fully formatted string of the error stack
 *
 * @param xmlbusErrorPtr pointer to the xmlbusError structure to be merged to a string
 * @return xmlChar* containing the formatted string for the full error stack.
 *         NOTE: the xmlChar* is allocated and needs to be freed by the caller.
 */
XMLBUSPUBFUN xmlChar* XMLBUSCALL xmlbusErrorGetString(xmlbusErrorPtr err);

/**
 * @brief get a formatted string of the last error in the stack
 *
 * @param xmlbusErrorPtr containing the xmlbusError structure to give the last errors' string for
 * @return xmlChar* containing the last error.
 *         NOTE: the xmlChar* is allocated and needs to be freed by the caller
 */
XMLBUSPUBFUN xmlChar* XMLBUSCALL xmlbusErrorGetLastString(xmlbusErrorPtr err);

/**
 * @brief get a fully formatted string of the full error stack.
 *
 * @param xmlbusErrorPtr pointer to the xmlbusError structure to be merged to a string
 * @return xmlChar* containing the full error stack including file and function names
 *         NOTE: the the xmlChar* is allocated and needs to be freed by the caller
 */
XMLBUSPUBFUN xmlChar* XMLBUSCALL xmlbusErrorGetFullString(xmlbusErrorPtr err);

/**
 * @brief get the errorcode of the last error in the stack
 *
 * @param xmlbusErrorPtr pointer to the xmlbusError structure
 * @return long containing the errorcode
 */
XMLBUSPUBFUN long XMLBUSCALL xmlbusErrorGetLastCode(xmlbusErrorPtr err);

/**
 * @brief get the complete error stack as a XML formatted structure
 *
 * @param xmlbusErrorPtr pointer to the xmlbusError structure
 * @return xmlNodePtr containing the complete error stack in XML
 */
XMLBUSPUBFUN xmlNodePtr XMLBUSCALL xmlbusErrorGetFullStackAsNode(xmlbusErrorPtr err);

#ifdef __cplusplus
}
#endif

#endif /* XMLBUS_ERROR_H */


text:
package org.apache.camel.component.grape;

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

import groovy.lang.GroovyClassLoader;
import org.apache.camel.CamelContext;
import org.apache.camel.ServiceStatus;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.apache.camel.ServiceStatus.Started;
import static org.apache.camel.component.grape.GrapeComponent.grapeCamelContext;
import static org.apache.camel.component.grape.GrapeEndpoint.loadPatches;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class GrapeComponentTest {

    FilePatchesRepository pathesRepository = new FilePatchesRepository();

    CamelContext camelContext = new DefaultCamelContext();

    @BeforeEach
    public void before() {
        grapeCamelContext(camelContext);
    }

    @Test
    public void shouldLoadStreamComponent() {
        assertDoesNotThrow(
                () -> runShouldLoadStreamTest("grape:org.apache.camel/camel-stream/" + camelContext.getVersion(), "msg"));
    }

    @Test
    public void shouldLoadStreamComponentViaBodyRequest() {
        assertDoesNotThrow(
                () -> runShouldLoadStreamTest("grape:grape", "org.apache.camel/camel-stream/" + camelContext.getVersion()));
    }

    private void runShouldLoadStreamTest(String s, String s2) {
        pathesRepository.clear();
        camelContext.start();
        camelContext.createProducerTemplate().sendBody(s,
                s2);
        camelContext.createProducerTemplate().sendBody("stream:out", "msg");
    }

    @Test
    public void shouldLoadBeanAtRuntime() {
        pathesRepository.clear();
        camelContext.start();
        camelContext.createProducerTemplate().sendBody("grape:grape",
                "org.apache.camel/camel-stream/" + camelContext.getVersion());
        ServiceStatus status = camelContext.createProducerTemplate().requestBody(
                "bean:org.apache.camel.component.stream.StreamComponent?method=getStatus", null, ServiceStatus.class);
        assertEquals(Started, status);
    }

    @Test
    public void shouldLoadPatchesAtStartup() throws Exception {
        // Given
        pathesRepository.clear();
        camelContext.start();
        camelContext.createProducerTemplate().sendBody("grape:grape",
                "org.apache.camel/camel-stream/" + camelContext.getVersion());
        camelContext.stop();

        camelContext = new DefaultCamelContext();
        camelContext.setApplicationContextClassLoader(new GroovyClassLoader());
        camelContext.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                loadPatches(camelContext);
            }
        });

        // When
        camelContext.start();
        ServiceStatus status = camelContext.createProducerTemplate().requestBody(
                "bean:org.apache.camel.component.stream.StreamComponent?method=getStatus", null, ServiceStatus.class);

        // Then
        assertEquals(Started, status);
    }

    @Test
    public void shouldListPatches() {
        pathesRepository.clear();
        camelContext.start();
        camelContext.createProducerTemplate().sendBody("grape:grape",
                "org.apache.camel/camel-stream/" + camelContext.getVersion());
        List<String> patches = pathesRepository.listPatches();
        assertEquals(Arrays.asList("org.apache.camel/camel-stream/" + camelContext.getVersion()), patches);
    }

}


text:
using System.Threading.Tasks;
using Tweetinvi.Models;
using Tweetinvi.Streaming.Webhooks;

namespace Tweetinvi.AspNet.Core.Logic
{
    public interface IWebhookRouter
    {
        Task<bool> IsRequestManagedByTweetinviAsync(IWebhooksRequest request);
        Task<bool> TryRouteRequestAsync(IWebhooksRequest request, IConsumerOnlyCredentials credentials);
    }

    public class WebhookRouter : IWebhookRouter
    {
        private readonly IWebhookDispatcher _webhookDispatcher;
        private readonly IWebhooksRoutes _webhooksRoutes;
        private readonly IWebhooksHelper _webhooksHelper;

        public WebhookRouter(
            IWebhookDispatcher webhookDispatcher,
            IWebhooksRoutes webhooksWebhooksRoutes,
            IWebhooksHelper webhooksHelper)
        {
            _webhookDispatcher = webhookDispatcher;
            _webhooksRoutes = webhooksWebhooksRoutes;
            _webhooksHelper = webhooksHelper;
        }

        public Task<bool> IsRequestManagedByTweetinviAsync(IWebhooksRequest request)
        {
            return _webhooksHelper.IsRequestManagedByTweetinviAsync(request);
        }

        public async Task<bool> TryRouteRequestAsync(IWebhooksRequest request, IConsumerOnlyCredentials credentials)
        {
            var isCrcChallenge = _webhooksHelper.IsCrcChallenge(request);
            if (isCrcChallenge)
            {
                return await _webhooksRoutes.TryToReplyToCrcChallengeAsync(request, credentials).ConfigureAwait(false);
            }

            var jsonBody = await request.GetJsonFromBodyAsync().ConfigureAwait(false);

            _webhookDispatcher.WebhookMessageReceived(new WebhookMessage(jsonBody));

            return await Task.FromResult(true).ConfigureAwait(false);
        }
    }
}


text:
package ch.pantas.billsplitter.model;

import android.content.Context;

import java.util.List;

import static com.google.inject.internal.util.$Preconditions.checkNotNull;

public class ExpensePresentation {
    private final User payer;
    private final Expense expense;
    private final SupportedCurrency currency;
    private final List<User> attendees;

    public ExpensePresentation(User payer, Expense expense, SupportedCurrency currency, List<User> attendees) {
        checkNotNull(payer);
        checkNotNull(expense);
        checkNotNull(attendees);

        this.payer = payer;
        this.expense = expense;
        this.currency = currency;
        this.attendees = attendees;
    }

    public Expense getExpense() {
        return expense;
    }

    public User getPayer() {
        return payer;
    }

    public String getFormattedAmount() {
        return currency.format(expense.getAmount());
    }

    public String getAttendeesCommaSeparated() {
        StringBuffer attendeeString = new StringBuffer();
        boolean first = true;
        for (User user : attendees) {
            if (!first) {
                attendeeString.append(", ");
            }

            attendeeString.append(user.getName());
            first = false;
        }

        return attendeeString.toString();
    }
}


text:
package cn.nec.nlc.example.activitytest24;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
	// constant for identifying the dialog
	private static final int DIALOG_ALERT = 10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	// adjust this method if you have more than
	// one button pointing to this method
	public void onClick(View view) {
		showDialog(DIALOG_ALERT);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
	  switch (id) {
	    case DIALOG_ALERT:
	      Builder builder = new AlertDialog.Builder(this);
	      builder.setMessage("This ends the activity");
	      builder.setCancelable(false);	// default: true
	      builder.setPositiveButton("I agree", new OkOnClickListener());
	      builder.setNegativeButton("No, no", new CancelOnClickListener());
	      AlertDialog dialog = builder.create();
	      dialog.show();
	  }
	  return super.onCreateDialog(id);
	}

	private final class OkOnClickListener implements
    	DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int which) {
			MainActivity.this.finish();
		}
	}

	private final class CancelOnClickListener implements
		DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int which) {
			Toast.makeText(getApplicationContext(),
					"Cancel selected, activity continues", Toast.LENGTH_LONG)
					.show();
		}
	}
}


text:
Order: 50
Title: GitLab CI
---

To use GitVersion with GitLab CI, either use the [MSBuild Task](../../usage/msbuild-task)
or put the GitVersion executable in your runner's `PATH`.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using CityPlace.Domain.Entities;
using CityPlace.Domain.Interfaces.Repositories;
using CityPlace.Domain.IoC;
using CityPlace.Domain.Notifications.Templates;
using CityPlace.Domain.Routing;
using CityPlace.Domain.Utils;
using CityPlace.Web.Classes.Security;
using CityPlace.Web.Models.Manage;

namespace CityPlace.Web.Controllers
{
    /// <summary>
    /// Контроллер управления пользователями, зарегистрированными в системе
    /// </summary>
    public class ManageUsersController : BaseController
    {
        /// <summary>
        /// Страница со списком пользователей, зарегистрированных в системе
        /// </summary>
        /// <param name="model">Модель фильтрации</param>
        /// <returns></returns>
        [Route("manage/users/")][AuthorizationCheck(Permission.ManageUsers)]
        public ActionResult Index(ManageUsersListModel model)
        {
            // Репозиторий
            var rep = Locator.GetService<IUsersRepository>();

            IEnumerable<User> users = rep.FindAll().OrderByDescending(c => c.DateRegistred);

            model.Fetched = users.ToList();

            PushNavigationItem("Пользователи","/manage/users");
            PushNavigationItem("Список пользователей","#");

            return View(model);
        }

        /// <summary>
        /// Отображает форму создания нового пользоователя
        /// </summary>
        /// <param name="CompanyId">Идентификатор компании выбранной при создании по умолчанию</param>
        /// <returns></returns>
        [Route("manage/users/add")]
        [AuthorizationCheck(Permission.ManageUsers)]
        public ActionResult CreateUser(long? CompanyId)
        {
            PushNavigationItem("Пользователи","/manage/users");
            PushNavigationItem("Создание нового пользователя","#");

            ViewBag.companyId = CompanyId.HasValue ? CompanyId.Value : -1;

            return View();
        }

        /// <summary>
        /// Обрабатывает создание нового пользователя через личный кабинет администратора
        /// </summary>
        /// <param name="user">Модель основных данных пользователя</param>
        /// <param name="Password">Пароль</param>
        /// <param name="PasswordConfirm">Подтверждение пароля</param>
        /// <returns></returns>
        [Route("manage/users/create")]
        [HttpPost]
        [AuthorizationCheck(Permission.ManageUsers)]
        public ActionResult Create(User user, string Password, string PasswordConfirm)
        {
            // Реп
            var rep = Locator.GetService<IUsersRepository>();
            if (rep.ExistsUserWithLogin(user.Email))
            {
                ShowError("Такой пользователь уже зарегистрирован");
                return RedirectToAction("Index");
            }

            // Регистрируем
            user.PasswordHash = PasswordUtils.GenerateMD5PasswordHash(Password);
            user.DateRegistred = DateTime.Now;

            rep.Add(user);
            rep.SubmitChanges();

            ShowSuccess(string.Format("Успешно зарегистрирован пользователь {0} {1}. На его почту отправлено письмо с информацией о регистрации", user.GetFio(), user.Email));

            // Уведомляем
            var notificationModel = new
            {
                FIO = user.GetFio(),
                Email = user.Email,
                Password = Password
            };

            NotifyEmail(user, "Регистрация в системе SeoLight",
                new ParametrizedFileTemplate(
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "Mail", "Register.html"),
                    notificationModel).ToString());

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Карточка пользователя с ограниченной инфорацией=
        /// </summary>
        /// <param name="id">Идентификатор пользователя</param>
        /// <returns></returns>
        [AuthorizationCheck(Permission.ManageUsers)]
        [Route("manage/users/{id}/info")]
        public ActionResult Info(long id)
        {
            var rep = Locator.GetService<IUsersRepository>();
            var user = rep.Load(id);
            if (user == null)
            {
                ShowError("Такой пользователь не найден");
                return RedirectToAction("Index");
            }

            PushNavigationItem("Пользователи","/manage/users");
            PushNavigationItem("Карточка пользователя "+user.GetFio(),"#");

            return View(user);
        }

        /// <summary>
        /// Обновляет некоторые данные о пользователе
        /// </summary>
        /// <param name="id">Идентификатор пользователя</param>
        /// <param name="CompanyId">Идентификатор компании</param>
        /// <param name="RoleId">Идентификатор оли</param>
        /// <param name="Status">Статус пользователя</param>
        /// <returns></returns>
        [AuthorizationCheck(Permission.ManageUsers)]
        [Route("manage/users/update-info")]
        [HttpPost]
        public ActionResult UpdateCard(long id, long RoleId, short Status)
        {
            var rep = Locator.GetService<IUsersRepository>();
            var rolesRep = Locator.GetService<IRolesRepository>();
            var user = rep.Load(id);
            if (user == null)
            {
                ShowError("Такой пользователь не найден");
                return RedirectToAction("Index");
            }

            var role = rolesRep.Load(RoleId);

            if (RoleId != user.RoleId)
            {
                user.Role.Users.Remove(user);
                role.Users.Add(user);
            }
            user.Status = Status;

            user.DateModified = DateTime.Now;
            rep.SubmitChanges();

            ShowSuccess("Изменения успешно сохранены");

            return RedirectToAction("Index");
        }
    }
}


text:
type: tutorial
layout: tutorial
title:  "Kotlin Android Extensions"
description: "This tutorial describes how to use Kotlin Android Extensions to improve support for Android development."
authors: Yan Zhulanow
showAuthorInfo: true
date: 2015-03-18
source:
---
In this tutorial we'll walk through the steps required to use the Kotlin Android Extensions plugin, enhancing the development experience with Android.

### Background

Every Android developer knows well the `findViewById()` function. It is, without a doubt, a source of potential bugs and nasty code which is hard to read and support.
While there are several libraries available that provide solutions to this problem, being libraries dependent on runtime, they require annotating fields for each `View`.

The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code or shipping any additional runtime.

In essence, this would allow for the following code:

~~~kotlin
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView.setText("Hello, world!")
        // Instead of findView(R.id.textView) as TextView
    }
}
~~~

`textView` is an extension property for `Activity`, and it has the same type as declared in `activity_main.xml`.

### Using Kotlin Android Extensions

#### Configuring the dependency

{{ site.text_using_gradle }}

Android Extensions is a part of the Kotlin IDEA plugin. You do not need to install additional plugins.

All you need is to enable the Android Extensions Gradle plugin in your project-local `build.gradle` file:

``` groovy
apply plugin: 'kotlin-android-extensions'
```

#### Importing synthetic properties

It is convenient to import all widget properties for a specific layout in one go:

``` kotlin
import kotlinx.android.synthetic.main.<layout>.*
```

Thus if the layout filename is `activity_main.xml`, we'd import `kotlinx.android.synthetic.main.activity_main.*`.

If we want to call the synthetic properties on `View` (useful in adapter classes), we should also import `kotlinx.android.synthetic.main.activity_main.view.*`.

Once we do that, we can then invoke the corresponding extensions, which are properties named after the views in the XML file.
For example, for this view:

``` xml
    <TextView
            android:id="@+id/hello"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hello World, MyActivity"
            />
```

There will be property named `hello`:

``` kotlin
activity.hello.setText("Hi!")
```

### Android Flavors

Android Extensions plugin supports Android flavors. Suppose you have a flavor named `free` in your `build.gradle` file:

```
android {
    productFlavors {
        free {
            versionName "1.0-free"
        }
    }
}
```

So you can import all synthetic properties for the `free/res/layout/activity_free.xml` layout by adding this import:

```kotlin
import kotlinx.android.synthetic.free.activity_free.*
```

### Under the hood

Kotlin Android Extensions is a plugin for the Kotlin compiler, and it does two things:

1. Adds a hidden caching function and a field inside each Kotlin `Activity`. The method is pretty small so it doesn't increase the size of APK much.
2. Replaces each synthetic property call with a function call.

How this works is that when invoking a synthetic property, where the receiver is a Kotlin Activity/Fragment class that is in module sources, the caching function is invoked.
For instance, given

``` kotlin
class MyActivity: Activity()
fun MyActivity.a() {
    this.textView.setText("")
}
```

a hidden caching function is generated inside MyActivity, so we can use the caching mechanism.

However in the following case:

``` kotlin
fun Activity.b() {
    this.textView.setText("")
}
```

We wouldn't know if this function would be invoked on only Activities from our sources or on plain Java Activities also. As such, we don't use caching there, even
if MyActivity instance from the previous example is the receiver.


text:
(function() {
  describe('MyCtrl1', function() {
    var myCtrl1;
    myCtrl1 = null;
    beforeEach(function() {
      return myCtrl1 = new MyCtrl1();
    });
    return it('should ....', function() {});
  });

}).call(this);


text:
<?php

/**
 *  Lousson\Message\Generic\GenericMessageBroker class definition
 *
 *  @package    org.lousson.message
 *  @copyright  (c) 2013, The Lousson Project
 *  @license    http://opensource.org/licenses/bsd-license.php New BSD License
 *  @author     Mathias J. Hennig <mhennig at quirkies.org>
 *  @filesource
 */
namespace Lousson\Message\Generic;

/** Interfaces: */
use Lousson\Message\AnyMessageBroker;
use Lousson\Message\AnyMessageHandler;
use Lousson\Message\AnyMessageProvider;
use Lousson\Message\AnyMessage;

/**
 *  A generic message broker implementation
 *
 *  The Lousson\Message\Generic\GenericMessageBroker is an implementation
 *  of the AnyMessageBroker interface. It acts as a combined decorator for
 *  both; a message provider and a handler instance.
 *
 *  @since      lousson/Lousson_Message-0.1.0
 *  @package    org.lousson.message
 */
class GenericMessageBroker implements AnyMessageBroker
{
    /**
     *  Create a broker instance
     *
     *  The constructor requires the caller to provide both, a message
     *  provider and a handler instance, for the broker to delegate any
     *  invocation to.
     *
     *  @param  AnyMessageProvider  $provider   The message provider
     *  @param  AnyMessageHandler   $handler    The message handler
     */
    public function __construct(
        AnyMessageProvider $provider,
        AnyMessageHandler $handler
    ) {
        $this->provider = $provider;
        $this->handler = $handler;
    }

    /**
     *  Process message data
     *
     *  The process() method is used to invoke the logic that processes
     *  the message $data, a byte sequence of the given mime- or media-
     *  $type, according to the event $uri provided. If the $type is not
     *  provided, implementations should assume "application/octet-stream"
     *  or may attempt to detect it.
     *
     *  @param  string              $uri        The event URI
     *  @param  string              $data       The message data
     *  @param  string              $type       The media type
     *
     *  @throws \Lousson\Message\AnyMessageException
     *          All exceptions raised implement this interface
     *
     *  @throws \InvalidArgumentException
     *          Raised in case an argument is considered invalid
     *
     *  @throws \RuntimeException
     *          Raised in case an internal error occurred
     */
    public function process($uri, $data, $type = null)
    {
        $this->handler->process($uri, $data, $type);
    }

    /**
     *  Process message instances
     *
     *  The processMessage() method is used to invoke the logic that
     *  processes the given $message according to the event $uri.
     *
     *  @param  string              $uri        The event URI
     *  @param  AnyMessage          $message    The message instance
     *
     *  @throws \Lousson\Message\AnyMessageException
     *          All exceptions raised implement this interface
     *
     *  @throws \InvalidArgumentException
     *          Raised in case an argument is considered invalid
     *
     *  @throws \RuntimeException
     *          Raised in case an internal error occurred
     */
    public function processMessage($uri, AnyMessage $message)
    {
        $this->handler->processMessage($uri, $message);
    }

    /**
     *  Retrieve message instances
     *
     *  The fetch() method is used to obtain the next message that is
     *  associated with the given event $uri. The $flags parameter can
     *  be used to request special behavior:
     *
     *- AnyMessageProvider::FETCH_CONFIRM
     *  Populate the $token reference for acknowledge() or discard()
     *
     *  @param  string              $uri        The event URI
     *  @param  int                 $flags      The option bitmask
     *  @param  mixed               $token      The delivery token
     *
     *  @return \Lousson\Message\AnyMessage
     *          A message instance is returned on success, or NULL in
     *          case no more messages are available for the given $uri
     *
     *  @throws \Lousson\Message\AnyMessageException
     *          All exceptions raised implement this interface
     *
     *  @throws \InvalidArgumentException
     *          Raised in case an argument is considered invalid
     *
     *  @throws \RuntimeException
     *          Raised in case an internal error occurred
     */
    public function fetch(
        $uri, $flags = self::FETCH_DEFAULT, &$token = null
    ) {
        $message = $this->provider->fetch($uri, $flags, $token);
        return $message;
    }

    /**
     *  Acknowledge a message
     *
     *  The acknowledge() method is used to tag a message (formerly
     *  received via fetchToken() on the same instance) as acknowledged.
     *  This is usually done after the processing of the message, when one
     *  knows that no further errors can occur.
     *
     *  The optional $flags parameter can be used to request special
     *  behavior (none defined yet).
     *
     *  @param  mixed               $token      The delivery token
     *  @param  int                 $flags      The option bitmask
     *
     *  @throws \Lousson\Message\AnyMessageException
     *          All exceptions raised implement this interface
     *
     *  @throws \InvalidArgumentException
     *          Raised in case an argument is considered invalid
     *
     *  @throws \RuntimeException
     *          Raised in case an internal error occurred
     */
    public function acknowledge($token, $flags = self::ACK_DEFAULT)
    {
        $this->provider->acknowledge($token, $flags);
    }

    /**
     *  Discard a message
     *
     *  The discard() method is used to tag a message (formerly received
     *  via fetch() or fetchToken() on the same instance) as discarded.
     *  This is usually done if either the message was invalid or some
     *  internal error occured (in combination with DISC_REQUEUE).
     *  behavior:
     *
     *- AnyMessageProvider::DISC_REQUEUE
     *  Re-queue the message for the next call to fetch()
     *
     *  @param  mixed               $token      The delivery token
     *  @param  int                 $flags      The option bitmask
     *
     *  @throws \Lousson\Message\AnyMessageException
     *          All exceptions raised implement this interface
     *
     *  @throws \InvalidArgumentException
     *          Raised in case an argument is considered invalid
     *
     *  @throws \RuntimeException
     *          Raised in case an internal error occurred
     */
    public function discard($token, $flags = self::DISC_DEFAULT)
    {
        $this->provider->discard($token, $flags);
    }
}


text:
package org.folg.gedcom.parser;

import com.google.gson.*;
import org.folg.gedcom.model.Extensions;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * User: Dallan
 * Date: 12/18/11
 */
public class ExtensionsTypeAdapter implements JsonSerializer<Extensions>, JsonDeserializer<Extensions> {
   private Gson gson;
   private Map<String,Class> classExtensions;
   private Map<String,Type> typeExtensions;

   public ExtensionsTypeAdapter() {
      gson = new Gson();
      classExtensions = new HashMap<String, Class>();
      typeExtensions = new HashMap<String, Type>();
   }

   public void registerExtension(String extensionKey, Class clazz) {
      classExtensions.put(extensionKey, clazz);
   }

   public void registerExtension(String extensionKey, Type type) {
      typeExtensions.put(extensionKey, type);
   }

   public JsonElement serialize(Extensions src, Type typeOfSrc, JsonSerializationContext context) {
      JsonObject o = new JsonObject();
      for (Map.Entry<String, Object> entry : src.getExtensions().entrySet()) {
         String key = entry.getKey();
         Object extension = entry.getValue();
         JsonElement elm = (extension instanceof JsonElement ? (JsonElement) extension : gson.toJsonTree(extension));
         o.add(key, elm);
      }
      return o;
   }

   @SuppressWarnings("unchecked")
   public Extensions deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
      JsonObject o = json.getAsJsonObject();
      Extensions extensions = new Extensions();
      for (Map.Entry<String, JsonElement> entry : o.entrySet()) {
         String key = entry.getKey();
         JsonElement jsonElement = entry.getValue();
         Object extension;
         Type type = typeExtensions.get(key);
         if (type != null) {
            extension = gson.fromJson(jsonElement, type);
         }
         else {
            Class clazz = classExtensions.get(key);
            if (clazz != null) {
               extension = gson.fromJson(jsonElement, clazz);
            }
            else {
               extension = jsonElement;
            }
         }
         extensions.put(key, extension);
      }
      return extensions;
   }
}


text:
import re, os, pprint

# paths to relevant directories
path_to_scripts = '../game/script/'

# Get list of all *.gd files to read in files
file_regex = re.compile(r'.*\.gd')
files = []
for folder_name, sub_folders, file_names in os.walk(path_to_scripts):
	all_file = filter(file_regex.match, list(file_names))
	for f in (list(all_file)):
		files.append(f)

# opens one file at a time and stores in file_data
full_regex = re.compile(r'(((#.*\n)*)func +([^_].*)\((.*)\):|enum(.*){(([^,}]*,)*.*)})')
comment_regex = re.compile(r'ret +(.*), *arg +(.*)')
#function_regex = re.compile(r'((#.*\n)*)func +([^_].*):')
#enum_regex = re.compile(r'enum(.*){(([^,}]*,)*.*)}')
file_data = {}
for f in files:
	file_data[f] = []
	file = open(path_to_scripts + f)
	text = file.read()
	file.close()
	# searches text by regex to get info to put into file_data
	result_list = full_regex.findall(text)
	for index, result_groups in enumerate(result_list):
		if result_groups[3] == '':
			#enum
			print("Enum.")
		else:
			#func
			comment_group = result_groups[1].split('\n')
			function_data = {"function_name": result_groups[3]}
			comments = ''
			for i in range(len(comment_group) - 1):
				if i == len(comment_group) - 2:
					match = comment_regex.match(comment_group[i][1:].strip())
					print(match)
					if match != None:
						arg_types = match.group(2).split(',')
						args_raw = result_groups[4].split(',')
						args = []
						for i in range(len(args_raw)):
							if i < len(arg_types):
								args.append(arg_types[i].strip() + " " + args_raw[i].strip())
							else:
								args.append(args_raw[i].strip())
						function_data["arguments"] = args
						function_data["return_type"] = match.group(1).strip()
						continue
				# need refactoring
				comments += comment_group[i][1:].strip() + "  \n"
			if comments != '':
				function_data["comments"] = comments
			file_data[f].append(function_data)

pprint.pprint(file_data)

# Opens api file in api_file and writes file_data to it
api_file = open('API.md', 'w')

# writing

api_file.close()


text:
using System;
using System.Net.Sockets;

namespace EventStore.Transport.Tcp
{
    internal class SocketArgsPool
    {
        public readonly string Name;

        private readonly Func<SocketAsyncEventArgs> _socketArgsCreator;
        private readonly Common.Concurrent.ConcurrentStack<SocketAsyncEventArgs> _socketArgsPool = new Common.Concurrent.ConcurrentStack<SocketAsyncEventArgs>();

        public SocketArgsPool(string name, int initialCount, Func<SocketAsyncEventArgs> socketArgsCreator)
        {
            if (socketArgsCreator == null)
                throw new ArgumentNullException("socketArgsCreator");
            if (initialCount < 0)
                throw new ArgumentOutOfRangeException("initialCount");

            Name = name;
            _socketArgsCreator = socketArgsCreator;

            for (int i = 0; i < initialCount; ++i)
            {
                _socketArgsPool.Push(socketArgsCreator());
            }
        }

        public SocketAsyncEventArgs Get()
        {
            SocketAsyncEventArgs result;
            if (_socketArgsPool.TryPop(out result))
                return result;
            return _socketArgsCreator();
        }

        public void Return(SocketAsyncEventArgs socketArgs)
        {
            _socketArgsPool.Push(socketArgs);
        }
    }
}


text:
These tests assume you have access to some llvm tools (clang, lldb, FileCheck)
in your PATH. clang and lldb are usually installed if you build them, but in
order to have utils like FileCheck installed you have to make sure
`LLVM_INSTALL_UTILS` is true when you configure your build.

You also need lit in your path. A stand-alone version of lit is
available in PyPI, and can be installed by running `pip install lit`.

## Running the tests

Pass the path to the directory containing these tests to the lit tool. For
example, if you're in the root directory of the gala repo, run:
```
lit test/lit
```

## Adding new tests

The configuration for the test suite is in `lit.cfg.py`. It currently defines
`.test` as the only recognized extension for tests.

These tests usually have three parts:

- A source file that uses some language featue we want to test from the
  debugger.
- A python script that uses the gdb API to interact with the test program and
  prints some results.
- A `.test` file that contains some lit `RUN:` directives to build the test
  program and run the debugger, and some `CHECK:` directives to verify the
  output matches expectations.

Take a look at the existing tests for more details.


text:
require_relative 'creative_asset_utils'
require_relative 'dfareporting_utils'

def create_enhanced_banner_creative(dfareporting, args)
  util = CreativeAssetUtils.new(dfareporting, args[:profile_id])

  # Upload the html5 asset
  html5_asset_id = util.uploadAsset(args[:advertiser_id],
      args[:path_to_html_asset_file], 'HTML')

  # Upload the backup image asset
  backup_image_asset_id = util.uploadAsset(args[:advertiser_id],
      args[:path_to_image_file], 'HTML_IMAGE')

  # Construct the creative structure
  creative = {
    :advertiserId => args[:advertiser_id],
    :backupImageClickThroughUrl => 'https://www.google.com',
    :backupImageReportingLabel => 'backup_image_exit',
    :backupImageTargetWindow => { :targetWindowOption => 'NEW_WINDOW' },
    :clickTags => [
      {
        :eventName => 'exit',
        :name => 'click_tag',
        :value => 'https://www.google.com'
      }
    ],
    :creativeAssets => [
      {
        :assetIdentifier => html5_asset_id,
        :role => 'PRIMARY'
      },
      {
        :assetIdentifier => backup_image_asset_id,
        :role => 'BACKUP_IMAGE'
      }
    ],
    :name => 'Example enhanced banner creative',
    :size => { :id => args[:size_id] },
    :type => 'ENHANCED_BANNER'
  }

  # Insert the creative
  result = dfareporting.creatives.insert(
    :profileId => args[:profile_id]
  ).body(creative).execute()

  puts 'Created enhanced banner creative with ID %d and name "%s".' %
      [result.data.id, result.data.name]
end

if __FILE__ == $0
  # Retrieve command line arguments
  args = DfaReportingUtils.get_arguments(
      ARGV, :profile_id, :advertiser_id, :size_id, :path_to_html_asset_file,
      :path_to_image_file)

  # Authenticate and initialize API service
  dfareporting = DfaReportingUtils.setup()

  create_enhanced_banner_creative(dfareporting, args)
end


text:
/* ----- comments ----- */
.comments {
    position: relative;
    padding: 0 4px 12px 12px;
    color: black;
}
.comments .e-overlay {
    position: absolute;
}
.comments .actionset {
    float: right;
    position: relative;
    left: 2px;
    padding-left: 8px;
}
.comments_title {
    margin: 0;
    font-size: 1.834em; /* =22px */
}
.comment_list {
    clear: both;
    margin: 0;
    padding: 12px 0 0 0;
    list-style: none;
}
.comment_item {
    margin: 0;
    padding: 11px 0 7px 0;
}
.comment_list .first_item {
    background: none;
}
.comment_list .last_item {
    padding-bottom: 0;
}
.comment_actionset {
    float: right;
    padding: 6px 0 6px 10px;
}
.comment_actionset a:link, .comment_actionset a:visited {
    text-decoration: underline;
}
.comment_actionset a:hover, .comment_actionset a:active {
    text-decoration: none;
}
.comment_userinfo {
    padding-bottom: 7px;
}
.comment_username {
    font-size: 1.25em; /* =15px */
    font-weight: bold;
}
.comment_username a:link, .comment_username a:visited {
    text-decoration: none;
}
.comment_username a:hover, .comment_username a:active {
    text-decoration: underline;
}
.comment_date {
    color: #00a31f;
}
.comment_text {
    clear: both;
    margin-bottom: 5px;
}
.comment_form {
    margin: 0;
}
.comment_inputblock {
    position: relative;
    clear: both;
    padding-top: 20px;
}
.comment_item .comment_inputblock {
    padding-top: 0;
}
.comment_inputblock .btn_comment {
    position: relative;
    left: -2px;
    margin-right: -2px;
}
.comment_inputblock .e-overlay{
    position: absolute;
}
.comment_title {
    font-size: 1.25em; /* =15px */
    font-weight: bold;
}
.comment_field {
    padding: 3px 8px 9px 0;
}
.comment_field textarea {
    width: 100%;
    height: 110px;
    margin-right: -8px;
}
.comment_controlset .note {
    padding-left: 7px;
    padding-right: 7px;
}
.comment_thread {
    position: relative;
}
.comment_thread_icon {
    display: block;
    position: absolute;
    top: 20px;
    left: 2px;
    z-index: 1;
}
.comment_thread .comment_list {
    padding: 7px 0 0 38px;
}
.comments .link_comment {
    font-size: 1.834em; /* =22px */
}

.comments .btn {
    margin-right: 10px;
    display: inline-block;
}

/* ----- /comments ----- */