text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Dtos;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.Repositories.Implement;
using Umbraco.Core.Scoping;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
using Umbraco.Tests.TestHelpers.Stubs;
using Umbraco.Tests.Testing;
using Current = Umbraco.Web.Composing.Current;

namespace Umbraco.Tests.Services
{
    [TestFixture, NUnit.Framework.Ignore("fixme - ignored test")]
    [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
    public class ContentServicePerformanceTest : TestWithDatabaseBase
    {
        public override void SetUp()
        {
            base.SetUp();
            CreateTestData();
        }

        protected override void Compose()
        {
            base.Compose();
            Composition.Register<IProfiler, TestProfiler>();
        }

        [Test]
        public void Profiler()
        {
            Assert.IsInstanceOf<TestProfiler>(Current.Profiler);
        }

        private static IProfilingLogger GetTestProfilingLogger()
        {
            var logger = new DebugDiagnosticsLogger();
            var profiler = new TestProfiler();
            return new ProfilingLogger(logger, profiler);
        }

        [Test]
        public void Retrieving_All_Content_In_Site()
        {
            //NOTE: Doing this the old 1 by 1 way and based on the results of the ContentServicePerformanceTest.Retrieving_All_Content_In_Site
            // the old way takes 143795ms, the new above way takes:
            // 14249ms
            //
            // ... NOPE, made some new changes, it is now....
            // 5290ms  !!!!!!
            //
            // that is a 96% savings of processing and sql calls!
            //
            // ... NOPE, made even more nice changes, it is now...
            // 4452ms !!!!!!!

            var contentType1 = MockedContentTypes.CreateTextPageContentType("test1", "test1");
            var contentType2 = MockedContentTypes.CreateTextPageContentType("test2", "test2");
            var contentType3 = MockedContentTypes.CreateTextPageContentType("test3", "test3");
            ServiceContext.ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 });
            contentType1.AllowedContentTypes = new[]
            {
                new ContentTypeSort(new Lazy<int>(() => contentType2.Id), 0, contentType2.Alias),
                new ContentTypeSort(new Lazy<int>(() => contentType3.Id), 1, contentType3.Alias)
            };
            contentType2.AllowedContentTypes = new[]
            {
                new ContentTypeSort(new Lazy<int>(() => contentType1.Id), 0, contentType1.Alias),
                new ContentTypeSort(new Lazy<int>(() => contentType3.Id), 1, contentType3.Alias)
            };
            contentType3.AllowedContentTypes = new[]
            {
                new ContentTypeSort(new Lazy<int>(() => contentType1.Id), 0, contentType1.Alias),
                new ContentTypeSort(new Lazy<int>(() => contentType2.Id), 1, contentType2.Alias)
            };
            ServiceContext.ContentTypeService.Save(new[] { contentType1, contentType2, contentType3 });

            var roots = MockedContent.CreateTextpageContent(contentType1, -1, 10);
            ServiceContext.ContentService.Save(roots);
            foreach (var root in roots)
            {
                var item1 = MockedContent.CreateTextpageContent(contentType1, root.Id, 10);
                var item2 = MockedContent.CreateTextpageContent(contentType2, root.Id, 10);
                var item3 = MockedContent.CreateTextpageContent(contentType3, root.Id, 10);

                ServiceContext.ContentService.Save(item1.Concat(item2).Concat(item3));
            }

            var total = new List<IContent>();

            using (GetTestProfilingLogger().TraceDuration<ContentServicePerformanceTest>("Getting all content in site"))
            {
                TestProfiler.Enable();
                total.AddRange(ServiceContext.ContentService.GetRootContent());
                foreach (var content in total.ToArray())
                {
                    total.AddRange(ServiceContext.ContentService.GetPagedDescendants(content.Id, 0, int.MaxValue, out var _));
                }
                TestProfiler.Disable();
                Current.Logger.Info<ContentServicePerformanceTest>("Returned {Total} items", total.Count);
            }
        }

        [Test]
        public void Creating_100_Items()
        {
            // Arrange
            var contentType = ServiceContext.ContentTypeService.Get(NodeDto.NodeIdSeed);
            var pages = MockedContent.CreateTextpageContent(contentType, -1, 100);

            // Act
            Stopwatch watch = Stopwatch.StartNew();
            ServiceContext.ContentService.Save(pages, 0);
            watch.Stop();
            var elapsed = watch.ElapsedMilliseconds;

            Debug.Print("100 content items saved in {0} ms", elapsed);

            // Assert
            Assert.That(pages.Any(x => x.HasIdentity == false), Is.False);
        }

        [Test]
        public void Creating_1000_Items()
        {
            // Arrange
            var contentType = ServiceContext.ContentTypeService.Get(NodeDto.NodeIdSeed);
            var pages = MockedContent.CreateTextpageContent(contentType, -1, 1000);

            // Act
            Stopwatch watch = Stopwatch.StartNew();
            ServiceContext.ContentService.Save(pages, 0);
            watch.Stop();
            var elapsed = watch.ElapsedMilliseconds;

            Debug.Print("100 content items saved in {0} ms", elapsed);

            // Assert
            Assert.That(pages.Any(x => x.HasIdentity == false), Is.False);
        }

        [Test]
        public void Getting_100_Uncached_Items()
        {
            // Arrange
            var contentType = ServiceContext.ContentTypeService.Get(NodeDto.NodeIdSeed);
            var pages = MockedContent.CreateTextpageContent(contentType, -1, 100);
            ServiceContext.ContentService.Save(pages, 0);

            var provider = TestObjects.GetScopeProvider(Logger);
            using (var scope = provider.CreateScope())
            {
                var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of<ITemplatesSection>(), TestObjects.GetFileSystemsMock());
                var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository);
                var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of<IContentSection>());

                // Act
                Stopwatch watch = Stopwatch.StartNew();
                var contents = repository.GetMany();
                watch.Stop();
                var elapsed = watch.ElapsedMilliseconds;

                Debug.Print("100 content items retrieved in {0} ms without caching", elapsed);

                // Assert
                Assert.That(contents.Any(x => x.HasIdentity == false), Is.False);
                Assert.That(contents.Any(x => x == null), Is.False);
            }

        }

        [Test, NUnit.Framework.Ignore("fixme - ignored test")]
        public void Getting_1000_Uncached_Items()
        {
            // Arrange
            var contentType = ServiceContext.ContentTypeService.Get(NodeDto.NodeIdSeed);
            var pages = MockedContent.CreateTextpageContent(contentType, -1, 1000);
            ServiceContext.ContentService.Save(pages, 0);

            var provider = TestObjects.GetScopeProvider(Logger);
            using (var scope = provider.CreateScope())
            {
                var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of<ITemplatesSection>(), TestObjects.GetFileSystemsMock());
                var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository);
                var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of<IContentSection>());

                // Act
                Stopwatch watch = Stopwatch.StartNew();
                var contents = repository.GetMany();
                watch.Stop();
                var elapsed = watch.ElapsedMilliseconds;

                Debug.Print("1000 content items retrieved in {0} ms without caching", elapsed);

                // Assert
                //Assert.That(contents.Any(x => x.HasIdentity == false), Is.False);
                //Assert.That(contents.Any(x => x == null), Is.False);
            }
        }

        [Test]
        public void Getting_100_Cached_Items()
        {
            // Arrange
            var contentType = ServiceContext.ContentTypeService.Get(NodeDto.NodeIdSeed);
            var pages = MockedContent.CreateTextpageContent(contentType, -1, 100);
            ServiceContext.ContentService.Save(pages, 0);

            var provider = TestObjects.GetScopeProvider(Logger);
            using (var scope = provider.CreateScope())
            {
                var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of<ITemplatesSection>(), TestObjects.GetFileSystemsMock());
                var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository);
                var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of<IContentSection>());

                // Act
                var contents = repository.GetMany();

                Stopwatch watch = Stopwatch.StartNew();
                var contentsCached = repository.GetMany();
                watch.Stop();
                var elapsed = watch.ElapsedMilliseconds;

                Debug.Print("100 content items retrieved in {0} ms with caching", elapsed);

                // Assert
                Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False);
                Assert.That(contentsCached.Any(x => x == null), Is.False);
                Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count()));
            }
        }

        [Test, NUnit.Framework.Ignore("fixme - ignored test")]
        public void Getting_1000_Cached_Items()
        {
            // Arrange
            var contentType = ServiceContext.ContentTypeService.Get(NodeDto.NodeIdSeed);
            var pages = MockedContent.CreateTextpageContent(contentType, -1, 1000);
            ServiceContext.ContentService.Save(pages, 0);

            var provider = TestObjects.GetScopeProvider(Logger);
            using (var scope = provider.CreateScope())
            {
                var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of<ITemplatesSection>(), TestObjects.GetFileSystemsMock());
                var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository);
                var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger);
                var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of<IContentSection>());

                // Act
                var contents = repository.GetMany();

                Stopwatch watch = Stopwatch.StartNew();
                var contentsCached = repository.GetMany();
                watch.Stop();
                var elapsed = watch.ElapsedMilliseconds;

                Debug.Print("1000 content items retrieved in {0} ms with caching", elapsed);

                // Assert
                //Assert.That(contentsCached.Any(x => x.HasIdentity == false), Is.False);
                //Assert.That(contentsCached.Any(x => x == null), Is.False);
                //Assert.That(contentsCached.Count(), Is.EqualTo(contents.Count()));
            }
        }

        [TearDown]
        public override void TearDown()
        {
            base.TearDown();
        }

        public void CreateTestData()
        {
            //Create and Save ContentType "textpage" -> NodeDto.NodeIdSeed
            ContentType contentType = MockedContentTypes.CreateTextPageContentType();
            ServiceContext.ContentTypeService.Save(contentType);
        }
    }
}


text:
package org.hoteia.qalingo.core.fetchplan.retailer;

import java.util.ArrayList;
import java.util.List;

import org.hoteia.qalingo.core.fetchplan.FetchPlan;
import org.hoteia.qalingo.core.fetchplan.SpecificFetchMode;
import org.hoteia.qalingo.core.domain.Retailer_;
import org.hoteia.qalingo.core.domain.Store_;
import org.hoteia.qalingo.core.domain.Company_;
import org.hoteia.qalingo.core.domain.CompanyStoreRel_;

public class FetchPlanGraphRetailer {

    public static FetchPlan defaultRetailerFetchPlan() {
        List<SpecificFetchMode> fetchplans = new ArrayList<SpecificFetchMode>();
        fetchplans.add(new SpecificFetchMode(Retailer_.links.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.addresses.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.stores.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.assets.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.attributes.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.customerRates.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.customerComments.getName()));
        return new FetchPlan(fetchplans);
    }

    public static FetchPlan fullRetailerFetchPlan() {
    	List<SpecificFetchMode> fetchplans = new ArrayList<SpecificFetchMode>();
        fetchplans.add(new SpecificFetchMode(Retailer_.links.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.addresses.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.stores.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.assets.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.attributes.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.customerRates.getName()));
        fetchplans.add(new SpecificFetchMode(Retailer_.customerComments.getName()));
        return new FetchPlan(fetchplans);
    }

    public static FetchPlan defaultStoreFetchPlan() {
        List<SpecificFetchMode> fetchplans = new ArrayList<SpecificFetchMode>();
        fetchplans.add(new SpecificFetchMode(Store_.attributes.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.assets.getName()));
        return new FetchPlan(fetchplans);
    }

    public static FetchPlan fullStoreFetchPlan() {
        List<SpecificFetchMode> fetchplans = new ArrayList<SpecificFetchMode>();
        fetchplans.add(new SpecificFetchMode(Store_.attributes.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.assets.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.businessHours.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.retailer.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.productBrands.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.companyStoreRels.getName()));
        fetchplans.add(new SpecificFetchMode(Store_.companyStoreRels.getName() + "." + CompanyStoreRel_.pk.getName()));
//        fetchplans.add(new SpecificFetchMode(Store_.retailer.getName() + "." + Retailer_.company.getName() + "." + Company_.users.getName()));
        return new FetchPlan(fetchplans);
    }

}

redpajama_set_name: RedPajamaGithub


text:
module LocationSH
  def default_location
    Todo.location
  end

  def custom_location
    "#{default_location}.custom"
  end

end
World LocationSH


text:
module Feldspar.Core.Frontend.NoInline where

import Language.Syntactic

import Feldspar.Core.Constructs
import Feldspar.Core.Constructs.NoInline

noInline :: (Syntax a) => a -> a
noInline = sugarSymF NoInline


text:
VersionHandler::VersionHandler() {}

VersionHandler::~VersionHandler() {}

void VersionHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      version_ui::kRequestVersionInfo,
      base::Bind(&VersionHandler::HandleRequestVersionInfo,
                 base::Unretained(this)));
}

void VersionHandler::HandleRequestVersionInfo(const base::ListValue* args) {
  // Respond with the variations info immediately.
  web_ui()->CallJavascriptFunction(version_ui::kReturnVariationInfo,
                                   *version_ui::GetVariationsList());
}


text:
package com.imaginea.activegrid.core.models

import com.imaginea.activegrid.core.utils.ActiveGridUtils
import org.neo4j.graphdb.Node
import org.slf4j.LoggerFactory

/**
  * Created by nagulmeeras on 31/10/16.
  */
case class ReservedInstanceDetails(override val id: Option[Long],
                                   instanceType: Option[String],
                                   reservedInstancesId: Option[String],
                                   availabilityZone: Option[String],
                                   tenancy: Option[String],
                                   offeringType: Option[String],
                                   productDescription: Option[String],
                                   count: Option[Int]) extends BaseEntity

object ReservedInstanceDetails {
  val reservedInstanceDetailsLabel = "ReservedInstanceDetails"
  val logger = LoggerFactory.getLogger(getClass)

  def fromNeo4jGraph(nodeId: Long): Option[ReservedInstanceDetails] = {
    val mayBeNode = Neo4jRepository.findNodeById(nodeId)
    mayBeNode match {
      case Some(node) =>
        if (Neo4jRepository.hasLabel(node, reservedInstanceDetailsLabel)) {
          val map = Neo4jRepository.getProperties(node, "instanceType", "reservedInstancesId", "availabilityZone", "tenancy",
            "offeringType", "productDescription", "count")

          Some(ReservedInstanceDetails(Some(nodeId),
            ActiveGridUtils.getValueFromMapAs[String](map, "instanceType"),
            ActiveGridUtils.getValueFromMapAs[String](map, "reservedInstancesId"),
            ActiveGridUtils.getValueFromMapAs[String](map, "availabilityZone"),
            ActiveGridUtils.getValueFromMapAs[String](map, "tenancy"),
            ActiveGridUtils.getValueFromMapAs[String](map, "offeringType"),
            ActiveGridUtils.getValueFromMapAs[String](map, "productDescription"),
            ActiveGridUtils.getValueFromMapAs[Int](map, "count")))
        } else {
          None
        }
      case None => None
    }
  }

  implicit class ReservedInstanceDetailsImpl(reservedInstanceDetails: ReservedInstanceDetails)
    extends Neo4jRep[ReservedInstanceDetails] {

    override def toNeo4jGraph(entity: ReservedInstanceDetails): Node = {
      val map = Map("instanceType" -> entity.instanceType,
        "reservedInstancesId" -> entity.reservedInstancesId,
        "availabilityZone" -> entity.availabilityZone,
        "tenancy" -> entity.tenancy,
        "offeringType" -> entity.offeringType,
        "productDescription" -> entity.productDescription,
        "count" -> entity.count)
      Neo4jRepository.saveEntity[ReservedInstanceDetails](reservedInstanceDetailsLabel, entity.id, map)
    }

    override def fromNeo4jGraph(nodeId: Long): Option[ReservedInstanceDetails] = {
      ReservedInstanceDetails.fromNeo4jGraph(nodeId)
    }
  }

}


text:
package com.ripariandata.timberwolf.mail.exchange;

import com.microsoft.schemas.exchange.services.x2006.messages.CreateFolderResponseType;
import com.microsoft.schemas.exchange.services.x2006.messages.CreateFolderType;
import com.microsoft.schemas.exchange.services.x2006.messages.CreateItemType;
import com.microsoft.schemas.exchange.services.x2006.messages.DeleteFolderType;
import com.microsoft.schemas.exchange.services.x2006.messages.DeleteItemType;
import com.microsoft.schemas.exchange.services.x2006.messages.FindItemResponseMessageType;
import com.microsoft.schemas.exchange.services.x2006.messages.FindItemType;
import com.microsoft.schemas.exchange.services.x2006.messages.FolderInfoResponseMessageType;
import com.microsoft.schemas.exchange.services.x2006.messages.ItemInfoResponseMessageType;
import com.microsoft.schemas.exchange.services.x2006.messages.MoveItemType;
import com.microsoft.schemas.exchange.services.x2006.messages.ResponseCodeType;
import com.microsoft.schemas.exchange.services.x2006.messages.ResponseMessageType;
import com.microsoft.schemas.exchange.services.x2006.types.BodyTypeType;
import com.microsoft.schemas.exchange.services.x2006.types.DefaultShapeNamesType;
import com.microsoft.schemas.exchange.services.x2006.types.DisposalType;
import com.microsoft.schemas.exchange.services.x2006.types.DistinguishedFolderIdNameType;
import com.microsoft.schemas.exchange.services.x2006.types.FolderType;
import com.microsoft.schemas.exchange.services.x2006.types.ItemIdType;
import com.microsoft.schemas.exchange.services.x2006.types.ItemQueryTraversalType;
import com.microsoft.schemas.exchange.services.x2006.types.ItemResponseShapeType;
import com.microsoft.schemas.exchange.services.x2006.types.MessageDispositionType;
import com.microsoft.schemas.exchange.services.x2006.types.MessageType;
import com.microsoft.schemas.exchange.services.x2006.types.NonEmptyArrayOfAllItemsType;
import com.microsoft.schemas.exchange.services.x2006.types.NonEmptyArrayOfBaseFolderIdsType;
import com.microsoft.schemas.exchange.services.x2006.types.NonEmptyArrayOfBaseItemIdsType;
import com.microsoft.schemas.exchange.services.x2006.types.NonEmptyArrayOfFoldersType;
import com.microsoft.schemas.exchange.services.x2006.types.TargetFolderIdType;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlsoap.schemas.soap.envelope.BodyType;
import org.xmlsoap.schemas.soap.envelope.EnvelopeDocument;
import org.xmlsoap.schemas.soap.envelope.EnvelopeType;

/**
 * This class puts a bunch of folders or emails into an account in exchange.
 * This should only be used by integration tests.
 */
public class ExchangePump
{

    private static final Logger LOG = LoggerFactory.getLogger(ExchangePump.class);
    private static final String DECLARATION = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    private static final String SOAP_ENCODING = "UTF-8";

    private String endpoint;
    private HttpUrlConnectionFactory connectionFactory = new SaslHttpUrlConnectionFactory();
    private String sender;

    public ExchangePump(final String exchangeUrl, final String senderEmail)
    {
        endpoint = exchangeUrl;
        sender = senderEmail;
    }

    private EnvelopeDocument createEmptyRequest(final String user)
    {
        EnvelopeDocument request = EnvelopeDocument.Factory.newInstance();
        EnvelopeType envelope = request.addNewEnvelope();
        envelope.addNewHeader().addNewExchangeImpersonation().addNewConnectingSID().setPrincipalName(user);
        return request;
    }

    /**
     * Tells Exchange to create all given 'folders' inside parentFolderId.
     * The request is performed as 'user'.
     * Will not create folders that already have ids.
     */
    private void createFolders(final String user, final TargetFolderIdType parentFolderId,
                               final String parentFolderName, final List<RequiredFolder> folders)
            throws FailedToCreateFolders
    {
        EnvelopeDocument request = createEmptyRequest(user);
        CreateFolderType createFolder = request.getEnvelope().addNewBody().addNewCreateFolder();
        createFolder.setParentFolderId(parentFolderId);
        NonEmptyArrayOfFoldersType requestedFolders = createFolder.addNewFolders();
        for (RequiredFolder folder : folders)
        {
            // Don't recreate folders that already exist
            if (folder.getId() == null)
            {
                LOG.debug("Creating folder: {}", folder.getName());
                requestedFolders.addNewFolder().setDisplayName(folder.getName());
            }
        }
        if (requestedFolders.sizeOfFolderArray() == 0)
        {
            LOG.debug("All requested folders were already created.");
            return;
        }
        CreateFolderResponseType response = sendRequest(request).getCreateFolderResponse();
        FolderInfoResponseMessageType[] array = response.getResponseMessages().getCreateFolderResponseMessageArray();
        int i = 0;
        for (FolderInfoResponseMessageType folderResponse : array)
        {
            for (FolderType folder : folderResponse.getFolders().getFolderArray())
            {
                while (folders.get(i).getId() != null)
                {
                    i++;
                }
                folders.get(i).setId(folder.getFolderId().getId());
                i++;
            }
        }
        if (i < folders.size())
        {
            LOG.error("Failed to create all folders for user: {}", user);
            LOG.error("Requested Folders in {}:", parentFolderName);
            for (RequiredFolder folder : folders)
            {
                LOG.error("  {}", folder.getName());
            }
            throw new FailedToCreateFolders(
                    "Failed to create all folders, perhaps some existed before running the test");
        }
    }

    public void createFolders(final String user, final String parent, final List<RequiredFolder> folders)
            throws FailedToCreateFolders
    {
        TargetFolderIdType parentFolder = TargetFolderIdType.Factory.newInstance();
        parentFolder.addNewFolderId().setId(parent);
        createFolders(user, parentFolder, parent, folders);
    }

    public void createFolders(final String user, final DistinguishedFolderIdNameType.Enum parent,
                              final List<RequiredFolder> folders) throws FailedToCreateFolders
    {
        TargetFolderIdType parentFolder = TargetFolderIdType.Factory.newInstance();
        parentFolder.addNewDistinguishedFolderId().setId(parent);
        createFolders(user, parentFolder, parent.toString(), folders);
    }

    public void deleteFolders(final String user, final List<RequiredFolder> folders) throws FailedToDeleteMessage
    {
        EnvelopeDocument request = createEmptyRequest(user);
        DeleteFolderType deleteFolder = request.getEnvelope().addNewBody().addNewDeleteFolder();
        deleteFolder.setDeleteType(DisposalType.HARD_DELETE);
        NonEmptyArrayOfBaseFolderIdsType doomedFolders = deleteFolder.addNewFolderIds();

        for (RequiredFolder folder : folders)
        {
            final String folderId = folder.getId();
            if (folderId != null && folderId.length() > 0)
            {
                doomedFolders.addNewFolderId().setId(folderId);
                LOG.debug("Preparing to delete folder: {}", folderId);
            }
        }
        BodyType response = sendRequest(request);
        ResponseMessageType[] responses =
                response.getDeleteFolderResponse().getResponseMessages().getDeleteFolderResponseMessageArray();
        for (ResponseMessageType resp : responses)
        {
            if (resp.getResponseCode() != ResponseCodeType.NO_ERROR)
            {
                LOG.debug(response.toString());
                throw new FailedToDeleteMessage(
                        "ResponseCode some sort of error: " + resp.getResponseCode());
            }
        }
    }

    public void deleteEmails(final String user, final List<MessageId> emails) throws FailedToDeleteMessage
    {
        EnvelopeDocument request = createEmptyRequest(user);
        DeleteItemType deleteItem = request.getEnvelope().addNewBody().addNewDeleteItem();
        deleteItem.setDeleteType(DisposalType.HARD_DELETE);
        NonEmptyArrayOfBaseItemIdsType doomedItems = deleteItem.addNewItemIds();
        for (MessageId email : emails)
        {
            String emailId = email.getId();
            doomedItems.addNewItemId().setId(emailId);
            LOG.debug("Preparing to delete email item: {}", emailId);
        }
        BodyType response = sendRequest(request);
        ResponseMessageType[] responses =
                response.getDeleteItemResponse().getResponseMessages().getDeleteItemResponseMessageArray();
        for (ResponseMessageType resp : responses)
        {
            if (resp.getResponseCode() != ResponseCodeType.NO_ERROR)
            {
                LOG.debug(response.toString());
                throw new FailedToDeleteMessage(
                        "ResponseCode some sort of error: " + resp.getResponseCode());
            }
        }
    }

    private void createEmails(final List<RequiredEmail> emails, final EnvelopeDocument request,
                              final NonEmptyArrayOfAllItemsType emptyItemsType)
            throws FailedToCreateMessage
    {
        for (RequiredEmail email : emails)
        {
            MessageType exchangeMessage = emptyItemsType.addNewMessage();
            exchangeMessage.addNewFrom().addNewMailbox().setEmailAddress(sender);
            com.microsoft.schemas.exchange.services.x2006.types.BodyType body = exchangeMessage.addNewBody();
            body.setBodyType(BodyTypeType.TEXT);
            body.setStringValue(email.getBody());
            exchangeMessage.setSubject(email.getSubject());
            exchangeMessage.addNewToRecipients().addNewMailbox().setEmailAddress(email.getTo());
            if (email.getCc() != null)
            {
                exchangeMessage.addNewCcRecipients().addNewMailbox().setEmailAddress(email.getCc());
            }
            if (email.getBcc() != null)
            {
                exchangeMessage.addNewBccRecipients().addNewMailbox().setEmailAddress(email.getBcc());
            }
        }
        BodyType response = sendRequest(request);
        ItemInfoResponseMessageType[] responses =
                response.getCreateItemResponse().getResponseMessages().getCreateItemResponseMessageArray();
        if (responses.length != emails.size())
        {
            LOG.debug(response.toString());
            throw new FailedToCreateMessage(
                    "There should have been " + emails.size() + " response message to createItem");
        }
        for (ItemInfoResponseMessageType resp : responses)
        {
            if (resp.getResponseCode() != ResponseCodeType.NO_ERROR)
            {
                LOG.debug(response.toString());
                throw new FailedToCreateMessage(
                        "ResponseCode some sort of error: " + resp.getResponseCode());
            }
        }
    }

    public void sendMessages(final List<RequiredEmail> emails) throws FailedToCreateMessage
    {
        EnvelopeDocument request = createEmptyRequest(sender);
        CreateItemType createItem = request.getEnvelope().addNewBody().addNewCreateItem();
        createItem.setMessageDisposition(MessageDispositionType.SEND_ONLY);
        NonEmptyArrayOfAllItemsType items = createItem.addNewItems();

        createEmails(emails, request, items);
    }

    public void saveDrafts(final String user, final List<RequiredEmail> drafts) throws FailedToCreateMessage
    {
        EnvelopeDocument request = createEmptyRequest(user);
        CreateItemType createItem = request.getEnvelope().addNewBody().addNewCreateItem();
        createItem.addNewSavedItemFolderId().addNewDistinguishedFolderId().setId(DistinguishedFolderIdNameType.DRAFTS);
        createItem.setMessageDisposition(MessageDispositionType.SAVE_ONLY);
        NonEmptyArrayOfAllItemsType items = createItem.addNewItems();

        createEmails(drafts, request, items);
    }

    public void sendAndSave(final String user, final List<RequiredEmail> drafts) throws FailedToCreateMessage
    {
        EnvelopeDocument request = createEmptyRequest(user);
        CreateItemType createItem = request.getEnvelope().addNewBody().addNewCreateItem();
        createItem.addNewSavedItemFolderId().addNewDistinguishedFolderId()
                  .setId(DistinguishedFolderIdNameType.SENTITEMS);
        createItem.setMessageDisposition(MessageDispositionType.SEND_AND_SAVE_COPY);
        NonEmptyArrayOfAllItemsType items = createItem.addNewItems();

        createEmails(drafts, request, items);
    }

    public HashMap<String, List<MessageId>> findItems(final String user,
                                                      final DistinguishedFolderIdNameType.Enum parent)
            throws FailedToFindMessage
    {
        HashMap<String, List<MessageId>> emailResults = new HashMap<String, List<MessageId>>();
        EnvelopeDocument request = createEmptyRequest(user);
        FindItemType findItem = request.getEnvelope().addNewBody().addNewFindItem();
        findItem.setTraversal(ItemQueryTraversalType.SHALLOW);
        ItemResponseShapeType itemShape = findItem.addNewItemShape();
        itemShape.setBaseShape(DefaultShapeNamesType.DEFAULT);
        // I tried to use ID_ONLY and add some AdditionalProperties, but the
        // schema appears to be screwy and not have FieldURI in there correctly
        findItem.addNewParentFolderIds().addNewDistinguishedFolderId().setId(parent);
        BodyType response = sendRequest(request);
        FindItemResponseMessageType responseMessage =
                response.getFindItemResponse().getResponseMessages().getFindItemResponseMessageArray()[0];
        if (responseMessage.getResponseCode() != ResponseCodeType.NO_ERROR)
        {
            throw new FailedToFindMessage(
                    "ResponseCode some sort of error: " + responseMessage.getResponseCode());
        }
        for (MessageType email : responseMessage.getRootFolder().getItems().getMessageArray())
        {
            String folderId = RequiredEmail.getFolderId(email.getSubject());
            if (folderId != null)
            {
                List<MessageId> emails = emailResults.get(folderId);
                if (emails == null)
                {
                    emails = new ArrayList<MessageId>();
                    emailResults.put(folderId, emails);
                }
                emails.add(new MessageId(email.getItemId().getId(), email.getItemId().getChangeKey()));
            }
        }
        return emailResults;
    }

    private void moveMessages(final String user, final TargetFolderIdType targetFolderId,
                              final List<MessageId> messageIds) throws FailedToMoveMessage
    {
        EnvelopeDocument request = createEmptyRequest(user);
        MoveItemType moveItem = request.getEnvelope().addNewBody().addNewMoveItem();
        moveItem.setToFolderId(targetFolderId);
        NonEmptyArrayOfBaseItemIdsType itemIds = moveItem.addNewItemIds();
        for (MessageId messageId : messageIds)
        {
            ItemIdType itemId = itemIds.addNewItemId();
            itemId.setId(messageId.getId());
            itemId.setChangeKey(messageId.getChangeKey());
        }
        BodyType response = sendRequest(request);
        ItemInfoResponseMessageType[] responses =
                response.getMoveItemResponse().getResponseMessages().getMoveItemResponseMessageArray();
        if (responses.length != messageIds.size())
        {
            throw new FailedToMoveMessage("There should have been 1 response message to moveItem");
        }

        for (ItemInfoResponseMessageType resp : responses)
        {
            if (resp.getResponseCode() != ResponseCodeType.NO_ERROR)
            {
                throw new FailedToMoveMessage("ResponseCode some sort of error: " + resp.getResponseCode());
            }
        }
    }

    public void moveMessages(final String user, final String folder, final List<MessageId> messageIds)
            throws FailedToMoveMessage
    {
        TargetFolderIdType targetFolderId = TargetFolderIdType.Factory.newInstance();
        targetFolderId.addNewFolderId().setId(folder);
        moveMessages(user, targetFolderId, messageIds);
    }

    public void moveMessages(final String user, final DistinguishedFolderIdNameType.Enum distinguishedFolder,
                             final List<MessageId> messageIds) throws FailedToMoveMessage
    {
        TargetFolderIdType targetFolderId = TargetFolderIdType.Factory.newInstance();
        targetFolderId.addNewDistinguishedFolderId().setId(distinguishedFolder);
        moveMessages(user, targetFolderId, messageIds);
    }

    private BodyType sendRequest(final EnvelopeDocument envelope) throws SendRequestFailed
    {
        String request = DECLARATION + envelope.xmlText();

        LOG.trace("Sending SOAP request to {}.  SOAP envelope:", endpoint);
        LOG.trace(envelope.toString());

        try
        {
            HttpURLConnection conn = connectionFactory.newInstance(endpoint, request.getBytes(SOAP_ENCODING));

            int code = conn.getResponseCode();

            InputStream responseData = conn.getInputStream();

            int amtAvailable = responseData.available();

            if (code == HttpURLConnection.HTTP_OK)
            {
                EnvelopeDocument response = EnvelopeDocument.Factory.parse(responseData);

                LOG.trace("SOAP response received from {}.  SOAP envelope:", endpoint);
                LOG.trace(response.toString());

                return response.getEnvelope().getBody();
            }
            else
            {
                LOG.debug("HTTP Error: {}", code);
                throw new HttpErrorException(code);
            }
        }
        catch (Exception e)
        {
            throw new SendRequestFailed("Unexpected Exception: " + e.getMessage(), e);
        }

    }

    /** Exception for when sending a request to exchange fails. */
    public class SendRequestFailed extends RuntimeException
    {
        public SendRequestFailed(final String message, final Throwable cause)
        {
            super(message, cause);
        }
    }

    /** Exception for when creating folders fails. */
    public class FailedToCreateFolders extends Exception
    {
        public FailedToCreateFolders(final String message)
        {
            super(message);
        }
    }

    /** Exception for when creating messages fails. */
    public class FailedToCreateMessage extends Exception
    {
        public FailedToCreateMessage(final String message)
        {
            super(message);
        }
    }

    /** Exception for when deleting messages fails. */
    public class FailedToDeleteMessage extends Exception
    {
        public FailedToDeleteMessage(final String message)
        {
            super(message);
        }
    }

    /** Exception for when finding messages fails. */
    public class FailedToFindMessage extends Exception
    {
        public FailedToFindMessage(final String message)
        {
            super(message);
        }
    }

    /** Exception for when moving messages fails. */
    public class FailedToMoveMessage extends Exception
    {
        public FailedToMoveMessage(final String message)
        {
            super(message);
        }
    }

    /** A simple class representing an email. */
    public final class MessageId
    {
        private final String id;
        private final String changeKey;

        private MessageId(final String messageId, final String messageChangeKey)
        {
            id = messageId;
            changeKey = messageChangeKey;
        }

        private String getId()
        {
            return id;
        }

        private String getChangeKey()
        {
            return changeKey;
        }

        @Override
        public String toString()
        {
            return "MessageId{"
                   + "id='" + id + '\''
                   + ", changeKey='" + changeKey + '\''
                   + '}';
        }
    }
}


text:
// Code generated by lister-gen. DO NOT EDIT.

package v1beta1

import (
	v1beta1 "k8s.io/api/apps/v1beta1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
)

// ControllerRevisionLister helps list ControllerRevisions.
type ControllerRevisionLister interface {
	// List lists all ControllerRevisions in the indexer.
	List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error)
	// ControllerRevisions returns an object that can list and get ControllerRevisions.
	ControllerRevisions(namespace string) ControllerRevisionNamespaceLister
	ControllerRevisionListerExpansion
}

// controllerRevisionLister implements the ControllerRevisionLister interface.
type controllerRevisionLister struct {
	indexer cache.Indexer
}

// NewControllerRevisionLister returns a new ControllerRevisionLister.
func NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister {
	return &controllerRevisionLister{indexer: indexer}
}

// List lists all ControllerRevisions in the indexer.
func (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*v1beta1.ControllerRevision))
	})
	return ret, err
}

// ControllerRevisions returns an object that can list and get ControllerRevisions.
func (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister {
	return controllerRevisionNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// ControllerRevisionNamespaceLister helps list and get ControllerRevisions.
type ControllerRevisionNamespaceLister interface {
	// List lists all ControllerRevisions in the indexer for a given namespace.
	List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error)
	// Get retrieves the ControllerRevision from the indexer for a given namespace and name.
	Get(name string) (*v1beta1.ControllerRevision, error)
	ControllerRevisionNamespaceListerExpansion
}

// controllerRevisionNamespaceLister implements the ControllerRevisionNamespaceLister
// interface.
type controllerRevisionNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all ControllerRevisions in the indexer for a given namespace.
func (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1beta1.ControllerRevision))
	})
	return ret, err
}

// Get retrieves the ControllerRevision from the indexer for a given namespace and name.
func (s controllerRevisionNamespaceLister) Get(name string) (*v1beta1.ControllerRevision, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1beta1.Resource("controllerrevision"), name)
	}
	return obj.(*v1beta1.ControllerRevision), nil
}


text:
var App = require('app');
var stringUtils = require('utils/string_utils');

App.componentsStateMapper = App.QuickDataMapper.create({

  model: App.Service,

  clientModel: App.ClientComponent,
  clientMap: {
    id: 'ServiceComponentInfo.component_name',
    service_id: 'ServiceComponentInfo.service_name',
    stack_info_id: 'ServiceComponentInfo.component_name',
    component_name: 'ServiceComponentInfo.component_name',
    display_name: 'ServiceComponentInfo.display_name',
    service_name: 'ServiceComponentInfo.service_name',
    installed_count: 'ServiceComponentInfo.installed_count',
    install_failed_count: 'ServiceComponentInfo.install_failed_count',
    init_count: 'ServiceComponentInfo.init_count',
    unknown_count: 'ServiceComponentInfo.unknown_count',
    started_count: 'ServiceComponentInfo.started_count',
    total_count: 'ServiceComponentInfo.total_count',
    host_names: 'host_names',
    stale_config_hosts: 'stale_config_hosts'
  },

  slaveModel: App.SlaveComponent,
  masterModel: App.MasterComponent,

  paths: {
    INSTALLED_PATH: 'ServiceComponentInfo.installed_count',
    INSTALL_FAILED_PATH: 'ServiceComponentInfo.install_failed_count',
    INIT_PATH: 'ServiceComponentInfo.init_count',
    UNKNOWN_PATH: 'ServiceComponentInfo.unknown_count',
    STARTED_PATH: 'ServiceComponentInfo.started_count',
    TOTAL_PATH: 'ServiceComponentInfo.total_count'
  },
  configMap: {
    'DATANODE': {
      data_nodes_started: 'STARTED_PATH',
      data_nodes_installed: 'INSTALLED_PATH',
      data_nodes_total: 'TOTAL_PATH'
    },
    'NFS_GATEWAY': {
      nfs_gateways_started: 'STARTED_PATH',
      nfs_gateways_installed: 'INSTALLED_PATH',
      nfs_gateways_total: 'TOTAL_PATH'
    },
    'NODEMANAGER': {
      node_managers_started: 'STARTED_PATH',
      node_managers_installed: 'INSTALLED_PATH',
      node_managers_total: 'TOTAL_PATH'
    },
    'HAWQSEGMENT': {
      hawq_segments_started: 'STARTED_PATH',
      hawq_segments_installed: 'INSTALLED_PATH',
      hawq_segments_total: 'TOTAL_PATH'
    },
    'PXF': {
      pxfs_started: 'STARTED_PATH',
      pxfs_installed: 'INSTALLED_PATH',
      pxfs_total: 'TOTAL_PATH'
    },
    'HBASE_REGIONSERVER': {
      region_servers_started: 'STARTED_PATH',
      region_servers_installed: 'INSTALLED_PATH',
      region_servers_total: 'TOTAL_PATH'
    },
    'HBASE_REST_SERVER': {
      rest_servers_started: 'STARTED_PATH',
      rest_servers_installed: 'INSTALLED_PATH',
      rest_servers_total: 'TOTAL_PATH'
    },
    'PHOENIX_QUERY_SERVER': {
      phoenix_servers_started: 'STARTED_PATH',
      phoenix_servers_installed: 'INSTALLED_PATH',
      phoenix_servers_total: 'TOTAL_PATH'
    },
    'GANGLIA_MONITOR': {
      ganglia_monitors_started: 'STARTED_PATH',
      ganglia_monitors_installed: 'INSTALLED_PATH',
      ganglia_monitors_total: 'TOTAL_PATH'
    },
    'SUPERVISOR': {
      super_visors_started: 'STARTED_PATH',
      super_visors_installed: 'INSTALLED_PATH',
      super_visors_total: 'TOTAL_PATH'
    },
    'RANGER_TAGSYNC': {
      ranger_tagsyncs_started: 'STARTED_PATH',
      ranger_tagsyncs_installed: 'INSTALLED_PATH',
      ranger_tagsyncs_total: 'TOTAL_PATH'
    },
    'MAPREDUCE2_CLIENT': {
      map_reduce2_clients: 'INSTALLED_PATH'
    },
    'TEZ_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'HIVE_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'FALCON_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'OOZIE_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'ZOOKEEPER_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'PIG': {
      installed_clients: 'INSTALLED_PATH'
    },
    'SQOOP': {
      installed_clients: 'INSTALLED_PATH'
    },
    'YARN_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'HDFS_CLIENT': {
      installed_clients: 'INSTALLED_PATH'
    },
    'FLUME_HANDLER': {
      flume_handlers_total: 'TOTAL_PATH'
    }
  },
  /**
   * get formatted component config
   * @param componentName
   * @return {Object}
   */
  getComponentConfig: function (componentName) {
    var config = {};
    var componentConfig = this.get('configMap')[componentName];
    var paths = this.get('paths');

    for (var property in componentConfig) {
      if (paths[componentConfig[property]]) {
        config[property] = paths[componentConfig[property]];
      }
    }
    return config;
  },
  /**
   * get service extended model if it has one
   * @param serviceName
   * @return {Object|null}
   */
  getExtendedModel: function (serviceName) {
    if (App[App.Service.extendedModel[serviceName]]) {
      return App[App.Service.extendedModel[serviceName]].find(serviceName);
    }
    return null;
  },

  map: function (json) {
    console.time('App.componentsStateMapper execution time');

    var clients = [];
    var slaves = [];
    var masters = [];
    var hasNewComponents = false;
    var staleConfigHostsMap = App.cache.staleConfigsComponentHosts;

    if (json.items) {
      if (!App.isEmptyObject(Em.getWithDefault(App, 'cache.services', {}))) {
        hasNewComponents = json.items.mapProperty('ServiceComponentInfo.total_count').reduce(Em.sum, 0) >
          App.cache.services.mapProperty('host_components.length').reduce(Em.sum, 0);
      }
      json.items.forEach(function (item) {
        var componentConfig = this.getComponentConfig(item.ServiceComponentInfo.component_name);
        var parsedItem = this.parseIt(item, componentConfig);
        var service = App.Service.find(item.ServiceComponentInfo.service_name);
        var extendedModel = this.getExtendedModel(item.ServiceComponentInfo.service_name);
        var cacheService = App.cache['services'].findProperty('ServiceInfo.service_name', item.ServiceComponentInfo.service_name);

        item.stale_config_hosts = staleConfigHostsMap[item.ServiceComponentInfo.component_name] || [];
        if (item.ServiceComponentInfo.category === 'CLIENT') {
          item.host_names = item.host_components.mapProperty('HostRoles.host_name');
          clients.push(this.parseIt(item, this.clientMap));
        } else if (item.ServiceComponentInfo.category === 'SLAVE') {
          // for now map for slaves and clients are equal but it may vary in future.
          item.host_names = item.host_components.mapProperty('HostRoles.host_name');
          slaves.push(this.parseIt(item, this.clientMap));
        } else if (item.ServiceComponentInfo.category === 'MASTER') {
          item.host_names = item.host_components.mapProperty('HostRoles.host_name');
          masters.push(this.parseIt(item, this.clientMap));
        }
        if (cacheService) {
          cacheService.client_components = clients.filterProperty('service_name', cacheService.ServiceInfo.service_name).mapProperty('component_name');
          cacheService.slave_components = slaves.filterProperty('service_name', cacheService.ServiceInfo.service_name).mapProperty('component_name');
          cacheService.master_components = masters.filterProperty('service_name', cacheService.ServiceInfo.service_name).mapProperty('component_name');
          for (var i in parsedItem) {
            if (service.get('isLoaded')) {
              cacheService[i] = parsedItem[i];
              service.set(stringUtils.underScoreToCamelCase(i), parsedItem[i]);
              if (extendedModel && extendedModel.get('isLoaded')) {
                extendedModel.set(stringUtils.underScoreToCamelCase(i), parsedItem[i]);
              }
            }
          }
        }
      }, this);
    }
    App.store.safeLoadMany(this.clientModel, clients);
    App.store.safeLoadMany(this.slaveModel, slaves);
    App.store.safeLoadMany(this.masterModel, masters);

    if (hasNewComponents) {
      App.get('router.clusterController').triggerQuickLinksUpdate();
    }

    console.timeEnd('App.componentsStateMapper execution time');
  }
});


text:
#ifndef __PU_PARTICLE_EVENT_HANDLER_TOKENS_H__
#define __PU_PARTICLE_EVENT_HANDLER_TOKENS_H__

#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseEventHandler.h"
#include "ParticleUniverseScriptDeserializer.h"

namespace ParticleUniverse
{
	/** The ParticleEventHandlerTranslator parses 'ParticleEventHandler' tokens
	*/
	class _ParticleUniverseExport ParticleEventHandlerTranslator : public ScriptTranslator
	{
		protected:
			ParticleEventHandler* mParticleEventHandler;

		public:
			ParticleEventHandlerTranslator(void);
			virtual ~ParticleEventHandlerTranslator(void){};
			virtual void translate(ScriptCompiler* compiler, const AbstractNodePtr &node);
	};
	//-------------------------------------------------------------------------
	//-------------------------------------------------------------------------
	//-------------------------------------------------------------------------

	/**
    */
	class _ParticleUniverseExport ParticleEventHandlerWriter : public ScriptWriter
	{
		public:

			ParticleEventHandlerWriter(void) {};
			virtual ~ParticleEventHandlerWriter(void) {};

			/** @see
				ScriptWriter::write
			*/
			virtual void write(ParticleScriptSerializer* serializer, const IElement* element);
	};

}
#endif


text:
package org.springframework.boot.context.properties.bind;

/**
 * Java bean with an additional public single-arg constructor.
 *
 * @author Phillip Webb
 */
public class JavaBeanWithPublicConstructor {

	private String value;

	public JavaBeanWithPublicConstructor() {
	}

	public JavaBeanWithPublicConstructor(String value) {
		setValue(value);
	}

	public String getValue() {
		return this.value;
	}

	public void setValue(String value) {
		this.value = value;
	}

}


text:
namespace dukat
{
	class Ray2;
	class Vector2;

	class BoundingBody2
	{
	public:
		BoundingBody2(void) { }
		virtual ~BoundingBody2(void) { }

		// Containment / Intersection tests
		virtual bool contains(const Vector2& p) const = 0;
		// Checks if body intersects circle.
		virtual bool intersect_circle(const Vector2& center, float radius) const = 0;
		// Checks if body intersects ray. Will return the distance along intersection ray or no_intersection.
		virtual float intersect_ray(const Ray2& ray, float near, float far) const = 0;
	};
}


text:
<?php

namespace TomPHP\PatchBuilder\Types\Exception;

class InvalidLineNumberException extends \RangeException
{
}


text:
export class Rule extends Lint.Rules.AbstractRule {
    public static FAILURE_STRING = "forbidden internal module";

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new NoInternalModuleWalker(sourceFile, this.getOptions()));
    }
}

class NoInternalModuleWalker extends Lint.RuleWalker {
    public visitModuleDeclaration(node: ts.ModuleDeclaration) {
        if (Lint.isNodeFlagSet(node, ts.NodeFlags.Namespace)) {
            // ok namespace
        } else if (node.name.kind === ts.SyntaxKind.Identifier) {
            // for external modules, node.name will be a LiteralExpression instead of Identifier
            this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
        }
        super.visitModuleDeclaration(node);
    }
}


text:
package kafka

import (
	"bytes"
	"fmt"
	"net"
	"strconv"
	"sync"
	"time"

	"github.com/optiopay/kafka/v2/proto"
)

const (
	AnyRequest = -1
)

type Serializable interface {
	Bytes() ([]byte, error)
}

type RequestHandler func(request Serializable) (response Serializable)

type Server struct {
	Processed int

	mu       sync.RWMutex
	ln       net.Listener
	clients  map[int64]net.Conn
	handlers map[int16]RequestHandler
}

func NewServer() *Server {
	srv := &Server{
		clients:  make(map[int64]net.Conn),
		handlers: make(map[int16]RequestHandler),
	}
	srv.handlers[AnyRequest] = srv.defaultRequestHandler
	return srv
}

// Handle registers handler for given message kind. Handler registered with
// AnyRequest kind will be used only if there is no precise handler for the
// kind.
func (srv *Server) Handle(reqKind int16, handler RequestHandler) {
	srv.mu.Lock()
	srv.handlers[reqKind] = handler
	srv.mu.Unlock()
}

func (srv *Server) Address() string {
	return srv.ln.Addr().String()
}

func (srv *Server) HostPort() (string, int) {
	host, sport, err := net.SplitHostPort(srv.ln.Addr().String())
	if err != nil {
		panic(fmt.Sprintf("cannot split server address: %s", err))
	}
	port, err := strconv.Atoi(sport)
	if err != nil {
		panic(fmt.Sprintf("port '%s' is not a number: %s", sport, err))
	}
	if host == "" {
		host = "localhost"
	}
	return host, port
}

func (srv *Server) Start() {
	srv.mu.Lock()
	defer srv.mu.Unlock()

	if srv.ln != nil {
		panic("server already started")
	}
	ln, err := net.Listen("tcp4", "")
	if err != nil {
		panic(fmt.Sprintf("cannot start server: %s", err))
	}
	srv.ln = ln

	go func() {
		for {
			client, err := ln.Accept()
			if err != nil {
				return
			}
			go srv.handleClient(client)
		}
	}()
}

func (srv *Server) Close() {
	srv.mu.Lock()
	_ = srv.ln.Close()
	for _, cli := range srv.clients {
		_ = cli.Close()
	}
	srv.clients = make(map[int64]net.Conn)
	srv.mu.Unlock()
}

func (srv *Server) handleClient(c net.Conn) {
	clientID := time.Now().UnixNano()
	srv.mu.Lock()
	srv.clients[clientID] = c
	srv.mu.Unlock()

	defer func() {
		srv.mu.Lock()
		delete(srv.clients, clientID)
		srv.mu.Unlock()
	}()

	for {
		kind, b, err := proto.ReadReq(c)
		if err != nil {
			return
		}
		srv.mu.RLock()
		fn, ok := srv.handlers[kind]
		if !ok {
			fn, ok = srv.handlers[AnyRequest]
		}
		srv.mu.RUnlock()

		if !ok {
			panic(fmt.Sprintf("no handler for %d", kind))
		}

		var request Serializable

		switch kind {
		case proto.FetchReqKind:
			request, err = proto.ReadFetchReq(bytes.NewBuffer(b))
		case proto.ProduceReqKind:
			request, err = proto.ReadProduceReq(bytes.NewBuffer(b))
		case proto.OffsetReqKind:
			request, err = proto.ReadOffsetReq(bytes.NewBuffer(b))
		case proto.MetadataReqKind:
			request, err = proto.ReadMetadataReq(bytes.NewBuffer(b))
		case proto.ConsumerMetadataReqKind:
			request, err = proto.ReadConsumerMetadataReq(bytes.NewBuffer(b))
		case proto.OffsetCommitReqKind:
			request, err = proto.ReadOffsetCommitReq(bytes.NewBuffer(b))
		case proto.OffsetFetchReqKind:
			request, err = proto.ReadOffsetFetchReq(bytes.NewBuffer(b))
		case proto.APIVersionsReqKind:
			request, err = proto.ReadAPIVersionsReq(bytes.NewBuffer(b))
		}

		if err != nil {
			panic(fmt.Sprintf("could not read message %d: %s", kind, err))
		}

		response := fn(request)
		if response != nil {
			b, err := response.Bytes()
			if err != nil {
				panic(fmt.Sprintf("cannot serialize %T: %s", response, err))
			}
			if _, err := c.Write(b); err != nil {
				panic(fmt.Sprintf("cannot wirte to client: %s", err))
			}
		}
	}
}

func (srv *Server) defaultRequestHandler(request Serializable) Serializable {
	srv.mu.RLock()
	defer srv.mu.RUnlock()

	srv.Processed++

	switch req := request.(type) {
	case *proto.FetchReq:
		resp := &proto.FetchResp{
			CorrelationID: req.GetCorrelationID(),
			Topics:        make([]proto.FetchRespTopic, len(req.Topics)),
		}
		for ti, topic := range req.Topics {
			resp.Topics[ti] = proto.FetchRespTopic{
				Name:       topic.Name,
				Partitions: make([]proto.FetchRespPartition, len(topic.Partitions)),
			}
			for pi, part := range topic.Partitions {
				resp.Topics[ti].Partitions[pi] = proto.FetchRespPartition{
					ID:        part.ID,
					Err:       proto.ErrUnknownTopicOrPartition,
					TipOffset: -1,
					Messages:  []*proto.Message{},
				}
			}
		}
		return resp
	case *proto.ProduceReq:
		resp := &proto.ProduceResp{
			CorrelationID: req.GetCorrelationID(),
		}
		resp.Topics = make([]proto.ProduceRespTopic, len(req.Topics))
		for ti, topic := range req.Topics {
			resp.Topics[ti] = proto.ProduceRespTopic{
				Name:       topic.Name,
				Partitions: make([]proto.ProduceRespPartition, len(topic.Partitions)),
			}
			for pi, part := range topic.Partitions {
				resp.Topics[ti].Partitions[pi] = proto.ProduceRespPartition{
					ID:     part.ID,
					Err:    proto.ErrUnknownTopicOrPartition,
					Offset: -1,
				}
			}
		}
		return resp
	case *proto.OffsetReq:
		topics := make([]proto.OffsetRespTopic, len(req.Topics))
		for ti := range req.Topics {
			var topic = &topics[ti]
			topic.Name = req.Topics[ti].Name
			topic.Partitions = make([]proto.OffsetRespPartition, len(req.Topics[ti].Partitions))
			for pi := range topic.Partitions {
				var part = &topic.Partitions[pi]
				part.ID = req.Topics[ti].Partitions[pi].ID
				part.Err = proto.ErrUnknownTopicOrPartition
			}
		}

		return &proto.OffsetResp{
			CorrelationID: req.GetCorrelationID(),
			Topics:        topics,
		}
	case *proto.MetadataReq:
		host, sport, err := net.SplitHostPort(srv.ln.Addr().String())
		if err != nil {
			panic(fmt.Sprintf("cannot split server address: %s", err))
		}
		port, err := strconv.Atoi(sport)
		if err != nil {
			panic(fmt.Sprintf("port '%s' is not a number: %s", sport, err))
		}
		if host == "" {
			host = "localhost"
		}
		return &proto.MetadataResp{
			CorrelationID: req.GetCorrelationID(),
			Brokers: []proto.MetadataRespBroker{
				{NodeID: 1, Host: host, Port: int32(port)},
			},
			Topics: []proto.MetadataRespTopic{},
		}
	case *proto.ConsumerMetadataReq:
		panic("not implemented")
	case *proto.OffsetCommitReq:
		panic("not implemented")
	case *proto.OffsetFetchReq:
		panic("not implemented")
	case *proto.APIVersionsReq:
		return &proto.APIVersionsResp{
			CorrelationID: req.GetCorrelationID(),
			APIVersions: []proto.SupportedVersion{
				proto.SupportedVersion{APIKey: proto.ProduceReqKind, MinVersion: 0, MaxVersion: 0},
				proto.SupportedVersion{APIKey: proto.FetchReqKind, MinVersion: 0, MaxVersion: 0},
				proto.SupportedVersion{APIKey: proto.OffsetReqKind, MinVersion: 0, MaxVersion: 0},
				proto.SupportedVersion{APIKey: proto.MetadataReqKind, MinVersion: 0, MaxVersion: 0},
				proto.SupportedVersion{APIKey: proto.OffsetCommitReqKind, MinVersion: 0, MaxVersion: 0},
				proto.SupportedVersion{APIKey: proto.OffsetFetchReqKind, MinVersion: 0, MaxVersion: 0},
				proto.SupportedVersion{APIKey: proto.ConsumerMetadataReqKind, MinVersion: 0, MaxVersion: 0},
			},
		}
	default:
		panic(fmt.Sprintf("unknown message type: %T", req))
	}
}


text:
<?php

$errors		= array();  	// array to hold validation errors
$data 		= array(); 		// array to pass back data

// validate the variables ======================================================
foreach ($_POST as $key => $value) {
	if ( empty($value) ) {
		$errors[''.$key.''] = ''.$key.' is required.';
	}
}

// return a response ===========================================================
if ( !empty($errors) ) {
	// if there are items in our errors array, return those errors
	$data['success'] = false;
	$data['errors']  = $errors;
} else {
	// if there are no errors, return a message
	$data['success'] = true;
	$data['message'] = 'Thanks, we\'ve successfully received your test answers and will get back to you shortly.';
}

echo json_encode($data);


text:
import { VectorDrawableNodeRetriever as Retriever } from "../abstract_vector_drawable_node_retriever";
import { Context } from "../context";

export class VectorDrawableNodeRetriever extends Retriever {
  public mayRetrieveNode(ctx: Context): Element | null {
    const vdElement = document.body.childNodes.findVectorDrawbleElement();

    if (vdElement) {
      ctx.vecBase = document.body;
      return vdElement;
    } else {
      return null;
    }
  }
}


text:
/*
 * TODO
 * Add brief documentation about this file
 */

#ifndef UPS_TEMPLATE_H // TODO
#define UPS_TEMPLATE_H // TODO

#include "0root/root.h"

// TODO include c/c++ standard libraries
#include <ups/types.h>

// TODO include 3rd party headers
#include <json/json.h>

// TODO include public upscaledb headers
#include "ups/upscaledb.h"

// TODO include local headers, ordered by tier
// Always verify that a file of level N does not include headers > N!

#ifndef UPS_ROOT_H
#  error "root.h was not included"
#endif

namespace upscaledb {

struct Journal;
struct LocalEnv;

// Prefer struct over class
struct LocalEnvTest {
  LocalEnvTest(LocalEnv *env_)
    : env(env_), _journal(0) {
  }

  // Sets a new journal object
  void set_journal(Journal *journal);

  // NO leading underscore: public member. getters/setters are not
  // required
  LocalEnv *env;

  // leading underscore: "private" member
  Journal *_journal;
};

} // namespace upscaledb

#endif // UPS_TEMPLATE_H // TODO


text:
package org.apache.usergrid.persistence.actorsystem;

import akka.actor.ActorSelection;
import akka.actor.Address;
import akka.actor.UntypedActor;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent;
import akka.cluster.Member;
import akka.cluster.MemberStatus;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Once notified of nodes, sends unique propertyValue requests to ClusterSingletonRouter via it's local proxy.
 */
public class ClientActor extends UntypedActor {
    private static final Logger logger = LoggerFactory.getLogger( ClientActor.class );

    private final String name = RandomStringUtils.randomAlphanumeric( 4 );

    private final Set<Address>       nodes = new HashSet<>();
    private final Cluster            cluster = Cluster.get(getContext().system());
    private final Map<Class, String> routersByMessageType;

    private boolean ready = false;

    public ClientActor( Map<Class, String> routersByMessageType ) {
        this.routersByMessageType = routersByMessageType;
    }

    // subscribe to cluster changes, MemberEvent
    @Override
    public void preStart() {
        logger.debug("{} role {} address {}:{} starting up, subscribing to cluster events...", name,
            cluster.getSelfRoles().iterator().next(),
            cluster.readView().selfAddress().host(),
            cluster.readView().selfAddress().hostPort());
        cluster.subscribe(getSelf(), ClusterEvent.MemberEvent.class, ClusterEvent.ReachabilityEvent.class);
    }

    // re-subscribe when restart
    @Override
    public void postStop() {
        cluster.unsubscribe(getSelf());
    }

    @Override
    public void onReceive(Object message) {

        int startSize = nodes.size();

        String routerPath = routersByMessageType.get( message.getClass() );

        if ( routerPath != null && ready ) {

            // just pick any node, the ClusterSingletonRouter will do the consistent hash routing
            List<Address> nodesList = new ArrayList<>( nodes );
            Address address = nodesList.get( ThreadLocalRandom.current().nextInt( nodesList.size() ) );
            ActorSelection service = getContext().actorSelection( address + routerPath );
            service.tell( message, getSender() );

        } else if ( routerPath != null ) {

            logger.debug("{} responding with status unknown", name);
            getSender().tell( new ErrorResponse("ClientActor not ready"), getSender() );

        } else if ( message instanceof StatusRequest ) {
            if ( ready ) {
                getSender().tell( new StatusMessage( name, StatusMessage.Status.READY ), getSender() );
            } else {
                getSender().tell( new StatusMessage( name, StatusMessage.Status.INITIALIZING), getSender() );
            }
            return;

        } else {
            processAsClusterEvent( message );
        }

        if ( logger.isDebugEnabled() && startSize != nodes.size() ) {
            logger.debug( "{} now knows {} nodes", name, nodes.size() );
        }

        if (!nodes.isEmpty() && !ready) {
            logger.debug( name + " is ready" );
            ready = true;

        } else if (nodes.isEmpty() && ready) {
            ready = false;
        }
    }

    /**
     * Process messages about nodes up, down, reachable and unreachable.
     */
    private void processAsClusterEvent(Object message) {

        if (message instanceof ClusterEvent.CurrentClusterState) {
            ClusterEvent.CurrentClusterState state = (ClusterEvent.CurrentClusterState) message;
            nodes.clear();
            for (Member member : state.getMembers()) {
                if (member.hasRole("io") && member.status().equals( MemberStatus.up())) {
                    nodes.add(member.address());
                    logger.debug("RequestActor {} received cluster-state member-up for {}", name, member.address());
                }
            }

        } else if (message instanceof ClusterEvent.MemberUp) {
            ClusterEvent.MemberUp mUp = (ClusterEvent.MemberUp) message;
            if (mUp.member().hasRole("io")) {
                nodes.add( mUp.member().address() );
            }
            logger.debug("{} received member-up for {}", name, mUp.member().address());

        } else if (message instanceof ClusterEvent.MemberEvent) {
            ClusterEvent.MemberEvent other = (ClusterEvent.MemberEvent) message;
            nodes.remove(other.member().address());

        } else if (message instanceof ClusterEvent.UnreachableMember) {
            ClusterEvent.UnreachableMember unreachable = (ClusterEvent.UnreachableMember) message;
            nodes.remove(unreachable.member().address());
            logger.debug("{} received un-reachable for {}", name, unreachable.member().address());

        } else if (message instanceof ClusterEvent.ReachableMember) {
            ClusterEvent.ReachableMember reachable = (ClusterEvent.ReachableMember) message;
            if (reachable.member().hasRole("io")) {
                nodes.add( reachable.member().address() );
            }
            logger.debug("{} received reachable for {}", name, reachable.member().address());

        } else {
            logger.error("{}: unhandled message: {}", name, message.toString());
            unhandled(message);
        }
    }

    /**
     * RequestAction responds to StatusRequests.
     */
    public static class StatusRequest implements Serializable { }

    /**
     * RequestActor responds with, and some times unilaterally sends StatusMessages.
     */
    public static class StatusMessage implements Serializable {
        final String name;

        public Status getStatus() {
            return status;
        }

        public enum Status { INITIALIZING, READY }
        private final Status status;
        public StatusMessage(String name, Status status) {
            this.name = name;
            this.status = status;
        }
        public String getName() {
            return name;
        }
        public boolean isReady() {
            return status.equals( Status.READY );
        }
    }

    public static class ErrorResponse implements Serializable {
        private String message;
        public ErrorResponse( String message ) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

}


text:
<?php

namespace User;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Authentication\Storage;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

   public function getServiceConfig()
    {
        return array(
            'factories'=>array(
                    'User\Model\MyAuthStorage' => function($sm){
                        return new \User\Model\MyAuthStorage('tauth');
                    },

                    'AuthService' => function($sm) {
                                //My assumption, you've alredy set dbAdapter
                                //and has users table with columns : user_name and pass_word
                                //that password hashed with md5
						$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
			            $dbTableAuthAdapter  = new DbTableAuthAdapter($dbAdapter,'users','username','password','MD5(?)');
			            /*
			             * Advanced Usage By Example
			            *
			            * // The status field value of an account is not equal to "compromised"
			            $dbTableAuthAdapter = new DbTableAuthAdapter($db,
			            		'users',
			            		'username',
			            		'password',
			            		'MD5(?) AND status != "compromised"'
			            );

			            // The active field value of an account is equal to "TRUE"
			            $dbTableAuthAdapter = new DbTableAuthAdapter($db,
			            		'users',
			            		'username',
			            		'password',
			            		'MD5(?) AND active = "TRUE"'
			            );
			            */

			            $authService = new AuthenticationService();
			            $authService->setAdapter($dbTableAuthAdapter);
                        $authService->setStorage($sm->get('User\Model\MyAuthStorage'));

                        return $authService;
                    },
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}


text:
<?php

namespace Oro\Bundle\ImportExportBundle\Job\Step;

use Akeneo\Bundle\BatchBundle\Entity\StepExecution;

use Oro\Bundle\BatchBundle\Step\ItemStep;
use Oro\Bundle\ImportExportBundle\Job\JobExecutor;

class PostProcessItemStep extends ItemStep
{
    /**
     * @var array
     */
    protected $postProcessingJobs = [];

    /**
     * @var array
     */
    protected $contextSharedKeys = [];

    /**
     * @var JobExecutor
     */
    protected $jobExecutor;

    /**
     * @param string $jobName
     */
    public function setPostProcessingJobs($jobName)
    {
        $this->postProcessingJobs = $this->scalarToArray($jobName);
    }

    /**
     * @param string $contextSharedKeys
     */
    public function setContextSharedKeys($contextSharedKeys)
    {
        $this->contextSharedKeys = $this->scalarToArray($contextSharedKeys);
    }

    /**
     * @param JobExecutor $jobExecutor
     */
    public function setJobExecutor(JobExecutor $jobExecutor)
    {
        $this->jobExecutor = $jobExecutor;
    }

    /**
     * {@inheritdoc}
     */
    public function doExecute(StepExecution $stepExecution)
    {
        $this->initializeStepElements($stepExecution);

        $stepExecutor = new PostProcessStepExecutor();
        $stepExecutor
            ->setStepExecution($stepExecution)
            ->setJobExecutor($this->jobExecutor)
            ->setReader($this->reader)
            ->setProcessor($this->processor)
            ->setWriter($this->writer);
        if (null !== $this->batchSize) {
            $stepExecutor->setBatchSize($this->batchSize);
        }

        if ($this->contextSharedKeys) {
            $stepExecutor->setContextSharedKeys($this->contextSharedKeys);
        }

        if ($this->postProcessingJobs) {
            $jobType = $stepExecution->getJobExecution()->getJobInstance()->getType();
            foreach ($this->postProcessingJobs as $jobName) {
                $stepExecutor->addPostProcessingJob($jobType, $jobName);
            }
        }

        $stepExecutor->execute($this);
        $this->flushStepElements();
    }

    /**
     * @param string $scalar
     * @return array
     */
    protected function scalarToArray($scalar)
    {
        $result = explode(',', $scalar);
        $result = array_map('trim', $result);

        return array_filter($result);
    }
}


text:
local wrequire = require("vicious.helpers").wrequire
widgets = { _NAME = "vicious.widgets" }

return setmetatable(widgets, {__index = wrequire})


text:
class AddStaffFieldsToEquipmentReservation < ActiveRecord::Migration
  def self.up
    add_column :equipment_reservations, :staff, :boolean
    add_column :equipment_reservations, :program_hold, :boolean
  end

  def self.down
    remove_column :equipment_reservations, :program_hold
    remove_column :equipment_reservations, :staff
  end
end


text:
package at.ac.univie.cs.swa.soa.generator;

import at.ac.univie.cs.swa.soa.sdl.DataElement;
import at.ac.univie.cs.swa.soa.sdl.Operation;
import at.ac.univie.cs.swa.soa.sdl.SDL;
import at.ac.univie.cs.swa.soa.sdl.Service;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import java.io.File;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.generator.IFileSystemAccess;
import org.eclipse.xtext.xbase.lib.IterableExtensions;

@SuppressWarnings("all")
public class SEIGenerator {
  public void generateSEI(final IFileSystemAccess fsa, final SDL dsl) {
    String _name = dsl.getName();
    String _lowerCase = _name.toLowerCase();
    final String packagePath = _lowerCase.replace(".", File.separator);
    EList<Service> _services = dsl.getServices();
    final Iterable<Service> webServices = Iterables.<Service>filter(_services, Service.class);
    boolean _and = false;
    boolean _notEquals = (!Objects.equal(webServices, null));
    if (!_notEquals) {
      _and = false;
    } else {
      boolean _isEmpty = IterableExtensions.isEmpty(webServices);
      boolean _not = (!_isEmpty);
      _and = (_notEquals && _not);
    }
    if (_and) {
      for (final Service s : webServices) {
        {
          String _plus = (packagePath + File.separator);
          String _name_1 = s.getName();
          String _plus_1 = (_plus + _name_1);
          final String file = (_plus_1 + ".java");
          CharSequence _generate = this.generate(s, dsl);
          fsa.generateFile(file, _generate);
        }
      }
    }
  }

  protected CharSequence generate(final Service s, final SDL dsl) {
    CharSequence _xblockexpression = null;
    {
      String _name = dsl.getName();
      final String packageName = _name.toLowerCase();
      String _replace = packageName.replace(".", ":");
      final String nsURI = ("urn:" + _replace);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("package ");
      _builder.append(packageName, "");
      _builder.append(";");
      _builder.newLineIfNotEmpty();
      _builder.newLine();
      _builder.newLine();
      _builder.append("@javax.jws.WebService(targetNamespace = \"");
      _builder.append(nsURI, "");
      _builder.append("\", name = \"");
      String _name_1 = s.getName();
      _builder.append(_name_1, "");
      _builder.append("\")");
      _builder.newLineIfNotEmpty();
      _builder.append("@javax.jws.soap.SOAPBinding(parameterStyle = javax.jws.soap.SOAPBinding.ParameterStyle.BARE)");
      _builder.newLine();
      _builder.append("public interface ");
      String _name_2 = s.getName();
      _builder.append(_name_2, "");
      _builder.append(" {");
      _builder.newLineIfNotEmpty();
      _builder.newLine();
      {
        EList<Operation> _operations = s.getOperations();
        for(final Operation operation : _operations) {
          _builder.append("\t");
          CharSequence _generateOperation = this.generateOperation(operation, dsl);
          _builder.append(_generateOperation, "	");
          _builder.newLineIfNotEmpty();
        }
      }
      _builder.append("}");
      _builder.newLine();
      _xblockexpression = (_builder);
    }
    return _xblockexpression;
  }

  protected CharSequence generateOperation(final Operation operation, final SDL dsl) {
    CharSequence _xblockexpression = null;
    {
      boolean _and = false;
      boolean _and_1 = false;
      DataElement _inputType = operation.getInputType();
      boolean _notEquals = (!Objects.equal(_inputType, null));
      if (!_notEquals) {
        _and_1 = false;
      } else {
        DataElement _inputType_1 = operation.getInputType();
        String _name = _inputType_1.getName();
        boolean _notEquals_1 = (!Objects.equal(_name, null));
        _and_1 = (_notEquals && _notEquals_1);
      }
      if (!_and_1) {
        _and = false;
      } else {
        DataElement _inputType_2 = operation.getInputType();
        String _name_1 = _inputType_2.getName();
        boolean _isEmpty = _name_1.isEmpty();
        boolean _not = (!_isEmpty);
        _and = (_and_1 && _not);
      }
      final boolean hasInput = _and;
      boolean _and_2 = false;
      boolean _and_3 = false;
      DataElement _outputType = operation.getOutputType();
      boolean _notEquals_2 = (!Objects.equal(_outputType, null));
      if (!_notEquals_2) {
        _and_3 = false;
      } else {
        DataElement _outputType_1 = operation.getOutputType();
        String _name_2 = _outputType_1.getName();
        boolean _notEquals_3 = (!Objects.equal(_name_2, null));
        _and_3 = (_notEquals_2 && _notEquals_3);
      }
      if (!_and_3) {
        _and_2 = false;
      } else {
        DataElement _outputType_2 = operation.getOutputType();
        String _name_3 = _outputType_2.getName();
        boolean _isEmpty_1 = _name_3.isEmpty();
        boolean _not_1 = (!_isEmpty_1);
        _and_2 = (_and_3 && _not_1);
      }
      final boolean hasOutput = _and_2;
      String _xifexpression = null;
      DataElement _inputType_3 = operation.getInputType();
      boolean _notEquals_4 = (!Objects.equal(_inputType_3, null));
      if (_notEquals_4) {
        DataElement _inputType_4 = operation.getInputType();
        EObject _eContainer = _inputType_4.eContainer();
        String _name_4 = ((SDL) _eContainer).getName();
        _xifexpression = _name_4;
      } else {
        _xifexpression = null;
      }
      final String inputQualifiedPath = _xifexpression;
      String _xifexpression_1 = null;
      DataElement _outputType_3 = operation.getOutputType();
      boolean _notEquals_5 = (!Objects.equal(_outputType_3, null));
      if (_notEquals_5) {
        DataElement _outputType_4 = operation.getOutputType();
        EObject _eContainer_1 = _outputType_4.eContainer();
        String _name_5 = ((SDL) _eContainer_1).getName();
        _xifexpression_1 = _name_5;
      } else {
        _xifexpression_1 = null;
      }
      final String outputQualifiedPath = _xifexpression_1;
      String _xifexpression_2 = null;
      boolean _notEquals_6 = (!Objects.equal(inputQualifiedPath, null));
      if (_notEquals_6) {
        String _replace = inputQualifiedPath.replace(".", ":");
        String _plus = ("urn:" + _replace);
        _xifexpression_2 = _plus;
      } else {
        _xifexpression_2 = null;
      }
      final String inputNsURI = _xifexpression_2;
      String _xifexpression_3 = null;
      boolean _notEquals_7 = (!Objects.equal(outputQualifiedPath, null));
      if (_notEquals_7) {
        String _replace_1 = outputQualifiedPath.replace(".", ":");
        String _plus_1 = ("urn:" + _replace_1);
        _xifexpression_3 = _plus_1;
      } else {
        _xifexpression_3 = null;
      }
      final String outputNsURI = _xifexpression_3;
      StringConcatenation _builder = new StringConcatenation();
      _builder.newLine();
      {
        if (hasOutput) {
          _builder.append("@javax.jws.WebResult(name = \"");
          DataElement _outputType_5 = operation.getOutputType();
          String _name_6 = _outputType_5.getName();
          _builder.append(_name_6, "");
          _builder.append("\", targetNamespace = \"");
          _builder.append(outputNsURI, "");
          _builder.append("\",partName = \"");
          String _outputName = operation.getOutputName();
          _builder.append(_outputName, "");
          _builder.append("\")");
          _builder.newLineIfNotEmpty();
        } else {
          _builder.append("@javax.jws.Oneway");
          _builder.newLine();
        }
      }
      _builder.append("@javax.jws.WebMethod(operationName=\"");
      String _name_7 = operation.getName();
      _builder.append(_name_7, "");
      _builder.append("\")");
      _builder.newLineIfNotEmpty();
      _builder.append("public ");
      {
        if (hasOutput) {
          _builder.append(outputQualifiedPath, "");
          _builder.append(".");
          DataElement _outputType_6 = operation.getOutputType();
          String _name_8 = _outputType_6.getName();
          _builder.append(_name_8, "");
        } else {
          _builder.append("void");
        }
      }
      _builder.append(" ");
      String _name_9 = operation.getName();
      _builder.append(_name_9, "");
      _builder.append("(");
      _builder.newLineIfNotEmpty();
      _builder.append("@javax.jws.WebParam(partName = \"");
      String _inputName = operation.getInputName();
      _builder.append(_inputName, "");
      _builder.append("\",name = \"");
      DataElement _inputType_5 = operation.getInputType();
      String _name_10 = _inputType_5.getName();
      _builder.append(_name_10, "");
      _builder.append("\", targetNamespace = \"");
      _builder.append(inputNsURI, "");
      _builder.append("\")");
      _builder.newLineIfNotEmpty();
      {
        if (hasInput) {
          _builder.append(inputQualifiedPath, "");
          _builder.append(".");
          DataElement _inputType_6 = operation.getInputType();
          String _name_11 = _inputType_6.getName();
          _builder.append(_name_11, "");
        }
      }
      _builder.append(" ");
      String _inputName_1 = operation.getInputName();
      _builder.append(_inputName_1, "");
      _builder.append(");");
      _builder.newLineIfNotEmpty();
      _xblockexpression = (_builder);
    }
    return _xblockexpression;
  }
}


text:
import 'normalize.js'
import chai from 'chai'
import sinon from 'sinon'
import dirtyChai from 'dirty-chai'
import chaiAsPromised from 'chai-as-promised'
import sinonChai from 'sinon-chai'
import chaiEnzyme from 'chai-enzyme'
import configureStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import fmock from 'fetch-mock'

// Mocha / Chai
// ------------------------------------
mocha.setup({ui: 'bdd'})
chai.should()

global.chai = chai
global.expect = chai.expect
global.sinon = sinon

global.fmock = fmock
global.configureStore = configureStore
global.middlewares = [ thunk ]

// Chai Plugins
// ------------------------------------
chai.use(chaiEnzyme())
chai.use(dirtyChai)
chai.use(chaiAsPromised)
chai.use(sinonChai)

// Test Importer
// ------------------------------------
// We use a Webpack global here as it is replaced with a string during compile.
// Using a regular JS variable is not statically analyzable so webpack will throw warnings.
const testsContext = require.context('./', true, /\.(spec|test)\.(js|ts|tsx)$/)

// When a test file changes, only rerun that spec file. If something outside of a
// test file changed, rerun all tests.
// https://www.npmjs.com/package/karma-webpack-with-fast-source-maps
const __karmaWebpackManifest__ = []
const allTests = testsContext.keys()
const changedTests = allTests.filter(path => {
  return __karmaWebpackManifest__.indexOf(path) !== -1
})

;(changedTests.length ? changedTests : allTests).forEach(testsContext)


text:
package aezeed

import "github.com/btcsuite/btcwallet/waddrmgr"

func init() {
	// For the purposes of our itest, we'll crank down the scrypt params a
	// bit.
	scryptN = waddrmgr.FastScryptOptions.N
	scryptR = waddrmgr.FastScryptOptions.R
	scryptP = waddrmgr.FastScryptOptions.P
}


text:
@implementation GTLRAnalyticsDataQuery

@dynamic fields;

@end

@implementation GTLRAnalyticsDataQuery_PropertiesBatchRunPivotReports

@dynamic property;

+ (instancetype)queryWithObject:(GTLRAnalyticsData_BatchRunPivotReportsRequest *)object
                       property:(NSString *)property {
  if (object == nil) {
#if defined(DEBUG) && DEBUG
    NSAssert(object != nil, @"Got a nil object");
#endif
    return nil;
  }
  NSArray *pathParams = @[ @"property" ];
  NSString *pathURITemplate = @"v1beta/{+property}:batchRunPivotReports";
  GTLRAnalyticsDataQuery_PropertiesBatchRunPivotReports *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:@"POST"
                       pathParameterNames:pathParams];
  query.bodyObject = object;
  query.property = property;
  query.expectedObjectClass = [GTLRAnalyticsData_BatchRunPivotReportsResponse class];
  query.loggingName = @"analyticsdata.properties.batchRunPivotReports";
  return query;
}

@end

@implementation GTLRAnalyticsDataQuery_PropertiesBatchRunReports

@dynamic property;

+ (instancetype)queryWithObject:(GTLRAnalyticsData_BatchRunReportsRequest *)object
                       property:(NSString *)property {
  if (object == nil) {
#if defined(DEBUG) && DEBUG
    NSAssert(object != nil, @"Got a nil object");
#endif
    return nil;
  }
  NSArray *pathParams = @[ @"property" ];
  NSString *pathURITemplate = @"v1beta/{+property}:batchRunReports";
  GTLRAnalyticsDataQuery_PropertiesBatchRunReports *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:@"POST"
                       pathParameterNames:pathParams];
  query.bodyObject = object;
  query.property = property;
  query.expectedObjectClass = [GTLRAnalyticsData_BatchRunReportsResponse class];
  query.loggingName = @"analyticsdata.properties.batchRunReports";
  return query;
}

@end

@implementation GTLRAnalyticsDataQuery_PropertiesCheckCompatibility

@dynamic property;

+ (instancetype)queryWithObject:(GTLRAnalyticsData_CheckCompatibilityRequest *)object
                       property:(NSString *)property {
  if (object == nil) {
#if defined(DEBUG) && DEBUG
    NSAssert(object != nil, @"Got a nil object");
#endif
    return nil;
  }
  NSArray *pathParams = @[ @"property" ];
  NSString *pathURITemplate = @"v1beta/{+property}:checkCompatibility";
  GTLRAnalyticsDataQuery_PropertiesCheckCompatibility *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:@"POST"
                       pathParameterNames:pathParams];
  query.bodyObject = object;
  query.property = property;
  query.expectedObjectClass = [GTLRAnalyticsData_CheckCompatibilityResponse class];
  query.loggingName = @"analyticsdata.properties.checkCompatibility";
  return query;
}

@end

@implementation GTLRAnalyticsDataQuery_PropertiesGetMetadata

@dynamic name;

+ (instancetype)queryWithName:(NSString *)name {
  NSArray *pathParams = @[ @"name" ];
  NSString *pathURITemplate = @"v1beta/{+name}";
  GTLRAnalyticsDataQuery_PropertiesGetMetadata *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:nil
                       pathParameterNames:pathParams];
  query.name = name;
  query.expectedObjectClass = [GTLRAnalyticsData_Metadata class];
  query.loggingName = @"analyticsdata.properties.getMetadata";
  return query;
}

@end

@implementation GTLRAnalyticsDataQuery_PropertiesRunPivotReport

@dynamic property;

+ (instancetype)queryWithObject:(GTLRAnalyticsData_RunPivotReportRequest *)object
                       property:(NSString *)property {
  if (object == nil) {
#if defined(DEBUG) && DEBUG
    NSAssert(object != nil, @"Got a nil object");
#endif
    return nil;
  }
  NSArray *pathParams = @[ @"property" ];
  NSString *pathURITemplate = @"v1beta/{+property}:runPivotReport";
  GTLRAnalyticsDataQuery_PropertiesRunPivotReport *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:@"POST"
                       pathParameterNames:pathParams];
  query.bodyObject = object;
  query.property = property;
  query.expectedObjectClass = [GTLRAnalyticsData_RunPivotReportResponse class];
  query.loggingName = @"analyticsdata.properties.runPivotReport";
  return query;
}

@end

@implementation GTLRAnalyticsDataQuery_PropertiesRunRealtimeReport

@dynamic property;

+ (instancetype)queryWithObject:(GTLRAnalyticsData_RunRealtimeReportRequest *)object
                       property:(NSString *)property {
  if (object == nil) {
#if defined(DEBUG) && DEBUG
    NSAssert(object != nil, @"Got a nil object");
#endif
    return nil;
  }
  NSArray *pathParams = @[ @"property" ];
  NSString *pathURITemplate = @"v1beta/{+property}:runRealtimeReport";
  GTLRAnalyticsDataQuery_PropertiesRunRealtimeReport *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:@"POST"
                       pathParameterNames:pathParams];
  query.bodyObject = object;
  query.property = property;
  query.expectedObjectClass = [GTLRAnalyticsData_RunRealtimeReportResponse class];
  query.loggingName = @"analyticsdata.properties.runRealtimeReport";
  return query;
}

@end

@implementation GTLRAnalyticsDataQuery_PropertiesRunReport

@dynamic property;

+ (instancetype)queryWithObject:(GTLRAnalyticsData_RunReportRequest *)object
                       property:(NSString *)property {
  if (object == nil) {
#if defined(DEBUG) && DEBUG
    NSAssert(object != nil, @"Got a nil object");
#endif
    return nil;
  }
  NSArray *pathParams = @[ @"property" ];
  NSString *pathURITemplate = @"v1beta/{+property}:runReport";
  GTLRAnalyticsDataQuery_PropertiesRunReport *query =
    [[self alloc] initWithPathURITemplate:pathURITemplate
                               HTTPMethod:@"POST"
                       pathParameterNames:pathParams];
  query.bodyObject = object;
  query.property = property;
  query.expectedObjectClass = [GTLRAnalyticsData_RunReportResponse class];
  query.loggingName = @"analyticsdata.properties.runReport";
  return query;
}

@end


text:
from __future__ import division, absolute_import, print_function, unicode_literals

import re
from datetime import datetime
from urlparse import urljoin, urlsplit
from inspect import isclass

from lxml.html import defs, make_links_absolute, fragment_fromstring
from lxml.html.clean import Cleaner
from w3lib.url import safe_url_string
from scrapy.selector.csstranslator import ScrapyHTMLTranslator

def encode_if_unicode(string, encoding='utf-8'):
    return string.encode(encoding) if isinstance(string, unicode) else string

def parse_datetime(date_string, format_):
    return datetime.strptime(encode_if_unicode(date_string),
                             encode_if_unicode(format_))

def unwrap_html(html):
    l = html.index(">")
    r = html.rindex("<")
    return html[l+1:r]

def clean_html(html, url=None):
    if html.strip():
        html = html_cleaner.clean_html(html)
        if url is not None:
            html = make_links_absolute(html, url)
    return html
safe_attrs = defs.safe_attrs - {'class', 'align'}
remove_tags = ['font', 'span']
html_cleaner = Cleaner(style=True, page_structure=False,
                       remove_tags=remove_tags, safe_attrs=safe_attrs)

def clear_html_tags(html):
    html = fragment_fromstring(html).text_content()
    return html.strip()

def extract_number(string, index):
    return re.findall(r"\d+", string)[index]

def normalize_url(url, base_url=None, encoding='utf-8'):
    if base_url:
        url = urljoin(base_url, url)
    return safe_url_string(url, encoding)

def get_domain_from_url(url):
    return urlsplit(url).hostname or ""

def iterate_subclasses_in_module(module, base):
    for obj in vars(module).itervalues():
        if isclass(obj) and issubclass(obj, base) and obj.__module__ == module.__name__:
            yield obj

def css_to_xpath(css):
    return _csstranslator.css_to_xpath(css)
_csstranslator = ScrapyHTMLTranslator()


text:
require File.expand_path '../../test_helper', __dir__

# Test class for Delete Database
class TestDeleteDatabase < Minitest::Test
  def setup
    @service = Fog::Sql::AzureRM.new(credentials)
    @token_provider = Fog::Credentials::AzureRM.instance_variable_get(:@token_provider)
  end

  def test_delete_database_success
    @token_provider.stub :get_authentication_header, 'Bearer <some-token>' do
      RestClient.stub :delete, true do
        assert @service.delete_database('fog-test-rg', 'fog-test-server-name', 'database-name')
      end
    end
  end

  def test_delete_database_failure
    @token_provider.stub :get_authentication_header, 'Bearer <some-token>' do
      assert_raises ArgumentError do
        @service.delete_database('fog-test-zone')
      end
    end
  end

  def test_delete_database_exception
    response = proc { raise MsRestAzure::AzureOperationError.new(nil, nil, 'error' => { 'message' => 'mocked exception' }) }
    @token_provider.stub :get_authentication_header, response do
      assert_raises Exception do
        assert @service.delete_database('fog-test-rg', 'fog-test-server-name', 'database-name')
      end
    end
  end
end


text:
// Working Files List
// Visual Studio extension tool window that shows a selectable list of files
// that are open in the editor
// Copyright © 2016 Anthony Fung

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using NUnit.Framework;
using System.Threading;
using WorkingFilesList.Core.Controls;
using WorkingFilesList.Core.Controls.Command;

namespace WorkingFilesList.Core.Test.Controls.Command
{
    [TestFixture]
    [Apartment(ApartmentState.STA)]
    public class IncrementNumericUpDownValueTests
    {
        [Test]
        public void CanExecuteReturnsTrue()
        {
            // Arrange

            var command = new IncrementNumericUpDownValue();

            // Act

            var canExecute = command.CanExecute(null);

            // Assert

            Assert.IsTrue(canExecute);
        }

        [Test]
        public void CommandIncrementsNumericUpDownValue()
        {
            // Arrange

            var upDown = new NumericUpDown
            {
                Value = 0
            };

            var command = new IncrementNumericUpDownValue();

            // Act

            command.Execute(upDown);

            // Assert

            Assert.That(upDown.Value, Is.EqualTo(1));
        }

        [Test]
        public void ExceptionIsNotThrownIfParameterIsNotNumericUpDown()
        {
            // Arrange

            var command = new IncrementNumericUpDownValue();

            // Assert

            Assert.DoesNotThrow(() => command.Execute(new object()));
        }
    }
}