text:
#include "config.h"

#include "WebPageCompositor.h"

#if USE(ACCELERATED_COMPOSITING)
#include "WebPageCompositorClient.h"
#include "WebPageCompositor_p.h"

#include "BackingStore_p.h"
#include "LayerWebKitThread.h"
#include "WebPage_p.h"

#include <BlackBerryPlatformDebugMacros.h>
#include <BlackBerryPlatformExecutableMessage.h>
#include <BlackBerryPlatformMessage.h>
#include <BlackBerryPlatformMessageClient.h>
#include <BlackBerryPlatformViewportAccessor.h>
#include <GenericTimerClient.h>
#include <ThreadTimerClient.h>
#include <wtf/CurrentTime.h>

using namespace WebCore;

namespace BlackBerry {
namespace WebKit {

WebPageCompositorPrivate::WebPageCompositorPrivate(WebPagePrivate* page, WebPageCompositorClient* client)
    : m_client(client)
    , m_webPage(page)
    , m_drawsRootLayer(false)
{
    ASSERT(m_webPage);
    setOneShot(true); // one-shot animation client
}

WebPageCompositorPrivate::~WebPageCompositorPrivate()
{
    detach();
}

void WebPageCompositorPrivate::detach()
{
    if (m_webPage)
        Platform::AnimationFrameRateController::instance()->removeClient(this);
    m_webPage = 0;
}

void WebPageCompositorPrivate::setPage(WebPagePrivate *p)
{
    if (p == m_webPage)
        return;
    ASSERT(p);
    ASSERT(m_webPage); // if this is null, we have a bug and we need to re-add.
    m_webPage = p;
}

void WebPageCompositorPrivate::setContext(Platform::Graphics::GLES2Context* context)
{
    if (m_context == context)
        return;

    m_context = context;
    if (!m_context)
        m_layerRenderer.clear();
}

void WebPageCompositorPrivate::setRootLayer(LayerCompositingThread* rootLayer)
{
    m_rootLayer = rootLayer;
}

void WebPageCompositorPrivate::setOverlayLayer(LayerCompositingThread* overlayLayer)
{
    m_overlayLayer = overlayLayer;
}

void WebPageCompositorPrivate::prepareFrame(double animationTime)
{
    if (!m_context)
        return;

    // The LayerRenderer is involved in rendering the BackingStore when
    // WebPageCompositor is used to render the web page. The presence of a
    // WebPageCompositorClient (m_client) indicates this is the case, so
    // create a LayerRenderer if there are layers or if there's a client.
    if (!m_rootLayer && !m_overlayLayer && !m_compositingThreadOverlayLayer && !m_client)
        return;

    if (!m_layerRenderer) {
        m_layerRenderer = LayerRenderer::create(m_context);
        if (!m_layerRenderer->hardwareCompositing()) {
            m_layerRenderer.clear();
            return;
        }
    }

    // Unfortunately, we have to use currentTime() because the animations are
    // started in that time coordinate system.
    animationTime = currentTime();
    if (m_rootLayer)
        m_layerRenderer->prepareFrame(animationTime, m_rootLayer.get());
    if (m_overlayLayer)
        m_layerRenderer->prepareFrame(animationTime, m_overlayLayer.get());
    if (m_compositingThreadOverlayLayer)
        m_layerRenderer->prepareFrame(animationTime, m_compositingThreadOverlayLayer.get());
}

void WebPageCompositorPrivate::render(const IntRect& targetRect, const IntRect& clipRect, const TransformationMatrix& transformIn, const FloatRect& transformedContents, const FloatRect& /*viewport*/)
{
    // m_layerRenderer should have been created in prepareFrame
    if (!m_layerRenderer)
        return;

    // It's not safe to call into the BackingStore if the compositor hasn't been set yet.
    // For thread safety, we have to do it using a round-trip to the WebKit thread, so the
    // embedder might call this before the round-trip to WebPagePrivate::setCompositor() is
    // done.
    if (!m_webPage || m_webPage->compositor() != this)
        return;

    m_layerRenderer->setClearSurfaceOnDrawLayers(false);

    FloatRect contents = m_webPage->mapFromTransformedFloatRect(transformedContents);

    m_layerRenderer->setViewport(targetRect, clipRect, contents, m_layoutRectForCompositing, m_contentsSizeForCompositing);

    TransformationMatrix transform(transformIn);
    transform *= *m_webPage->m_transformationMatrix;

    if (!drawsRootLayer())
        m_webPage->m_backingStore->d->compositeContents(m_layerRenderer.get(), transform, contents, !m_backgroundColor.hasAlpha());

    compositeLayers(transform);
}

void WebPageCompositorPrivate::compositeLayers(const TransformationMatrix& transform)
{
    if (m_rootLayer)
        m_layerRenderer->compositeLayers(transform, m_rootLayer.get());
    if (m_overlayLayer)
        m_layerRenderer->compositeLayers(transform, m_overlayLayer.get());
    if (m_compositingThreadOverlayLayer)
        m_layerRenderer->compositeLayers(transform, m_compositingThreadOverlayLayer.get());

    m_lastCompositingResults = m_layerRenderer->lastRenderingResults();

    if (m_lastCompositingResults.needsAnimationFrame) {
        Platform::AnimationFrameRateController::instance()->addClient(this);
        m_webPage->updateDelegatedOverlays();
    }
}

bool WebPageCompositorPrivate::drawsRootLayer() const
{
    return m_rootLayer && m_drawsRootLayer;
}

bool WebPageCompositorPrivate::drawLayers(const IntRect& dstRect, const FloatRect& contents)
{
    // Is there anything to draw?
    if (!m_rootLayer && !m_overlayLayer && !m_compositingThreadOverlayLayer)
        return false;

    // prepareFrame creates the LayerRenderer if needed
    prepareFrame(currentTime());
    if (!m_layerRenderer)
        return false;

    bool shouldClear = drawsRootLayer();
    if (BackingStore* backingStore = m_webPage->m_backingStore)
        shouldClear = shouldClear || !backingStore->d->isOpenGLCompositing();
    m_layerRenderer->setClearSurfaceOnDrawLayers(shouldClear);

    // OpenGL window coordinates origin is at the lower left corner of the surface while
    // WebKit uses upper left as the origin of the window coordinate system. The passed in 'dstRect'
    // is in WebKit window coordinate system. Here we setup the viewport to the corresponding value
    // in OpenGL window coordinates.
    int viewportY = std::max(0, m_context->surfaceSize().height() - dstRect.maxY());
    IntRect viewport = IntRect(dstRect.x(), viewportY, dstRect.width(), dstRect.height());

    m_layerRenderer->setViewport(viewport, viewport, contents, m_layoutRectForCompositing, m_contentsSizeForCompositing);

    // WebKit uses row vectors which are multiplied by the matrix on the left (i.e. v*M)
    // Transformations are composed on the left so that M1.xform(M2) means M2*M1
    // We therefore start with our (othogonal) projection matrix, which will be applied
    // as the last transformation.
    TransformationMatrix transform = LayerRenderer::orthoMatrix(0, contents.width(), contents.height(), 0, -1000, 1000);
    transform.translate3d(-contents.x(), -contents.y(), 0);
    compositeLayers(transform);

    return true;
}

void WebPageCompositorPrivate::setBackgroundColor(const Color& color)
{
    m_backgroundColor = color;
}

void WebPageCompositorPrivate::releaseLayerResources()
{
    if (m_layerRenderer)
        m_layerRenderer->releaseLayerResources();
}

void WebPageCompositorPrivate::animationFrameChanged()
{
    BackingStore* backingStore = m_webPage->m_backingStore;
    if (!backingStore) {
        Platform::ViewportAccessor* viewportAccessor = m_webPage->client()->userInterfaceViewportAccessor();
        const Platform::IntRect dstRect = viewportAccessor->destinationSurfaceRect();
        const Platform::FloatRect srcRect = viewportAccessor->documentViewportRect();

        drawLayers(dstRect, srcRect);
        return;
    }

    if (backingStore->d->shouldDirectRenderingToWindow()) {
        if (backingStore->d->isDirectRenderingAnimationMessageScheduled())
            return; // don't send new messages as long as we haven't rerendered

        using namespace BlackBerry::Platform;

        backingStore->d->setDirectRenderingAnimationMessageScheduled();
        webKitThreadMessageClient()->dispatchMessage(createMethodCallMessage(&BackingStorePrivate::renderVisibleContents, backingStore->d));
        return;
    }

    if (!m_webPage->needsOneShotDrawingSynchronization())
        m_webPage->blitVisibleContents();
}

void WebPageCompositorPrivate::compositorDestroyed()
{
    if (m_client)
        m_client->compositorDestroyed();

    m_client = 0;
}

void WebPageCompositorPrivate::addOverlay(LayerCompositingThread* layer)
{
    if (!m_compositingThreadOverlayLayer)
        m_compositingThreadOverlayLayer = LayerCompositingThread::create(LayerData::CustomLayer, 0);
    m_compositingThreadOverlayLayer->addSublayer(layer);
}

void WebPageCompositorPrivate::removeOverlay(LayerCompositingThread* layer)
{
    if (layer->superlayer() != m_compositingThreadOverlayLayer)
        return;

    layer->removeFromSuperlayer();

    if (m_compositingThreadOverlayLayer && m_compositingThreadOverlayLayer->getSublayers().isEmpty())
        m_compositingThreadOverlayLayer.clear();
}

WebPageCompositor::WebPageCompositor(WebPage* page, WebPageCompositorClient* client)
{
    using namespace BlackBerry::Platform;

    RefPtr<WebPageCompositorPrivate> tmp = WebPageCompositorPrivate::create(page->d, client);

    // Keep one ref ourselves...
    d = tmp.get();
    d->ref();

    // ...And pass one ref to the web page.
    // This ensures that the compositor will be around for as long as it's
    // needed. Unfortunately RefPtr<T> is not public, so we have declare to
    // resort to manual refcounting.
    webKitThreadMessageClient()->dispatchMessage(createMethodCallMessage(&WebPagePrivate::setCompositor, d->page(), tmp));
}

WebPageCompositor::~WebPageCompositor()
{
    using namespace BlackBerry::Platform;

    // If we're being destroyed before the page, send a message to disconnect us
    if (d->page())
        webKitThreadMessageClient()->dispatchMessage(createMethodCallMessage(&WebPagePrivate::setCompositor, d->page(), PassRefPtr<WebPageCompositorPrivate>(0)));
    d->compositorDestroyed();
    d->deref();
}

WebPageCompositorClient* WebPageCompositor::client() const
{
    return d->client();
}

void WebPageCompositor::prepareFrame(Platform::Graphics::GLES2Context* context, double animationTime)
{
    d->setContext(context);
    d->prepareFrame(animationTime);
}

void WebPageCompositor::render(Platform::Graphics::GLES2Context* context,
                               const Platform::IntRect& targetRect,
                               const Platform::IntRect& clipRect,
                               const Platform::TransformationMatrix& transform,
                               const Platform::FloatRect& contents,
                               const Platform::FloatRect& viewport)
{
    d->setContext(context);
    d->render(targetRect, clipRect, TransformationMatrix(reinterpret_cast<const TransformationMatrix&>(transform)), contents, viewport);
}

void WebPageCompositor::cleanup(Platform::Graphics::GLES2Context* context)
{
    d->setContext(0);
}

void WebPageCompositor::contextLost()
{
    // This method needs to delete the compositor in a way that not tries to
    // use any OpenGL calls (the context is gone, so we can't and don't need to
    // free any OpenGL resources.
    notImplemented();
}

} // namespace WebKit
} // namespace BlackBerry

#else // USE(ACCELERATED_COMPOSITING)

namespace BlackBerry {
namespace WebKit {

WebPageCompositor::WebPageCompositor(WebPage*, WebPageCompositorClient*)
    : d(0)
{
}

WebPageCompositor::~WebPageCompositor()
{
}

WebPageCompositorClient* WebPageCompositor::client() const
{
    return 0;
}

void WebPageCompositor::prepareFrame(Platform::Graphics::GLES2Context*, double)
{
}

void WebPageCompositor::render(Platform::Graphics::GLES2Context*,
                               const Platform::IntRect&,
                               const Platform::IntRect&,
                               const Platform::TransformationMatrix&,
                               const Platform::FloatRect&,
                               const Platform::FloatRect&)
{
}

void WebPageCompositor::cleanup(Platform::Graphics::GLES2Context*)
{
}

void WebPageCompositor::contextLost()
{
}

} // namespace WebKit
} // namespace BlackBerry

#endif // USE(ACCELERATED_COMPOSITING)


text:
package org.ayo.rx.sample;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.internal.functions.Functions;
import io.reactivex.internal.operators.flowable.FlowableInternalHelper;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/2/14 0014.
 */

public class Rx_takeUntil2 extends BaseRxDemo {

    @Override
    protected String getTitle() {
        return "take";
    }
    @Override
    protected String getImageName() {
        return "takeUntil2";
    }
    private Disposable task;

    @Override
    protected String getCodeNormal() {
        return "Flowable.interval(1, 1, TimeUnit.SECONDS)\n" +
                "                .takeUntil(new Predicate<Long>() {\n" +
                "                    @Override\n" +
                "                    public boolean test(Long aLong) throws Exception {\n" +
                "                        return aLong >= 5;\n" +
                "                    }\n" +
                "                })";
    }

    protected void runOk(){
        /*
        - empty
            - 直接调用complete
         */
        task = Flowable.interval(1, 1, TimeUnit.SECONDS)
                .takeUntil(new Predicate<Long>() {
                    @Override
                    public boolean test(Long aLong) throws Exception {
                        return aLong >= 5;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long s) throws Exception {
                        notifyy(s + "");
                    }
                }, Functions.ERROR_CONSUMER,
                        new Action() {
                            @Override
                            public void run() throws Exception {
                                notifyy("onComplete---结束了!@@");
                            }
                        },
                        FlowableInternalHelper.RequestMax.INSTANCE);

    }

    protected void runError(){
    }

    @Override
    protected void onDestroy2() {
        super.onDestroy2();
        if(task != null) task.dispose();
    }

}

redpajama_set_name: RedPajamaGithub


text:
angular.module('bluestorm', [
    'ngCookies',
    'bluestorm.http',
    'bluestorm.user'
])
    .service('bluestorm', function(){
        var service = {
            urls: {},
            ssl: /* @echo ssl */
        };
        /* @echo appsUrl */

        // @if envConfig='production'
        service.urls['api'] = window.location.protocol + '///* @echo apiUrl */';
        service.urls['socket'] = window.location.protocol + '///* @echo socketUrl */';
        // @endif

        // @if envConfig='development'
        service.urls['api'] = window.location.protocol + '//' + window.location.hostname+':/* @echo apiPort */';
        service.urls['socket'] = window.location.protocol + '//' + window.location.hostname+":/* @echo socketPort */";
        // @endif

        service.env = '/* @echo NODE_ENV */';

        service.app = '/* @echo app */';

        service.getDomains = function () {
            var domains = [];
            for(var i in service.urls) {
                var url = service.urls[i];
                if(i!='socket'&&i!='api') {
                    url = url.substring(7, url.length);
                    url = url.split(':')[0];

                    if(domains.indexOf(url)==-1) {
                        domains.push(url);
                    }
                }

            }
            return domains;
        };

        return service;
    })
    .run(function (bluestorm, $window) {
        if(bluestorm.env=='development') {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'http://'+($window.location.hostname||'localhost')+':35729/livereload.js?snipver=1';
            document.body.appendChild(script);
        }
    })
    .factory('socket', function($rootScope, bluestorm, $cookies) {
        var socket = io(bluestorm.urls.socket);
        return {
            on: function(eventName, callback) {
                for(var key in socket._callbacks) {
                    if(key==eventName) {
                        socket.removeListener(key);
                    }
                }
                socket.on(eventName, function() {
                    var args = arguments;
                    $rootScope.$apply(function() {
                        callback.apply(socket, args);
                    });
                });
            },
            emit: function(eventName, data, callback) {

                if (typeof(data) === 'function' || typeof(data) === 'undefined') {
                    callback = data;
                    data = {};
                }
                var res = {
                    token: $cookies.get('bluestorm_token'),
                    data: data
                };
                socket.emit(eventName, res, function() {
                    var args = arguments;
                    $rootScope.$apply(function() {
                        if (callback) {
                            callback.apply(socket, args);
                        }
                    });
                });
            }
        };
    });


text:
package com.github.windbender.service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.github.windbender.WLCDMServerConfiguration;
import com.github.windbender.domain.User;

public class PasswordUpdatedMessage implements MessageCreator {

	User u;
	WLCDMServerConfiguration configuration;
	public PasswordUpdatedMessage(User u,WLCDMServerConfiguration configuration) {
		this.u = u;
		this.configuration = configuration;
	}

	@Override
	public MimeMessage createMessage(Session session) throws AddressException,
			MessagingException {
		MimeMessage message = new MimeMessage(session);

		// Set From: header field of the header.
		message.setFrom(new InternetAddress(configuration.getEmailFrom()));

		// Set To: header field of the header.
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail()));

		// Set Subject: header field
		message.setSubject("wildlifecam: Your password has been updated");

		// Send the actual HTML message, as big as you like
		message.setContent(
				"
This message is to inform you that your password has been updated
",
				"text/html");
		return message;
	}

}


text:
require 'securerandom'

module QA
  module Resource
    class Runner < Base
      attr_writer :name, :tags, :image

      attribute :project do
        Project.fabricate! do |resource|
          resource.name = 'project-with-ci-cd'
          resource.description = 'Project with CI/CD Pipelines'
        end
      end

      def name
        @name || "qa-runner-#{SecureRandom.hex(4)}"
      end

      def tags
        @tags || %w[qa e2e]
      end

      def image
        @image || 'gitlab/gitlab-runner:alpine'
      end

      def fabricate!
        project.visit!

        Page::Project::Menu.perform(&:go_to_ci_cd_settings)

        Service::Runner.new(name).tap do |runner|
          Page::Project::Settings::CICD.perform do |settings|
            settings.expand_runners_settings do |runners|
              runner.pull
              runner.token = runners.registration_token
              runner.address = runners.coordinator_address
              runner.tags = tags
              runner.image = image
              runner.register!
            end
          end
        end
      end
    end
  end
end


text:
@implementation EventsourceSingleton

-(NSString*)getInitialDefaultID {
    return @"SCN1";
}

-(void) enumerate:(id<IMethodResult>)methodResult {
    NSMutableArray* ar = [NSMutableArray arrayWithCapacity:2];
    [ar addObject:@"SCN1"];
    [ar addObject:@"SCN2"];
    [methodResult setResult:ar];
}

@end


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MyShop
{
	public class Grouping<K, T> : ObservableCollection<T>
	{
		public K Key { get; private set; }

		public Grouping(K key, IEnumerable<T> items)
		{
			Key = key;
			foreach (var item in items)
				this.Items.Add(item);
		}
	}
}


text:
require 'test_helper'

class <%= controller_class_name %>HelperTest < ActionView::TestCase

  should 'test something' do
    assert true
  end

end


text:
<resources>
    <string name="app_name">kotlin_zhihu</string>
</resources>


text:
/**
 * Class: Jobs.java
 * Developer: Eric Cardona
 * Creation Date: 02-12-2015
 * Description: The data class for Jobs in the AlumniNetwork application.
 *
 * @author Eric Cardona
 */

//Package Declarations
package com.ndnu.alumni.model;

public class Jobs
{
	////Data Members////
	private int JobID;
	private int UserID;
	private String JobTitle;
	private String CompanyName;
	private double Salary;
	private String Description;
	private String JobType;
	private String StartDate;
	private String EndDate;

	////Class Constructors////
	/**
	 * Method Description: Empty constructor that sets data members to null values.
	 *
	 */
	public Jobs()
	{
		this.JobID = 0;
		this.UserID = 0;
		this.JobTitle = "";
		this.CompanyName = "";
		this.Salary = 0.0;
		this.Description = "";
		this.JobType = "";
		this.StartDate = "";
		this.EndDate = "";
	}

	/**
	 * Method Description: Constructor that sets data members to user supplied input.
	 * @param JobID
	 * @param UserID
	 * @param JobTitle
	 * @param CompanyName
	 * @param Salary
	 * @param Description
	 * @param JobType
	 * @param StartDate
	 * @param EndDate
	 */
	public Jobs(int JobID, int UserID, String JobTitle,
			String CompanyName, double Salary, String Description, String JobType,
			String StartDate, String EndDate)
	{
		this.JobID = JobID;
		this.UserID = UserID;
		this.JobTitle = JobTitle;
		this.CompanyName = CompanyName;
		this.Salary = Salary;
		this.Description = Description;
		this.JobType = JobType;
		this.StartDate = StartDate;
		this.EndDate = EndDate;
	}

	////Getters and Setters////
	/**
	 * Method Description: Sets the JobID data member.
	 * @param JobID
	 */
	public void setJobID(int JobID)
	{
		this.JobID = JobID;
	}

	/**
	 * Method Description: Sets the UserID data member.
	 * @param UserID
	 */
	public void setUserID(int UserID)
	{
		this.UserID = UserID;
	}

	/**
	 * Method Description: Sets the JobTitle data member.
	 * @param JobTitle
	 */
	public void setJobTitle(String JobTitle)
	{
		this.JobTitle = JobTitle;
	}

	/**
	 * Method Description: Sets the CompanyName data member.
	 * @param CompanyName
	 */
	public void setCompanyName(String CompanyName)
	{
		this.CompanyName = CompanyName;
	}

	/**
	 * Method Description: Sets the Salary data member.
	 * @param Salary
	 */
	public void setSalary(double Salary)
	{
		this.Salary = Salary;
	}

	/**
	 * Method Description: Sets the Description data member.
	 * @param Description
	 */
	public void setDescription(String Description)
	{
		this.Description = Description;
	}

	/**
	 * Method Description: Sets the JobType data member.
	 * @param JobType
	 */
	public void setJobType(String JobType)
	{
		this.JobType = JobType;
	}

	/**
	 * Method Description: Sets the StartDate data member.
	 * @param StartDate
	 */
	public void setStartDate(String StartDate)
	{
		this.StartDate = StartDate;
	}

	/**
	 * Method Description: Sets the EndDate data member.
	 * @param EndDate
	 */
	public void setEndDate(String EndDate)
	{
		this.EndDate = EndDate;
	}

	/**
	 * Method Description: Returns a reference to the JobID data member.
	 * @return JobID
	 */
	public int getJobID()
	{
		return this.JobID;
	}

	/**
	 * Method Description: Returns a reference to the UserID data member.
	 * @return UserID
	 */
	public int getUserID()
	{
		return this.UserID;
	}

	/**
	 * Method Description: Returns a reference to the JobTitle data member.
	 * @return JobTitle
	 */
	public String getJobTitle()
	{
		return this.JobTitle;
	}

	/**
	 * Method Description: Returns a reference to the CompanyName data member.
	 * @return CompanyName
	 */
	public String getCompanyName()
	{
		return this.CompanyName;
	}

	/**
	 * Method Description: Returns a reference to the Salary data member.
	 * @return Salary
	 */
	public double getSalary()
	{
		return this.Salary;
	}

	/**
	 * Method Description: Returns a reference to the Description data member.
	 * @return Description
	 */
	public String getDescription()
	{
		return this.Description;
	}

	/**
	 * Method Description: Returns a reference to the JobType data member.
	 * @return JobType
	 */
	public String getJobType()
	{
		return this.JobType;
	}

	/**
	 * Method Description: Returns a reference to the StartDate data member.
	 * @return StartDate
	 */
	public String getStartDate()
	{
		return this.StartDate;
	}

	/**
	 * Method Description: Returns a reference to the EndDate data member.
	 * @return EndDate
	 */
	public String getEndDate()
	{
		return this.EndDate;
	}

	////Returning Methods////
	/**
	 * Method Description: Override of toString
	 * @return all data members
	 */
	public String toString()
	{
		return (this.JobID + "\n" + this.UserID + "\n" +
				this.JobTitle + "\n" + this.CompanyName + "\n" + this.Salary + "\n"  +
				this.Description + "\n" + this.JobType + "\n" + this.StartDate + "\n" +
				this.EndDate + "\n");
	}
}


text:
package com.rp.aula.design.abstractfactory.exercicio;

public class PizzaFornoConvencionalFactory implements ProdutoFactory {

	@Override
	public Pizza criaPizza() {
		return new PizzaFornoConvencional();
	}

	@Override
	public Esfirra criaEsfirra() {
		return new EsfirraFornoConvencional();
	}

}


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\PageCache\Test\Unit\Observer;

class ProcessLayoutRenderElementTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Magento\PageCache\Observer\ProcessLayoutRenderElement */
    protected $_model;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\PageCache\Model\Config */
    protected $_configMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Element\AbstractBlock */
    protected $_blockMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\View\Layout */
    protected $_layoutMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Event\Observer */
    protected $_observerMock;

    /** @var \Magento\Framework\DataObject */
    protected $_transport;

    /**
     * Set up all mocks and data for test
     */
    protected function setUp()
    {
        $this->_configMock = $this->getMock(
            'Magento\PageCache\Model\Config',
            ['getType', 'isEnabled'],
            [],
            '',
            false
        );

        $this->_model = new \Magento\PageCache\Observer\ProcessLayoutRenderElement($this->_configMock);
        $this->_observerMock = $this->getMock(
            'Magento\Framework\Event\Observer',
            ['getEvent'],
            [],
            '',
            false
        );
        $this->_layoutMock = $this->getMock(
            'Magento\Framework\View\Layout',
            ['isCacheable', 'getBlock', 'getUpdate', 'getHandles'],
            [],
            '',
            false
        );
        $this->_blockMock = $this->getMockForAbstractClass(
            'Magento\Framework\View\Element\AbstractBlock',
            [],
            '',
            false,
            true,
            true,
            ['getData', 'isScopePrivate', 'getNameInLayout', 'getUrl']
        );
        $this->_transport = new \Magento\Framework\DataObject(['output' => 'test output html']);
    }

    /**
     * @param bool $cacheState
     * @param bool $varnishIsEnabled
     * @param bool $scopeIsPrivate
     * @param int|null $blockTtl
     * @param string $expectedOutput
     * @dataProvider processLayoutRenderDataProvider
     */
    public function testExecute(
        $cacheState,
        $varnishIsEnabled,
        $scopeIsPrivate,
        $blockTtl,
        $expectedOutput
    ) {
        $eventMock = $this->getMock(
            'Magento\Framework\Event',
            ['getLayout', 'getElementName', 'getTransport'],
            [],
            '',
            false
        );
        $this->_observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($eventMock));
        $eventMock->expects($this->once())->method('getLayout')->will($this->returnValue($this->_layoutMock));
        $this->_configMock->expects($this->any())->method('isEnabled')->will($this->returnValue($cacheState));

        if ($cacheState) {
            $eventMock->expects($this->once())
                ->method('getElementName')
                ->will($this->returnValue('blockName'));

            $eventMock->expects($this->once())
                ->method('getTransport')
                ->will($this->returnValue($this->_transport));

            $this->_layoutMock->expects($this->once())
                ->method('isCacheable')
                ->will($this->returnValue(true));

            $this->_layoutMock->expects($this->any())
                ->method('getUpdate')
                ->will($this->returnSelf());

            $this->_layoutMock->expects($this->any())
                ->method('getHandles')
                ->will($this->returnValue([]));

            $this->_layoutMock->expects($this->once())
                ->method('getBlock')
                ->will($this->returnValue($this->_blockMock));

            if ($varnishIsEnabled) {
                $this->_blockMock->expects($this->once())
                    ->method('getData')
                    ->with('ttl')
                    ->will($this->returnValue($blockTtl));
                $this->_blockMock->expects($this->any())
                    ->method('getUrl')
                    ->will($this->returnValue('page_cache/block/wrapesi/with/handles/and/other/stuff'));
            }
            if ($scopeIsPrivate) {
                $this->_blockMock->expects($this->once())
                    ->method('getNameInLayout')
                    ->will($this->returnValue('testBlockName'));
                $this->_blockMock->expects($this->once())
                    ->method('isScopePrivate')
                    ->will($this->returnValue($scopeIsPrivate));
            }
            $this->_configMock->expects($this->any())->method('getType')->will($this->returnValue($varnishIsEnabled));
        }
        $this->_model->execute($this->_observerMock);

        $this->assertEquals($expectedOutput, $this->_transport['output']);
    }

    /**
     * Data provider for testProcessLayoutRenderElement
     *
     * @return array
     */
    public function processLayoutRenderDataProvider()
    {
        return [
            'full_page type and Varnish enabled, public scope, ttl is set' => [
                true,
                true,
                false,
                360,
                '<esi:include src="page_cache/block/wrapesi/with/handles/and/other/stuff" />',
            ],
            'full_page type and Varnish enabled, public scope, ttl is not set' => [
                true,
                true,
                false,
                null,
                'test output html',
            ],
            'full_page type enabled, Varnish disabled, public scope, ttl is set' => [
                true,
                false,
                false,
                360,
                'test output html',
            ],
            'full_page type enabled, Varnish disabled, public scope, ttl is not set' => [
                true,
                false,
                false,
                null,
                'test output html',
            ],
            'full_page type enabled, Varnish disabled, private scope, ttl is not set' => [
                true,
                false,
                true,
                null,
                '<!-- BLOCK testBlockName -->test output html<!-- /BLOCK testBlockName -->',
            ],
            'full_page type is disabled, Varnish enabled' => [false, true, false, null, 'test output html']
        ];
    }
}


text:
EP 226 - Waves & Oscillations & Thermodyamics
========

**Author:Manish Goregaokar**

Basic course on thermodynamics, waves, and oscillations.

The notes contain various formulae which I found useful to remember for this course


text:
'use strict';

var taskConfig = function(grunt) {
  grunt.registerTask('serve', 'Open a development server within your browser', function(target) {
    // Allow for remote access to app/site via the 0.0.0.0 ip address
    if (grunt.option('allow-remote')) {
      grunt.config.set('connect.options.hostname', '0.0.0.0');
    }

    if (target === 'dist') {
      return grunt.task.run(['build',
      'env:all', 'env:prod', 'express:dist', 'open', 'keepalive']);
    }

    grunt.task.run([
      'clean:tmp',
      'env:all',
      'copy:server',
      'injector',
      'wiredep',
      'browserify:server',
      'sass:server',
      'styleguide:server',
      'jsdoc:server',
      'autoprefixer:server'
    ]);

    if (target === 'nowatch') {
      return;
    }

    grunt.task.run([
      'express:server',
      'wait',
      'open'
    ]);

    if (target === 'docs') {
      return grunt.task.run(['listen:docs']);
    }

    return grunt.task.run(['watch']);

  });
};

module.exports = taskConfig;


text:
<?php
use Df\Payment\Method as M;
use Magento\Payment\Model\MethodInterface as IM;

/**
 * 2016-07-14 Поддержка тегов HTML обеспечивается шаблоном Df_Checkout/messages
 * @param string|null $m [optional]
 */
function dfp_error($m = null):void {df_checkout_error(dfp_error_message($m));}

/**
 * 2016-08-19
 * @used-by dfp_error()
 * @used-by \Df\Payment\PlaceOrderInternal::message()
 * @used-by \Dfe\Klarna\Exception::messageC()
 * @used-by \Dfe\Omise\Exception\Charge::messageC()
 * @used-by \Dfe\Stripe\Exception::messageC()
 * @used-by \Dfe\TwoCheckout\Exception::messageC()
 * @param string|null $m [optional]
 */
function dfp_error_message($m = ''):string {return nl2br(df_cc_n(
	__("Sorry, the payment attempt is failed.")
	, $m ? __("The payment service's message is «<b>%1</b>».", $m) : ''
	,__("Please try again, or try another payment method.")
));}

/**
 * 2016-09-08
 * @used-by \CanadaSatellite\Bambora\Action::check() (https://github.com/canadasatellite-ca/bambora)
 * @used-by \Df\GingerPaymentsBase\Init\Action::res()
 * @used-by \Df\Payment\CustomerReturn::execute()
 * @used-by \Df\Payment\Init\Action::action()
 * @used-by \Df\StripeClone\Method::transInfo()
 * @used-by \Dfe\AlphaCommerceHub\Method::transInfo()
 * @used-by \Dfe\CheckoutCom\Handler::p()
 * @used-by \Dfe\CheckoutCom\Handler\CustomerReturn::p()
 * @used-by \Dfe\CheckoutCom\Response::a()
 * @used-by \Dfe\Qiwi\Init\Action::preorder()
 * @used-by \Dfe\SecurePay\Refund::process()
 * @used-by \Dfe\TwoCheckout\Handler::p()
 * @param string|object $m
 * @param string|mixed[] $d
 */
function dfp_report($m, $d, string $title = '', string $suffix = ''):void {
	dfp_sentry_tags($m);
	df_sentry($m, $title ?: dfpm_title($m), ['extra' => is_array($d) ? $d : ['Payment Data' => $d]]);
	df_log_l(df_module_name_c($m), $d, $suffix);
}

/**
 * 2017-02-09
 * @used-by dfp_report()
 * @used-by \Df\Payment\W\Action::notImplemented()
 * @used-by \Df\Payment\Method::action()
 * @used-by \Df\Payment\W\Handler::log()
 * @param string|object $c
 */
function dfp_sentry_tags($c):void {
	$m = dfpm($c); /** @var IM|M $m */
	df_sentry_tags($m,
		[dfpm_title($m) => df_package_version($c)]
		+ (!dfp_my($m) ? [] : ['Payment Mode' => $m->test('development', 'production')])
	);
}


text:
require 'delegate'
require 'active_support/core_ext'
require 'newsreports'

module NewsreportsRails
  class NewsreportsTemplate < SimpleDelegator
    attr_accessor :_generate_options

    def initialize(newsreports_report_base_obj, template_context, template_virtual_path)
      @_template_context = template_context
      @_template_virtual_path = template_virtual_path
      super(newsreports_report_base_obj)
    end

    def partial!(options, locals = {})
      case options
      when Hash
        options[:locals] ||= {}
        options[:locals].merge!(:report => self)
        @_template_context.render(options)
      else
        @_template_context.render(options, locals.merge(:report => self))
      end
    end

    def search_tlf_path(virtual_path)
      "#{virtual_path || @_template_virtual_path}.tlf"
    end

    def generate_options(options)
      self._generate_options = options
    end

    def set_layout(options = {})
      _options = options ? options.dup: {}
      tlf_path = search_tlf_path(_options[:tlf])

      ActionController::Base.view_paths.each do |view_path|
        full_path = File.join(view_path.to_s, tlf_path)
        if File.exist?(full_path)
          return self.use_layout(full_path, *([_options[:layout_options]].compact))
        end
      end
      raise("#{tlf_path} not found.") unless _options[:allow_no_layout]
    end
  end

  class TemplateHandler
    cattr_accessor :default_format
    self.default_format = 'application/pdf'

    def self.call(template)
      %{
        if defined?(report)
          #{template.source}
        else
          generate_options = nil
          ThinReports::Report.create do |__report__|
            report = NewsreportsRails::NewsreportsTemplate.new(__report__, self, '#{template.virtual_path}')
            report.set_layout :allow_no_layout => true

            #{template.source}

            generate_options = report._generate_options
          end.generate(*([generate_options].compact))
        end
      }
    end
  end
end

ActionView::Template.register_template_handler :newsreports, NewsreportsRails::TemplateHandler


text:
<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
    <cacheControl>Public</cacheControl>
    <contentType>application/javascript</contentType>
    <description>angularanimate</description>
</StaticResource>


text:
namespace glbinding
{

class GLBINDING_API Version
{
public:
    Version();
    Version(int majorVersion, int minorVersion);

    bool operator< (const Version & version) const;
    bool operator> (const Version & version) const;
    bool operator==(const Version & version) const;
    bool operator!=(const Version & version) const;
    bool operator>=(const Version & version) const;
    bool operator<=(const Version & version) const;

    operator std::pair<unsigned char,  unsigned char> () const;
    operator std::pair<unsigned short, unsigned short>() const;
    operator std::pair<unsigned int,   unsigned int>  () const;

	std::string toString() const;

    bool isValid() const;
    bool isNull() const;

    const Version & nearest() const;

    static const std::set<Version> & versions();
    static const Version & latest();

public:
    int m_major;
    int m_minor;

protected:
    static const std::set<Version> s_validVersions;
    static const Version s_latest;
};

} // namespace glbinding

GLBINDING_API std::ostream & operator<<(std::ostream & stream, const glbinding::Version & version);


text:
VPRubberMenu
============

UICollectionView - Menu component with 'rubbery' effect inspired by Nike 'Making' application.
*Created just for fun :)*

![Screenshot](doc/img/VPRubber.gif "doc/img/VPRubber.gif")
![Screenshot](doc/img/ScreenShot 1.png "doc/img/ScreenShot 1.png")

Usage
============
Use VPRubberLayout with your UICollectionView as UICollectionViewFlowLayout.
Use VPRubberCell as your UICollectionViewCell.
Use VPRubberSettings for configuring animation.

Authors
=======

**Vitaliy Popruzhenko**

+ http://lnkd.in/Ruy9XF
+ http://github.com/vitalykw

Credits
=======
Inspired by [Making of Making Powered by NIKE MSI](https://itunes.apple.com/us/app/making-making-powered-by-nike/id662227880?mt=8)

## License:
Licensed under the MIT license


text:
<?php

namespace AppBundle\Validator;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class BirdCheck extends Constraint
{
    public $message  = "bird.wrong";

    public function validatedBy()
    {
        return 'app.bird.check';
    }

}


text:
package es.deusto.weblab.client.ui.widgets.exceptions;

import es.deusto.weblab.client.WebLabException;

public class WlWidgetException extends WebLabException {
	private static final long serialVersionUID = 7797395269457146776L;

	public WlWidgetException() {
	}

	public WlWidgetException(String arg0) {
		super(arg0);
	}

	public WlWidgetException(Throwable arg0) {
		super(arg0);
	}

	public WlWidgetException(String arg0, Throwable arg1) {
		super(arg0, arg1);
	}

}


text:
layout: post
title: Faculty posts in SGPGIMS Lucknow last date 31st March-2016
date: 2016-02-18 04:24
comments: true
tags:  Faculty Institute Medical UP
archive: false
---
SGPGIMS - The Sanjay Gandhi Post-Graduate Institute of Medical Sciences, Lucknow invites applications on prescribed form for the following positions of  Faculty :

- Professor : 02 posts in various departments
- Associate + Additional Professor : 01 post in various departments
- Professor : 04 posts in various departments
- Assistant Professors : 59  posts in various departments

**How to Apply** : Candidate should send the application on in prescribed format and a Bank DD of Rs. 1000/- and $100 in case of outside candidates in favour of Director, SGPGIMS Lucknow Academic Account payable at the SBI SGPGIMS Branch Lucknow (code no. 7789). Application should be addressed to the Director, Sanjay Gandhi Post Graduate institute of Medical Scinces, Lucknow (UP) and should be sent by registered/ speed post only. Last date is 31/03/2016.  (Last date is 15/04/2016 for overseas candidates)

Detailed advertisement, addendum/ corrigendum  and application format is available at <http://www.sgpgi.ac.in/safai_link.html>


text:
package org.apache.druid.query.aggregation.datasketches.hll.sql;

import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.query.aggregation.PostAggregator;
import org.apache.druid.query.aggregation.datasketches.hll.HllSketchToStringPostAggregator;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.sql.calcite.expression.DirectOperatorConversion;
import org.apache.druid.sql.calcite.expression.DruidExpression;
import org.apache.druid.sql.calcite.expression.OperatorConversions;
import org.apache.druid.sql.calcite.expression.PostAggregatorVisitor;
import org.apache.druid.sql.calcite.planner.PlannerContext;

import javax.annotation.Nullable;
import java.util.List;

public class HllSketchToStringOperatorConversion extends DirectOperatorConversion
{
  private static final String FUNCTION_NAME = "HLL_SKETCH_TO_STRING";
  private static final SqlFunction SQL_FUNCTION = OperatorConversions
      .operatorBuilder(StringUtils.toUpperCase(FUNCTION_NAME))
      .operandTypes(SqlTypeFamily.ANY)
      .returnType(SqlTypeName.VARCHAR)
      .build();

  public HllSketchToStringOperatorConversion()
  {
    super(SQL_FUNCTION, FUNCTION_NAME);
  }

  @Override
  public SqlOperator calciteOperator()
  {
    return SQL_FUNCTION;
  }

  @Override
  public DruidExpression toDruidExpression(
      PlannerContext plannerContext,
      RowSignature rowSignature,
      RexNode rexNode
  )
  {
    return null;
  }

  @Nullable
  @Override
  public PostAggregator toPostAggregator(
      PlannerContext plannerContext,
      RowSignature rowSignature,
      RexNode rexNode,
      PostAggregatorVisitor postAggregatorVisitor
  )
  {
    final List<RexNode> operands = ((RexCall) rexNode).getOperands();
    final PostAggregator firstOperand = OperatorConversions.toPostAggregator(
        plannerContext,
        rowSignature,
        operands.get(0),
        postAggregatorVisitor
    );

    if (firstOperand == null) {
      return null;
    }

    return new HllSketchToStringPostAggregator(
        postAggregatorVisitor.getOutputNamePrefix() + postAggregatorVisitor.getAndIncrementCounter(),
        firstOperand
    );
  }
}


text:
#import "SBBLKGUITextField.h"
#import "SBUtil.h"

@implementation SBBLKGUITextField

+ (void)initialize
{
	if (self == [SBBLKGUITextField class])
	{
		[self setCellClass:[SBBLKGUITextFieldCell class]];
	}
}

+ (Class)cellClass
{
	return [SBBLKGUITextFieldCell class];
}

- (id)initWithFrame:(NSRect)rect
{
	if (self = [super initWithFrame:rect])
	{
		[self setDefaultValues];
	}
	return self;
}

- (void)setDefaultValues
{
	[self setAlignment:NSRightTextAlignment];
	[self setDrawsBackground:NO];
	[self setTextColor:[NSColor whiteColor]];
}

@end

@implementation SBBLKGUITextFieldCell

- (id)init
{
	if (self = [super init])
	{
		[self setDefaultValues];
	}
	return self;
}

- (void)setDefaultValues
{
	[self setWraps:NO];
	[self setScrollable:YES];
	[self setFocusRingType:NSFocusRingTypeExterior];
}

- (NSText *)setUpFieldEditorAttributes:(NSText *)textObj
{
	NSText *text = [super setUpFieldEditorAttributes:textObj];
	if ([text isKindOfClass:[NSTextView class]])
	{
		NSDictionary *attributes = @{NSForegroundColorAttributeName: [NSColor whiteColor],
									NSBackgroundColorAttributeName: [NSColor grayColor]};
		[(NSTextView *)text setInsertionPointColor:[NSColor whiteColor]];
		[(NSTextView *)text setSelectedTextAttributes:attributes];
	}
	return text;
}

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
	CGRect r = CGRectZero;
	CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
	CGPathRef path = nil;
	CGFloat alpha = [controlView respondsToSelector:@selector(isEnabled)] ? ([(NSTextField *)controlView isEnabled] ? 1.0 : 0.2) : 1.0;

	r = NSRectToCGRect(cellFrame);
	path = SBRoundedPath(r, SBFieldRoundedCurve, 0, YES, YES);
	CGContextSaveGState(ctx);
	CGContextAddPath(ctx, path);
	CGContextSetRGBFillColor(ctx, 0.0, 0.0, 0.0, alpha * 0.1);
	CGContextFillPath(ctx);
	CGContextRestoreGState(ctx);

	r = NSRectToCGRect(cellFrame);
	r.origin.x += 0.5;
	r.origin.y += 0.5;
	r.size.width -= 1.0;
	r.size.height -= 1.0;
	path = SBRoundedPath(r, SBFieldRoundedCurve, 0, YES, YES);
	CGContextSaveGState(ctx);
	CGContextAddPath(ctx, path);
	CGContextSetLineWidth(ctx, 0.5);
	CGContextSetRGBStrokeColor(ctx, 1.0, 1.0, 1.0, alpha);
	CGContextStrokePath(ctx);
	CGContextRestoreGState(ctx);

	[self drawInteriorWithFrame:cellFrame inView:controlView];
}

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
	[super drawInteriorWithFrame:cellFrame inView:controlView];
}

- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject event:(NSEvent *)theEvent
{
	[super editWithFrame:aRect inView:controlView editor:textObj delegate:anObject event:theEvent];
}

- (void) selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
{
	[super selectWithFrame:aRect inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
}

@end


text:
package org.apache.helix.integration.task;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.helix.HelixException;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.MasterSlaveSMD;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.JobContext;
import org.apache.helix.task.TaskConfig;
import org.apache.helix.task.TaskPartitionState;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.TaskUtil;
import org.apache.helix.task.Workflow;
import org.apache.helix.task.WorkflowConfig;
import org.apache.helix.task.WorkflowContext;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestAddDeleteTask extends TaskTestBase {
  private static final String DATABASE = "TestDB_" + TestHelper.getTestClassName();

  @BeforeClass
  public void beforeClass() throws Exception {
    _numNodes = 3;
    super.beforeClass();
  }

  @AfterClass
  public void afterClass() throws Exception {
    super.afterClass();
  }

  @Test
  public void testAddDeleteTaskWorkflowMissing() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";
    TaskConfig task = new TaskConfig(null, null, null, null);
    try {
      _driver.addTask(workflowName, jobName, task);
      Assert.fail("Exception is expected because workflow config is missing");
    } catch (IllegalArgumentException e) {
      // IllegalArgumentException Exception is expected because workflow config is missing
    }

    try {
      _driver.deleteTask(workflowName, jobName, task.getId());
      Assert.fail("Exception is expected because workflow config is missing");
    } catch (IllegalArgumentException e) {
      // IllegalArgumentException Exception is expected because workflow config is missing
    }
  }

  @Test(dependsOnMethods = "testAddDeleteTaskWorkflowMissing")
  public void testAddDeleteTaskJobMissing() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    Workflow.Builder workflowBuilder1 = new Workflow.Builder(workflowName);
    _driver.start(workflowBuilder1.build());

    // Make sure workflow config and context have been created
    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowConfig config = _driver.getWorkflowConfig(workflowName);
      WorkflowContext context = _driver.getWorkflowContext(workflowName);
      return (config != null && context != null);
    }, TestHelper.WAIT_DURATION));

    TaskConfig task = new TaskConfig(null, null, null, null);
    try {
      _driver.addTask(workflowName, jobName, task);
      Assert.fail("Exception is expected because job config is missing");
    } catch (IllegalArgumentException e) {
      // IllegalArgumentException Exception is expected because job config is missing
    }

    try {
      _driver.deleteTask(workflowName, jobName, task.getId());
      Assert.fail("Exception is expected because job config is missing");
    } catch (IllegalArgumentException e) {
      // IllegalArgumentException Exception is expected because job config is missing
    }
  }

  @Test(dependsOnMethods = "testAddDeleteTaskJobMissing")
  public void testAddTaskToTargetedJob() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
        .setTargetPartitionStates(Sets.newHashSet("MASTER")).setNumConcurrentTasksPerInstance(100)
        .setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    // Make sure workflow config and context have been created
    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowConfig config = _driver.getWorkflowConfig(workflowName);
      WorkflowContext context = _driver.getWorkflowContext(workflowName);
      return (config != null && context != null);
    }, TestHelper.WAIT_DURATION));

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    TaskConfig task = new TaskConfig(null, null, null, null);
    try {
      _driver.addTask(workflowName, jobName, task);
      Assert.fail("Exception is expected because job is targeted");
    } catch (HelixException e) {
      // Helix Exception is expected because job is targeted
    }
    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testAddTaskToTargetedJob")
  public void testAddTaskJobAndTaskCommand() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Make sure workflow config and context have been created
    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowConfig config = _driver.getWorkflowConfig(workflowName);
      WorkflowContext context = _driver.getWorkflowContext(workflowName);
      return (config != null && context != null);
    }, TestHelper.WAIT_DURATION));

    TaskConfig task = new TaskConfig("dummy", null, null, null);
    try {
      _driver.addTask(workflowName, jobName, task);
      Assert.fail("Exception is expected because job and task both have command field");
    } catch (HelixException e) {
      // Helix Exception is expected job config and new task have command field
    }
    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testAddTaskJobAndTaskCommand")
  public void testAddTaskJobNotRunning() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    // Make sure workflow config and context have been created
    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowConfig config = _driver.getWorkflowConfig(workflowName);
      WorkflowContext context = _driver.getWorkflowContext(workflowName);
      return (config != null && context != null);
    }, TestHelper.WAIT_DURATION));

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.COMPLETED);

    TaskConfig task = new TaskConfig(null, null, null, null);
    try {
      _driver.addTask(workflowName, jobName, task);
      Assert.fail("Exception is expected because job is not running");
    } catch (HelixException e) {
      // Helix Exception is expected because job id not running
    }
  }

  @Test(dependsOnMethods = "testAddTaskJobNotRunning")
  public void testAddTaskWithNullConfig() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    // Make sure workflow config and context have been created
    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowConfig config = _driver.getWorkflowConfig(workflowName);
      WorkflowContext context = _driver.getWorkflowContext(workflowName);
      return (config != null && context != null);
    }, TestHelper.WAIT_DURATION));

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    try {
      _driver.addTask(workflowName, jobName, null);
      Assert.fail("Exception is expected because task config is null");
    } catch (IllegalArgumentException e) {
      // IllegalArgumentException Exception is expected because task config is null
    }

    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testAddTaskWithNullConfig")
  public void testAddTaskSuccessfully() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Add short running task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);

    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      TaskPartitionState state = jobContext.getPartitionState(1);
      return (jobContext != null && state == TaskPartitionState.COMPLETED);
    }, TestHelper.WAIT_DURATION));

    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testAddTaskSuccessfully")
  public void testAddTaskTwice() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Add short running task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);

    try {
      _driver.addTask(workflowName, jobName, task);
      Assert.fail("Exception is expected because task is being added multiple times");
    } catch (HelixException e) {
      // Helix Exception is expected because task is being added multiple times
    }

    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      TaskPartitionState state = jobContext.getPartitionState(1);
      return (jobContext != null && state == TaskPartitionState.COMPLETED);
    }, TestHelper.WAIT_DURATION));

    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testAddTaskTwice")
  public void testAddTaskToJobNotStarted() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setExecutionDelay(5000L).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100)
        .setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName);
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (workflowContext != null && jobContext == null);
    }, TestHelper.WAIT_DURATION));

    // Add short running task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);

    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state = jobContext.getPartitionState(1);
      if (state == null) {
        return false;
      }
      return (state == TaskPartitionState.COMPLETED);
    }, TestHelper.WAIT_DURATION));

    _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED);
  }

  @Test(dependsOnMethods = "testAddTaskToJobNotStarted")
  public void testAddTaskWorkflowAndJobNotStarted() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);

    _controller.syncStop();
    _driver.start(workflowBuilder1.build());

    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName);
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (workflowContext == null && jobContext == null);
    }, TestHelper.WAIT_DURATION));

    // Add short running task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);

    // Start the Controller
    String controllerName = CONTROLLER_PREFIX + "_0";
    _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
    _controller.syncStart();

    _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED);
  }

  @Test(dependsOnMethods = "testAddTaskWorkflowAndJobNotStarted")
  public void testDeleteNonExistedTask() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "9999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);

    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);
    String dummyID = "1234";
    try {
      _driver.deleteTask(workflowName, jobName, dummyID);
      Assert.fail("Exception is expected because a task with such ID does not exists!");
    } catch (IllegalArgumentException e) {
      // IllegalArgumentException Exception is expected because task with such ID does not exists
    }
    _driver.waitToStop(workflowName, TestHelper.WAIT_DURATION);
  }

  @Test(dependsOnMethods = "testDeleteNonExistedTask")
  public void testDeleteTaskFromJobNotStarted() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setExecutionDelay(500000L).setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100)
        .setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    Assert.assertTrue(TestHelper.verify(() -> {
      WorkflowContext workflowContext = _driver.getWorkflowContext(workflowName);
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (workflowContext != null && jobContext == null);
    }, TestHelper.WAIT_DURATION));

    // Add short running task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "1000"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);

    JobConfig jobConfig =
        _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName));

    // Make sure task has been added to the job config
    Assert.assertTrue(jobConfig.getMapConfigs().containsKey(task.getId()));

    _driver.deleteTask(workflowName, jobName, task.getId());
    jobConfig = _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName));

    // Make sure task has been removed from job config
    Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task.getId()));

    _driver.deleteAndWaitForCompletion(workflowName, TestHelper.WAIT_DURATION);
  }

  @Test(dependsOnMethods = "testDeleteTaskFromJobNotStarted")
  public void testAddAndDeleteTask() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Wait until initial task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state = jobContext.getPartitionState(0);
      if (state == null) {
        return false;
      }
      return (state == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    // Add new task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);

    // Wait until new task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state = jobContext.getPartitionState(1);
      if (state == null) {
        return false;
      }
      return (state == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    _driver.deleteTask(workflowName, jobName, task.getId());
    JobConfig jobConfig =
        _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName));
    // Make sure task has been removed from job config
    Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task.getId()));

    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      return (!jobContext.getPartitionSet().contains(1));
    }, TestHelper.WAIT_DURATION));

    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testAddAndDeleteTask")
  public void testDeleteTaskAndJobCompleted() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "20000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Wait until initial task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state = jobContext.getPartitionState(0);
      if (state == null) {
        return false;
      }
      return (state == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    // Add new task
    Map<String, String> taskConfig1 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    Map<String, String> taskConfig2 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    TaskConfig task1 = new TaskConfig(null, taskConfig1, null, null);
    TaskConfig task2 = new TaskConfig(null, taskConfig2, null, null);

    _driver.addTask(workflowName, jobName, task1);
    _driver.addTask(workflowName, jobName, task2);

    // Wait until new task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state1 = jobContext.getPartitionState(1);
      TaskPartitionState state2 = jobContext.getPartitionState(2);
      if (state1 == null && state2 == null) {
        return false;
      }
      return (state1 == TaskPartitionState.RUNNING && state2 == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    _driver.deleteTask(workflowName, jobName, task1.getId());
    _driver.deleteTask(workflowName, jobName, task2.getId());

    JobConfig jobConfig =
        _driver.getJobConfig(TaskUtil.getNamespacedJobName(workflowName, jobName));
    // Make sure task has been removed from job config
    Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task1.getId()));
    Assert.assertFalse(jobConfig.getMapConfigs().containsKey(task2.getId()));

    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      return (!jobContext.getPartitionSet().contains(1)
          && !jobContext.getPartitionSet().contains(2));
    }, TestHelper.WAIT_DURATION));

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.COMPLETED);
    _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED);
  }

  @Test(dependsOnMethods = "testDeleteTaskAndJobCompleted")
  public void testDeleteMiddleTaskAndAdd() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "20000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Wait until initial task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state = jobContext.getPartitionState(0);
      if (state == null) {
        return false;
      }
      return (state == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    // Only one task (initial task) should be included in the job
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (jobContext.getPartitionSet().size() == 1);
    }, TestHelper.WAIT_DURATION));

    // Add new tasks
    Map<String, String> taskConfig1 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    Map<String, String> taskConfig2 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    Map<String, String> taskConfig3 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    Map<String, String> taskConfig4 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    TaskConfig task1 = new TaskConfig(null, taskConfig1, null, null);
    TaskConfig task2 = new TaskConfig(null, taskConfig2, null, null);
    TaskConfig task3 = new TaskConfig(null, taskConfig3, null, null);
    TaskConfig task4 = new TaskConfig(null, taskConfig4, null, null);

    _driver.addTask(workflowName, jobName, task1);
    _driver.addTask(workflowName, jobName, task2);
    _driver.addTask(workflowName, jobName, task3);
    _driver.addTask(workflowName, jobName, task4);

    // 5 tasks should be included in the job
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (jobContext.getPartitionSet().size() == 5);
    }, TestHelper.WAIT_DURATION));

    // All Task should be in RUNNING
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      int runningTasks = 0;
      for (Integer pId: jobContext.getPartitionSet()) {
        if (jobContext.getPartitionState(pId) == TaskPartitionState.RUNNING) {
          runningTasks++;
        }
      }
      return (runningTasks == 5);
    }, TestHelper.WAIT_DURATION));

    _driver.deleteTask(workflowName, jobName, task3.getId());

    // Since one of the tasks had been delete, we should expect 4 tasks in the context
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (jobContext.getPartitionSet().size() == 4);
    }, TestHelper.WAIT_DURATION));

    // Add new tasks and make sure the task is being added to context
    Map<String, String> taskConfig5 =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    TaskConfig task5 = new TaskConfig(null, taskConfig5, null, null);
    _driver.addTask(workflowName, jobName, task5);

    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      return (jobContext.getPartitionSet().size() == 5);
    }, TestHelper.WAIT_DURATION));
    _driver.stop(workflowName);
  }

  @Test(dependsOnMethods = "testDeleteTaskAndJobCompleted")
  public void testPartitionDropTargetedJob() throws Exception {
    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    _gSetupTool.addResourceToCluster(CLUSTER_NAME, DATABASE, 3, MASTER_SLAVE_STATE_MODEL,
        IdealState.RebalanceMode.SEMI_AUTO.name());
    _gSetupTool.rebalanceResource(CLUSTER_NAME, DATABASE, 3);
    List<String> preferenceList = new ArrayList<>();
    preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 0));
    preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 1));
    preferenceList.add(PARTICIPANT_PREFIX + "_" + (_startPort + 2));
    IdealState idealState = new IdealState(DATABASE);
    idealState.setPreferenceList(DATABASE + "_0", preferenceList);
    idealState.setPreferenceList(DATABASE + "_1", preferenceList);
    idealState.setPreferenceList(DATABASE + "_2", preferenceList);
    _gSetupTool.getClusterManagementTool().updateIdealState(CLUSTER_NAME, DATABASE, idealState);

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setTargetResource(DATABASE)
        .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(100).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "10000"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Wait until new task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state1 = jobContext.getPartitionState(0);
      TaskPartitionState state2 = jobContext.getPartitionState(1);
      TaskPartitionState state3 = jobContext.getPartitionState(2);
      if (state1 == null || state2 == null || state3 == null) {
        return false;
      }
      return (state1 == TaskPartitionState.RUNNING && state2 == TaskPartitionState.RUNNING
          && state3 == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    // Remove one partition from the IS
    idealState = new IdealState(DATABASE);
    idealState.setPreferenceList(DATABASE + "_1", preferenceList);
    _gSetupTool.getClusterManagementTool().removeFromIdealState(CLUSTER_NAME, DATABASE, idealState);

    Assert.assertTrue(TestHelper
        .verify(() -> ((_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName))
            .getPartitionSet().size() == 2)), TestHelper.WAIT_DURATION));

    _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED);
  }

  @Test(dependsOnMethods = "testPartitionDropTargetedJob")
  public void testAddDeleteTaskOneInstance() throws Exception {
    // Stop all participant other than participant 0
    for (int i = 1; i < _numNodes; i++) {
      super.stopParticipant(i);
      Assert.assertFalse(_participants[i].isConnected());
    }

    String workflowName = TestHelper.getTestMethodName();
    String jobName = "JOB0";

    JobConfig.Builder jobBuilder1 = new JobConfig.Builder().setWorkflow(workflowName)
        .setNumberOfTasks(1).setNumConcurrentTasksPerInstance(1).setCommand(MockTask.TASK_COMMAND)
        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));

    Workflow.Builder workflowBuilder1 =
        new Workflow.Builder(workflowName).addJob(jobName, jobBuilder1);
    _driver.start(workflowBuilder1.build());

    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, jobName),
        TaskState.IN_PROGRESS);

    // Wait until initial task goes to RUNNING state
    Assert.assertTrue(TestHelper.verify(() -> {
      JobContext jobContext =
          _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName));
      if (jobContext == null) {
        return false;
      }
      TaskPartitionState state = jobContext.getPartitionState(0);
      if (state == null) {
        return false;
      }
      return (state == TaskPartitionState.RUNNING);
    }, TestHelper.WAIT_DURATION));

    // Add new task
    Map<String, String> newTaskConfig =
        new HashMap<String, String>(ImmutableMap.of(MockTask.JOB_DELAY, "99999999"));
    TaskConfig task = new TaskConfig(null, newTaskConfig, null, null);
    _driver.addTask(workflowName, jobName, task);
    Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName))
        .getPartitionSet().size(), 2);
    // Since only one task is allowed per instance, the new task should be scheduled
    Assert.assertNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName))
        .getPartitionState(1));
    _driver.deleteTask(workflowName, jobName, task.getId());
    Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, jobName))
        .getPartitionSet().size(), 1);
    _driver.stop(workflowName);
  }
}


text:
var ansi = require('ansi-escape-sequences')
var differ = require('ansi-diff')
var pretty = require('prettier-bytes')
var keypress = require('keypress')
var strip = require('strip-ansi')
var nanoraf = require('nanoraf')

var StartDelimiter = '|'
var EndDelimiter = '|'
var Filled = '█'
var Empty = '░'
var NewlineMatcher = /\n/g

var files = [
  'assets',
  'documents',
  'scripts',
  'styles',
  'manifest',
  'service-worker'
]

module.exports = render

function render (state) {
  var diff = differ()

  var render = nanoraf(onrender, raf)

  process.stdout.on('resize', onresize)

  if (process.stdin.isTTY) {
    keypress(process.stdin)
    process.stdin.setRawMode(true)
    process.stdin.resume()
    process.stdin.on('keypress', onkeypress)
  }

  return render

  function onrender () {
    process.stdout.write(diff.update(view(state)))
  }

  function onresize () {
    diff.resize({ width: process.stdout.columns, height: process.stdout.rows })
    diff.update('')
    render()
  }

  function onkeypress (ch, key) {
    if (key && key.ctrl && key.name === 'c') {
      process.exit()
    } else if (ch === '1') {
      // TODO: Switch to the main view.
      render()
    } else if (ch === '2') {
      // TODO: Switch to the log view.
      render()
    } else if (ch === '3') {
      // TODO: Switch to the stats view.
      render()
    }
  }
}

function view (state) {
  if (state.error) {
    return '\x1b[33c' + state.error
  }

  var str = '\x1b[33c'
  str += header(state)
  str += '\n\n'
  str += files.reduce(function (str, filename) {
    var file = state.files[filename]
    if (!file) return ''
    var status = file.status
    var count = status === 'done' ? String(state.count[filename]) : ''
    if (status === 'done') status = clr(status, 'green')

    // Make it so singular words aren't pluralized.
    var name = count === '1'
      ? file.name.replace(/s$/, '')
      : file.name

    str += clr(padLeft(count, 3), 'yellow') + ' '
    str += padRight(clr(name, 'green'), 14)
    var size = pretty(file.size).replace(' ', '')
    str += pad(7 - size.length) + clr(size, 'magenta') + ' '
    str += clr(file.timestamp, 'cyan') + ' '
    str += progress(file.progress, 10) + ' '
    str += status

    return str + '\n'
  }, '') + '\n'

  var ssrState = 'Pending'

  if (state.ssr) {
    ssrState = state.ssr.success
      ? 'Success'
      : `Skipped - ${state.ssr.error.message} ${state.ssr.error.stack.split('\n')[1].trim()}`
  }
  str += 'Server Side Rendering: ' + ssrState + '\n'

  str += footer(state)

  // pad string with newlines to ensure old rendered lines are cleared
  var padLines = Math.max(process.stdout.rows - str.match(NewlineMatcher).length - 1, 0)
  str += '\n'.repeat(padLines)

  return str
}

// header
function header (state) {
  var SSEStatus = state.sse > 0
    ? clr('connected', 'green')
    : state.port
      ? 'ready'
      : clr('starting', 'yellow')

  var httpStatus = state.port
    ? clr(clr('https://localhost:' + state.port, 'underline'), 'blue')
    : clr('starting', 'yellow')

  var left = `HTTP: ${httpStatus}`
  var right = `Live Reload: ${SSEStatus}`
  return spaceBetween(left, right)
}

// footer
function footer (state) {
  var size = Object.keys(state.files).reduce(function (num, filename) {
    var file = state.files[filename]
    return num + file.size
  }, 0)
  var bottomLeft = tabBar(1, 0)

  var totalSize = clr(pretty(size).replace(' ', ''), 'magenta')
  var bottomRight = `Total size: ${totalSize}`
  return spaceBetween(bottomLeft, bottomRight)
}

function tabBar (count, curr) {
  var str = ''
  var tmp
  for (var i = 0; i < count; i++) {
    tmp = String(i + 1)
    if (curr === i) {
      tmp = `[ ${tmp} ]`
    } else {
      tmp = clr(tmp, 'gray')
      if (i !== 0) tmp = ' ' + tmp
      if (i !== count) tmp = tmp + ' '
    }
    str += tmp
  }
  return str
}

function clr (text, color) {
  return process.stdout.isTTY ? ansi.format(text, color) : text
}

function padLeft (str, num, char) {
  str = String(str)
  var len = strip(str).length
  return pad(num - len, char) + str
}

function padRight (str, num, char) {
  str = String(str)
  var len = strip(str).length
  return str + pad(num - len, char)
}

function pad (len, char) {
  char = String(char === undefined ? ' ' : char)
  var res = ''
  while (res.length < len) res += char
  return res
}

function progress (curr, max) {
  var filledLength = Math.floor((curr / 100) * max)
  var emptyLength = max - filledLength
  var i = 1 + filledLength
  var j = i + emptyLength

  var str = StartDelimiter
  while (str.length < i) str += Filled
  while (str.length < j) str += Empty
  str += EndDelimiter
  return str
}

function raf (cb) {
  setTimeout(cb, 50)
}

function spaceBetween (left, right) {
  var len = process.stdout.columns - strip(left).length - strip(right).length
  var space = ''
  for (var i = 0; i < len; i++) {
    space += ' '
  }
  return left + space + right
}


text:
<?php
namespace Skel\DependencyInjection;
use Skel\Lib\ErrorHandler;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class Application extends \Symfony\Component\Console\Application
{
    /**
     * @var ContainerBuilder
     */
    protected $container;

    public function getContainer()
    {
        return $this->container;
    }

    /**
     * @param string $baseNamespaceName Highest level namespace for the application
     */
    public function __construct($baseNamespaceName)
    {
        // our error handler
        ErrorHandler::register();

        // create and populate the container
        $this->container = new ContainerBuilder();

        // some useful paths
        $paths = array();
        $paths['root'] = __DIR__ . '/../../../';
        $paths['config'] = $paths['root'] . 'app/config/';
        $paths['build'] = $paths['root'] . 'build/';
        $this->container->setParameter('paths', $paths);

        // the main config
        $loader = new YamlFileLoader($this->container, new FileLocator($paths['config']));
        $loader->load('config.yml');

        // construct the application
        $app = $this->container->getParameter('application');
        $version = $this->container->getParameter('version');
        parent::__construct($app['name'], $version['current']);

        // and add commands to it
        $this->addConsoleCommands($baseNamespaceName);

        // may be we have some commands also
        $this->addConsoleCommands(__NAMESPACE__);
    }

    /**
     * Adds all existing console commands
     *
     * @param string $baseNamespaceName Base namespace for the commands
     */
    protected function addConsoleCommands($baseNamespaceName)
    {
        // get all namespaces from the composer autoload list
        $paths = $this->container->getParameter('paths');
        $namespaces = include $paths['root'] . '/vendor/composer/autoload_namespaces.php';

        // find the path for the namespace
        foreach ($namespaces as $namespace => $lookupPaths) {
            if ($namespace == $baseNamespaceName) {
                // add all existing commands
                foreach ($lookupPaths as $path) {
                    $commandPath = $path . '/' . $namespace . '/Console/Command/';
                    if (is_dir($commandPath)) {
                        $files = Finder::create()->files()->name('*Command.php')
                                                 ->in($path . '/' . $namespace . '/Console/Command/');
                        foreach ($files as $file) {
                            $className = $file->getBasename('.php'); // strip .php extension
                            $r = new \ReflectionClass($baseNamespaceName . '\Console\Command' . '\\' . $className);
                            if (!$r->isAbstract()) {
                                $this->add($r->newInstance());
                            }
                        }
                    }
                }
                break;
            }
        }
    }
}


text:
FROM php:7.4-fpm

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip \
    nodejs \
    npm

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd sockets mysqli

# Get latest Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Create system user to run Composer and Artisan Commands
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
    chown -R $user:$user /home/$user

# Install redis
RUN pecl install -o -f redis \
    &&  rm -rf /tmp/pear \
    &&  docker-php-ext-enable redis \
    &&  npm install

# Set working directory
WORKDIR /var/www

USER $user


text:
package toyota;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import apps.toyota.homePage.HomePage;
import apps.toyota.mainNavigation.MainNavigation;

import com.orasi.utils.Constants;
import com.orasi.utils.TestReporter;
import com.orasi.utils.Screenshot;
import com.orasi.utils.WebDriverSetup;
import com.orasi.utils.dataProviders.ExcelDataProvider;

public class ChangeZipCode {

	private String application = "";
	private String browserUnderTest = "";
	private String browserVersion = "";
	private String operatingSystem = "";
	private String runLocation = "";
	private String environment = "";
	private Map<String, WebDriver> drivers = new HashMap<String, WebDriver>();

	@DataProvider(name = "dataScenario")
	public Object[][] scenarios() {
		return new ExcelDataProvider(Constants.TOYOTA_DATAPROVIDER_PATH
				+ "ChangeZipCode.xlsx", "ChangeZipCode").getTestData();
	}

	@BeforeTest(groups = { "regression" })
	@Parameters({ "runLocation", "browserUnderTest", "browserVersion",
			"operatingSystem", "environment" })
	public void setup(@Optional String runLocation, String browserUnderTest,
			String browserVersion, String operatingSystem, String environment) {
		this.application = "Toyota";
		this.runLocation = runLocation;
		this.browserUnderTest = browserUnderTest;
		this.browserVersion = browserVersion;
		this.operatingSystem = operatingSystem;
		this.environment = environment;
	}

	@AfterMethod(groups = { "regression" })
	public synchronized void closeSession(ITestResult test) {
		System.out.println(test.getMethod().getMethodName());
		WebDriver driver = drivers.get(test.getMethod().getMethodName());

		// if is a failure, then take a screenshot
		if (test.getStatus() == ITestResult.FAILURE) {
			new Screenshot().takeScreenShot(test, driver);
		}

		if(driver.getWindowHandles().size() != 0){
			driver.quit();
		}
	}

	/**
	 * @throws IOException
	 * @throws InterruptedException
	 * @Summary: Changes zip code on Toyota.com website
	 * @Precondition:NA
	 * @Author: Waightstill W Avery
	 * @Version: 03/10/2015
	 * @Return: N/A
	 */
	@Test(dataProvider = "dataScenario", groups = { "regression" })
	public void testChangeZipCode(
			String testScenario, String zipCode) throws InterruptedException, IOException {

		String testName = new Object() {
		}.getClass().getEnclosingMethod().getName();
		//Uncomment the following line to have TestReporter outputs output to the console
		//TestReporter.setPrintToConsole(true);
		WebDriverSetup setup = new WebDriverSetup(application,
				browserUnderTest, browserVersion, operatingSystem, runLocation,
				environment);
		WebDriver driver = setup.initialize();

		System.out.println(testName);
		drivers.put(testName, driver);

		//Ensure the home page is loaded
		TestReporter.logScenario(testScenario);
		HomePage homePage = new HomePage(driver);
		Assert.assertEquals(homePage.pageLoaded(), true);

		//Change the zipcode
		MainNavigation mainNav = new MainNavigation(driver);
		mainNav.changeZipCodes(zipCode);
	}
}


text:
watson.framework.support.console.commands.development
=====================================================

.. automodule:: watson.framework.support.console.commands.development
    :members:
    :private-members: