text:
<?php

namespace Opis\Http;

use Opis\Stream\{IStream, Stream};

class Request extends Message
{
    /** @var string */
    protected $method;

    /** @var string */
    protected $requestTarget;

    /** @var bool */
    protected $secure;

    /** @var Uri */
    protected $uri;

    /** @var array|null */
    protected $cookies;

    /** @var array */
    protected $files;

    /** @var array|null */
    protected $query;

    /** @var array|null */
    protected $formData;

    /** @var ServerVariables */
    protected $serverVars;

    /**
     * Request constructor.
     * @param string $method
     * @param string $requestTarget
     * @param string $protocolVersion
     * @param bool $secure
     * @param array $headers
     * @param array $files
     * @param null|IStream $body
     * @param array|null $cookies
     * @param array|null $query
     * @param array|null $formData
     * @param ServerVariables|null $serverVars
     */
    public function __construct(
        string $method = 'GET',
        string $requestTarget = '/',
        string $protocolVersion = 'HTTP/1.1',
        bool $secure = false,
        array $headers = [],
        array $files = [],
        ?IStream $body = null,
        ?array $cookies = null,
        ?array $query = null,
        ?array $formData = null,
        ServerVariables $serverVars = null
    ) {

        $this->method = strtoupper($method);
        $this->requestTarget = $requestTarget;
        $this->files = $files;
        $this->secure = $secure;

        if (!in_array($this->method, ['POST', 'PUT', 'PATCH', 'DELETE'])) {
            $body = null;
        } else {
            if ($body === null) {
                $body = new Stream('php://input');
            }
        }

        $this->cookies = $cookies;
        $this->query = $query;
        $this->formData = $formData;
        $this->serverVars = $serverVars ?? new ServerVariables();

        parent::__construct($body, $headers, $protocolVersion);
    }

    /**
     * @return string
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    /**
     * @return string
     */
    public function getRequestTarget(): string
    {
        return $this->requestTarget;
    }

    /**
     * @return Uri
     */
    public function getUri(): Uri
    {
        if ($this->uri === null) {
            $uri = new Uri($this->requestTarget);

            $components = $uri->getComponents();

            if (!isset($components['host'])) {
                if (isset($this->headers['Host'])) {
                    $port = null;
                    $host = $this->headers['Host'];
                    if (strpos($host, ':') !== false) {
                        list($host, $port) = explode(':', $host);
                        $port = (int) $port;
                        if ($port < 0 || $port > 65535) {
                            $port = null;
                        }
                    }
                    $components['host'] = $host;
                    $components['port'] = $port;
                    $components['authority'] = $port === null ? $host : $host . ':' . $port;
                }
            }

            if (isset($components['host'])) {
                if (!isset($components['scheme'])) {
                    $components['scheme'] = $this->secure ? 'https' : 'http';
                }
                $uri = new Uri($components);
            }

            $this->uri = $uri;
        }

        return $this->uri;
    }

    /**
     * @return bool
     */
    public function isSecure(): bool
    {
        return $this->secure;
    }

    /**
     * @param string $name
     * @return bool
     */
    public function hasCookie(string $name): bool
    {
        return isset($this->getCookies()[$name]);
    }

    /**
     * @param string $name
     * @param bool $decode
     * @return string|null
     */
    public function getCookie(string $name, bool $decode = true): ?string
    {
        $cookie = $this->getCookies()[$name] ?? null;

        if ($decode && $cookie !== null) {
            return rawurldecode($cookie);
        }

        return $cookie;
    }

    /**
     * @return array
     */
    public function getCookies(): array
    {
        if ($this->cookies === null) {
            $result = [];
            $cookies = explode('; ', $this->headers['Cookie']);
            foreach ($cookies as $cookie) {
                list($name, $value) = explode('=', $cookie, 2);
                $name = trim($name);
                if (empty($name)) {
                    continue;
                }
                $result[$name] = trim($value, '"');
            }
            $this->cookies = $result;
        }

        return $this->cookies;
    }

    /**
     * @return IUploadedFile[]
     */
    public function getUploadedFiles(): array
    {
        return $this->files;
    }

    /**
     * @return array
     */
    public function getQuery(): array
    {
        if ($this->query === null) {
            $query = $this->getUri()->getQuery();
            if ($query === null) {
                $query = [];
            } else {
                parse_str($query, $query);
            }
            $this->query = $query;
        }

        return $this->query;
    }

    /**
     * @return array
     */
    public function getFormData(): array
    {
        if ($this->formData === null) {
            $data = [];
            if (isset($this->headers['Content-Type']) && 0 === strpos($this->headers['Content-Type'],
                    'application/x-www-form-urlencoded') && $this->body !== null) {
                parse_str((string)$this->body, $data);
            }
            $this->formData = $data;
        }

        return $this->formData;
    }

    /**
     * @return ServerVariables
     */
    public function getServerVariables(): ServerVariables
    {
        return $this->serverVars;
    }

    /**
     * @param string $name
     * @param null $default
     * @return mixed|null
     */
    public function query(string $name, $default = null)
    {
        return $this->getQuery()[$name] ?? $default;
    }

    /**
     * @param string $name
     * @param null $default
     * @return mixed|null
     */
    public function formData(string $name, $default = null)
    {
        return $this->getFormData()[$name] ?? $default;
    }

    /**
     * @param string $name
     * @return null|IUploadedFile
     */
    public function file(string $name): ?IUploadedFile
    {
        return $this->getUploadedFiles()[$name] ?? null;
    }

    /**
     * @return Request
     */
    public static function fromGlobals(): self
    {
        $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

        if ($method === 'POST') {
            if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
                $method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
            } elseif (isset($_POST['x_http_method_override'])) {
                $method = strtoupper($_POST['x_http_method_override']);
            }
        }

        $headers = [];

        foreach ($_SERVER as $key => $value) {
            if (!is_scalar($value)) {
                continue;
            }
            if (strpos($key, 'HTTP_') === 0) {
                $key = substr($key, 5);
            } elseif (!in_array($key, ['CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'])) {
                continue;
            }
            $key = implode('-', explode('_', $key));
            $headers[$key] = $value;
        }

        if (isset($_SERVER['PATH_INFO'])) {
            $requestTarget = $_SERVER['PATH_INFO'];
            if (isset($_SERVER['QUERY_STRING'])) {
                $requestTarget .= '?' . $_SERVER['QUERY_STRING'];
            }
        } else {
            $requestTarget = $_SERVER['REQUEST_URI'] ?? '/';
        }

        $protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
        $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
        $files = UploadedFile::parseFiles($_FILES);
        $serverVariables = new ServerVariables($_SERVER);

        return new self($method, $requestTarget, $protocol, $secure, $headers, $files, null, $_COOKIE, $_GET, $_POST,
            $serverVariables);
    }
}


text:
def testInner():
    class Outer:
        def __init__(self,x): self.x = x

        # if python ever gets class decorators,
        # an inner class could be specified as:
        #@innerclass
        class Inner:
            def __init__(self, y): self.y = y
            def sum(self):  return self.x + self.y
        # as of python 2.4
        Inner = innerclass(Inner)

    outer = Outer('foo')
    inner = outer.Inner('bar'); assert inner.sum() == 'foobar'
    # outer.x, inner.x, inner.__outer__.x refer to the same object
    outer.x = 'moo'; assert inner.sum() == 'moobar'
    inner.x = 'zoo'; assert inner.sum() == 'zoobar'
    inner.__outer__.x = 'coo'; assert inner.sum() == 'coobar'
    # an inner class must be bounded to an outer class instance
    try: Outer.Inner('foo')
    except AttributeError, e: pass #print e
    else: assert False

def testStaticInner():
    class Outer:

        x = 'foo'

        class Nested:
            def __init__(self, y): self.y = y
            def sum(self): return self.x + self.y
        Nested = nestedclass(Nested)

    outer = Outer()
    nested = Outer.Nested('bar'); assert nested.sum() == 'foobar'
    nested.x = 'moo'; assert Outer.x == 'moo' and nested.sum() == 'moobar'
    nested.y = 'baz'; assert nested.sum() == 'moobaz'

def innerclass(cls):
    '''Class decorator for making a class behave as a Java (non-static) inner
    class.

    Each instance of the decorated class is associated with an instance of its
    enclosing class. The outer instance is referenced implicitly when an
    attribute lookup fails in the inner object's namespace. It can also be
    referenced explicitly through the property '__outer__' of the inner
    instance.
    '''
    if hasattr(cls, '__outer__'):
        raise TypeError('Cannot set attribute "__outer__" in inner class')
    class InnerDescriptor(object):
        def __get__(self,outer,outercls):
            if outer is None:
                raise AttributeError('An enclosing instance that contains '
                           '%s.%s is required' % (cls.__name__, cls.__name__))
            clsdict = cls.__dict__.copy()
            # explicit read-only reference to the outer instance
            clsdict['__outer__'] = property(lambda self: outer)
            # implicit lookup in the outer instance
            clsdict['__getattr__'] = lambda self,attr: getattr(outer,attr)
            def __setattr__(this, attr, value):
                # setting an attribute in the inner instance sets the
                # respective attribute in the outer instance if and only if
                # the attribute is already defined in the outer instance
                if hasattr(outer, attr): setattr(outer,attr,value)
                else: super(this.__class__,this).__setattr__(attr,value)
            clsdict['__setattr__'] = __setattr__
            return type(cls.__name__, cls.__bases__, clsdict)
    return InnerDescriptor()

def nestedclass(cls):
    '''Class decorator for making a class behave as a Java static inner class.

    Each instance of the decorated class is associated with its enclosing
    class. The outer class is referenced implicitly when an attribute lookup
    fails in the inner object's namespace. It can also be referenced
    explicitly through the attribute '__outer__' of the inner instance.
    '''
    if hasattr(cls, '__outer__'):
        raise TypeError('Cannot set attribute "__outer__" in nested class')
    class NestedDescriptor(object):
        def __get__(self, outer, outercls):
            clsdict = cls.__dict__.copy()
            # explicit read-only reference the outer class
            clsdict['__outer__'] = outercls
            # implicit lookup in the outer class
            clsdict['__getattr__'] = lambda self,attr: getattr(outercls,attr)
            def __setattr__(this, attr, value):
                # setting an attribute in the inner instance sets the
                # respective attribute in the outer class if and only if the
                # attribute is already defined in the outer class
                if hasattr(outercls, attr): setattr(outercls,attr,value)
                else: super(this.__class__,this).__setattr__(attr,value)
            clsdict['__setattr__'] = __setattr__
            return type(cls.__name__, cls.__bases__, clsdict)
    return NestedDescriptor()

if __name__ == '__main__':
    testInner()
    testStaticInner()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Omnipay\Skeleton\Message;

use Omnipay\Tests\TestCase;

class ResponseTest extends TestCase
{
    public function testConstruct()
    {
        // response should decode URL format data
        $response = new Response($this->getMockRequest(), 'example=value&foo=bar');
        $this->assertEquals(array('example' => 'value', 'foo' => 'bar'), $response->getData());
    }

    public function testProPurchaseSuccess()
    {
        $httpResponse = $this->getMockHttpResponse('AuthorizeSuccess.txt');
        $response = new Response($this->getMockRequest(), $httpResponse->getBody());

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals('1234', $response->getTransactionReference());
        $this->assertNull($response->getMessage());
    }
}


text:
import { Category } from 'hint/dist/src/lib/enums/category';
import { HintScope } from 'hint/dist/src/lib/enums/hint-scope';
import { HintMetadata } from 'hint/dist/src/lib/types';

const meta: HintMetadata = {
    docs: {
        category: Category.pwa,
        description: 'Require valid web app manifest',
        name: 'Valid manifest'
    },
    id: 'manifest-is-valid',
    schema: [],
    scope: HintScope.any
};

export default meta;


text:
require 'trask/models/editable_html'

module Trask
  module ViewHelpers

    def editable_collection(*args, &block)
      block = capture(&block) if block_given?
      collection = Trask::ContentCollection.build(@_editable_page, block, *args)
      render partial: 'content_collection', locals: { collection: collection }
    end

    def editable_html(*args, &block)
      block = capture(&block) if block_given?
      content = Trask::EditableHtml.build(@_editable_page, block, *args)
      render partial: 'trask/editable_html', locals: { content: content }
    end

  end
end


text:
package com.thomas.zxing.decoding;

import java.util.Vector;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.thomas.BroadcastDemo.MipcaActivityCapture;
import com.thomas.view.ViewfinderResultPointCallback;
import com.thomas.zxing.camera.CameraManager;

/**
 * This class handles all the messaging which comprises the state machine for capture.
 */
public final class CaptureActivityHandler extends Handler {

  private static final String TAG = CaptureActivityHandler.class.getSimpleName();

  private final MipcaActivityCapture activity;
  private final DecodeThread decodeThread;
  private State state;

  private enum State {
    PREVIEW,
    SUCCESS,
    DONE
  }

  public CaptureActivityHandler(MipcaActivityCapture activity, Vector<BarcodeFormat> decodeFormats,
      String characterSet) {
    this.activity = activity;

    decodeThread = new DecodeThread(activity, decodeFormats, characterSet,
        new ViewfinderResultPointCallback(activity.getViewfinderView()));
    decodeThread.start();
    state = State.SUCCESS;
    // Start ourselves capturing previews and decoding.
    CameraManager.get().startPreview();
    restartPreviewAndDecode();
  }

  private int getId(String idName,String type){
    return activity.getResources().getIdentifier(idName, type, activity.getPackageName());
  }
  @Override
  public void handleMessage(Message message) {
     int auto_focus = getId("auto_focus","id");
     int restart_preview = getId("restart_preview","id");
     int decode_succeeded = getId("decode_succeeded","id");
     int decode_failed = getId("decode_failed","id");
     int return_scan_result = getId("return_scan_result","id");
     int launch_product_query = getId("launch_product_query","id");

     if(message.what == auto_focus){
      if (state == State.PREVIEW) {
        CameraManager.get().requestAutoFocus(this, getId("auto_focus","id"));
      }
    }else if(message.what == restart_preview){
       Log.d(TAG, "Got restart preview message");
       restartPreviewAndDecode();
    }else if(message.what == decode_succeeded){
       Log.d(TAG, "Got decode succeeded message");
       state = State.SUCCESS;
       Bundle bundle = message.getData();

       /***********************************************************************/
       Bitmap barcode = bundle == null ? null :
               (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);//���ñ����߳�

       activity.handleDecode((Result) message.obj, barcode);//���ؽ��?        /***********************************************************************/

    }else if(message.what == decode_failed){
       state = State.PREVIEW;
       CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), getId("decode","id"));
    }else if(message.what == return_scan_result){
       Log.d(TAG, "Got return scan result message");
       activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
       activity.finish();
    }else if(message.what == launch_product_query){
       Log.d(TAG, "Got product query message");
       String url = (String) message.obj;
       Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
       activity.startActivity(intent);
    }

// switch (message.what) {
//      case R.id.auto_focus:
//        //Log.d(TAG, "Got auto-focus message");
//        // When one auto focus pass finishes, start another. This is the closest thing to
//        // continuous AF. It does seem to hunt a bit, but I'm not sure what else to do.
//        if (state == State.PREVIEW) {
//          CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
//        }
//        break;
//      case R.id.restart_preview:
//        Log.d(TAG, "Got restart preview message");
//        restartPreviewAndDecode();
//        break;
//      case R.id.decode_succeeded:
//        Log.d(TAG, "Got decode succeeded message");
//        state = State.SUCCESS;
//        Bundle bundle = message.getData();
//
//        /***********************************************************************/
//        Bitmap barcode = bundle == null ? null :
//            (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);//���ñ����߳�
//
//        activity.handleDecode((Result) message.obj, barcode);//���ؽ��?        /***********************************************************************/
//        break;
//      case R.id.decode_failed:
//        // We're decoding as fast as possible, so when one decode fails, start another.
//        state = State.PREVIEW;
//        CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
//        break;
//      case R.id.return_scan_result:
//        Log.d(TAG, "Got return scan result message");
//        activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
//        activity.finish();
//        break;
//      case R.id.launch_product_query:
//        Log.d(TAG, "Got product query message");
//        String url = (String) message.obj;
//        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
//        activity.startActivity(intent);
//        break;
//    }
  }

  public void quitSynchronously() {
    state = State.DONE;
    CameraManager.get().stopPreview();
//    Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit);
    Message quit = Message.obtain(decodeThread.getHandler(), getId("quit","id"));
    quit.sendToTarget();
    try {
      decodeThread.join();
    } catch (InterruptedException e) {
      // continue
    }

    // Be absolutely sure we don't send any queued up messages
//    removeMessages(R.id.decode_succeeded);
//    removeMessages(R.id.decode_failed);
    removeMessages(getId("decode_succeeded","id"));
    removeMessages(getId("decode_failed","id"));
  }

  private void restartPreviewAndDecode() {
    if (state == State.SUCCESS) {
      state = State.PREVIEW;
//      CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
//      CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
      CameraManager.get().requestPreviewFrame(decodeThread.getHandler(),getId("decode","id"));
      CameraManager.get().requestAutoFocus(this, getId("auto_focus","id"));
      activity.drawViewfinder();
    }
  }

}


text:
if (typeof String.prototype.startsWith != 'function') {
	String.prototype.startsWith = function (str) {
		return this.slice(0, str.length) == str;
	};
}

if (typeof String.prototype.endsWith != 'function') {
	String.prototype.endsWith = function (str) {
		return this.slice(-str.length) == str;
	};
}

function handleActionDrop(event, ui) {
	log.debug('handleActionDrop()');
	var column = $(this).attr('data-column');
	var row = $(this).attr('data-row');
	var oldCol = ui.draggable.attr('data-column');
	var oldRow = ui.draggable.attr('data-row');
	var slug = ui.draggable.attr('data-slug');
	var pk = ui.draggable.attr('data-pk');
	var type = ui.draggable.attr('data-type');
	var unlock = ui.draggable.attr('data-unlock');
	var title = ui.draggable.children('a').attr('title');
	var cls = ui.draggable.attr('class');
	var classes = cls.split(" ");
	var fromPalette = false;
	var fromGrid = false;
	for (var i = 0; i < classes.length; i++) {
		if (classes[i] == 'palette-draggable') {
			fromPalette = true;
		}
		if (classes[i].startsWith('sgg-') && classes[i].endsWith('-cell')) {
			fromGrid = true;
		}
	}
//	log.debug('fromPalette=' + fromPalette + ' fromGrid=' + fromGrid);
	if (unlock) {
		unlock = trim1(unlock);
	}
	var levelSlug = findLevelSlug(this);
	var unlockCondition = createUnlockStr(unlock);
	if (fromPalette) {
		ui.draggable.removeClass('palette-draggable');
		ui.draggable.removeClass('ui-draggable-dragging');
		ui.draggable.removeClass('sgg-'+ type + '-palette');
		ui.draggable.addClass('sgg-'+ type + '-cell');
		ui.draggable.addClass('grid_dragable');
		var temp = ui.draggable.clone();
		temp.removeClass('hidden');
		temp.attr('style', '');
		temp.attr('data-column', column);
		temp.attr('data-row', row);
		var html = $('
').append(temp).html();
//		log.debug(html);
		$(this).html(html);
//		ui.draggable.addClass('hidden');
		movePaletteAction(slug, levelSlug, column, row);
	} else if (fromGrid) {
		var temp = ui.draggable.clone();
		temp.removeClass('hidden');
		temp.attr('style', '');
		temp.attr('data-column', column);
		temp.attr('data-row', row);
		var html = $('
').append(temp).html();
//		log.debug(html);
		$(this).html(html);
//		ui.draggable.addClass('hidden');
		moveGridAction(slug, levelSlug, oldCol, oldRow, column, row);
	} else if (type == "filler") {
		numFiller += 1;
		slug = 'filler-' + numFiller;
		var text = 'Filler-' + numFiller;
		var drop = createActionDropDiv(slug, type, row, column, text, "-1", text);
		var html = $('
').append(drop.clone()).html();
//		log.debug(html);
		$(this).html(html);
		pk = instantiateGridAction(slug, levelSlug, column, row);
	} else  {
		// From the library
		var drop = createActionDropDiv(slug, type, row, column, ui.draggable.text(), pk, title);
		var html = $('
').append(drop.clone()).html();
//		log.debug(html);
		$(this).html(html);
		pk = instantiateGridAction(slug, levelSlug, column, row);
		if (type == 'event') {
			log.debug('set event date');
	        var modalElement = $('#eventDateChooser');
			var text = "Select the date and time for " + title;
			modalElement.find('#eventName').html(text);
			modalElement.find('input#id_event_slug').val(slug);

	        modalElement.modal({
	            backdrop: true,
	            keyboard: true,
	            show: false
	        });
	        modalElement.css('margin-top', (modalElement.outerHeight() / 2) * -1);
	        modalElement.modal('show');

		}
	}
	$(this).children().draggable({
		cursor : 'move',
		start: handleGridStartDrag,
		helper : 'clone',
	});
}

function handleColumnDrop(event, ui) {
	log.debug('handleColumnDrop()');
	var levelID = findLevelID(this);
	var column = $(this).attr('data-column');
	var slug = ui.draggable.attr('data-slug');
	var pk = ui.draggable.attr('data-pk');
	var levelSlug = findLevelSlug(this);
	if (pk == "-1") {
		$(this).html('');
		deactivateColumn(levelID, column);
	}
	else {
		var drop = createColumnDropDiv(slug, column, ui.draggable.text(), trim2(pk));
		var html = $('
').append(drop.clone()).html();
		$(this).html(html);
		activateColumn(levelID, column, slug);
	}
	instantiateGridColumn(slug, levelSlug, column);
}

function handleColumnStartDrag(event, ui) {
	log.debug('handleColumnStartDrag(' + event + ', ' + ui + ')');
	$(this).addClass('hidden');
}

function handleGridStartDrag(event, ui) {
	log.debug('handleGridStartDrag(' + event + ', ' + ui + ')');
	$(this).addClass('hidden');
}

function handleLibraryStartDrag(event, ui) {
	log.debug('handleLibraryStartDrag(' + event + ', ' + ui + ')');
	$(this).addClass('hidden');
}

function handlePaletteStartDrag(event, ui) {
	log.debug('handlePaletteStartDrag(' + event + ', ' + ui + ')');
	$(this).addClass('hidden');
}

function handlePaletteDrop(obj) {
	log.debug('handlePaletteDrop');
	var slug = obj.attr('data-slug');
	var pk = obj.attr('data-pk');
	var type = obj.attr('data-type');
	var title = obj.children('a').attr('title');
	var text = obj.text();
	if (text) {
		text = trim2(text);
	}
//	log.debug("slug = " + slug);
	clearLevelColumnPriority(slug);
	var drop = createPaletteDropDiv(slug, type, text, pk, title);
//	log.debug(drop.html());
	$('.sgg-right-palette').append(drop);
	drop.draggable({
		cursor : 'move',
		start: handlePaletteStartDrag,
		helper : 'clone',
	});
	var slot = obj.parent();
//	log.debug(slot);
	slot.html("");
}

/**
 * Returns a jQuery object that represents the dropped ColumnName.
 * @param slug a String the ColumnName's slug.
 * @param column an int the column the ColumnName is dropped into.
 * @param text a String the name of the column.
 * @returns a jQuery object representing the dropped ColumnName. It can be added to the page.
 */
function createColumnDropDiv(slug, column, text, id) {
	log.debug("createColumnDropDiv(" + slug + ", " + column + ", " + text + ", " + id + ")");
	var drop = $('

' + ''
			+ trim2(text) + '

');
	return drop;
}

function instantiateGridColumn(colSlug, levelSlug, column) {
	log.debug('instantiateGridColumn(' + colSlug + ', ' + levelSlug + ', ' + column + ')');
    jQuery.ajax({
        url: "/smartgrid_design/newcol/" + colSlug + "/" + levelSlug + "/" + column + "/",
        success: function(data) {
//        	log.debug('pk of Grid ColumnName is ' + data.pk);
        	var div = $('div[data-slug="' + catSlug + '"]:visible > a');
        	var href = div.attr('href');
        	href = href.slice(0, href.length - 1);
        	var index = href.lastIndexOf('/');
        	if (index != -1) {
        		href = href.slice(0, index + 1) + data.pk + '/';
//        		log.debug(href);
        		div.attr('href', href);
//        		log.debug(div);
        	}

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

function instantiateGridAction(actSlug, levelSlug, column, row) {
	log.debug('instantiateGridAction(' + actSlug + ', ' + levelSlug + ', ' + column + ', ' + row + ')');
    jQuery.ajax({
        url: "/smartgrid_design/newaction/" + actSlug + "/" + levelSlug + "/" + column + "/" + row + "/",
        success: function(data) {
//        	log.debug('pk of new Grid Action is ' + data.pk);
        	var div = $('div[data-slug="' + actSlug + '"]:visible > a');
        	var href = div.attr('href');
        	if (href) {
//        		log.debug('href = ' + href);
        		href = href.slice(0, href.length - 1);
        		var index = href.lastIndexOf('/');
        		if (index != -1) {
        			href = href.slice(0, index + 1) + data.pk + '/';
//        		log.debug(href);
        			div.attr('href', href);
//        		log.debug(div);
        		}
        	}
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

function moveGridAction(actSlug, levelSlug, oldColumn, oldRow, column, row) {
	log.debug('moveGridAction(' + actSlug + ', ' + levelSlug + ', ' + oldColumn + ', ' + oldRow + ', ' + column + ', ' + row + ')');
    jQuery.ajax({
        url: "/smartgrid_design/moveaction/" + actSlug + "/" + levelSlug + "/" + oldColumn + "/" + oldRow + "/" + column + "/" + row + "/",
        success: function(data) {
//        	log.debug('pk of new Grid Action is ' + data.pk);
        	var div = $('div[data-slug="' + actSlug + '"]:visible > a');
        	var href = div.attr('href');
        	if (href) {
//        		log.debug('href = ' + href);
        		href = href.slice(0, href.length - 1);
        		var index = href.lastIndexOf('/');
        		if (index != -1) {
        			href = href.slice(0, index + 1) + data.pk + '/';
//        		log.debug(href);
        			div.attr('href', href);
//        		log.debug(div);
        		}
        	}
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });

}

function movePaletteAction(actSlug, levelSlug, column, row) {
	log.debug('movePaletteAction(' + actSlug + ', ' + levelSlug + ', ' + column + ', ' + row + ')');
    jQuery.ajax({
        url: "/smartgrid_design/paletteaction/" + actSlug + "/" + levelSlug + "/" + column + "/" + row + "/",
        success: function(data) {
//        	log.debug('pk of new Grid Action is ' + data.pk);
        	var div = $('div[data-slug="' + actSlug + '"]:visible > a');
        	var href = div.attr('href');
        	if (href) {
//        		log.debug('href = ' + href);
        		href = href.slice(0, href.length - 1);
        		var index = href.lastIndexOf('/');
        		if (index != -1) {
        			href = href.slice(0, index + 1) + data.pk + '/';
//        		log.debug(href);
        			div.attr('href', href);
//        		log.debug(div);
        		}
        	}
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
//        	log.debug(XMLHttpRequest + ' - ' + textStatus + ' - ' + errorThrown);
        }
    });

}

function getDesignerDiff() {
	log.debug('getDesignerDiff()');
	jQuery.ajax({
		url: "/smartgrid_design/get_diff/",
		success: function(data) {
			var diff = data.diff;
			var numDiff = diff.length;
			var diffDiv = $('.sgg-differences');
			if (numDiff == 0) {
				var noDiff = 'Changes:No changes from the Smart Grid.';
				diffDiv.html(noDiff);
			}
			else {
				var html = 'Changes:';
				for (var i = 0; i < diff.length; i++) {
					var inner = diff[i];
					html += '
';
					html += '
' + inner[0] + '
';
					html += '
';
					for (var j = 0; j < inner[1].length; j++) {
						html += '' + inner[1][j] + ', ';
					}
					html = html.substring(0, html.length - 2);
					html += '

';
				}
				diffDiv.html(html);
			}
		}
	})
}

function runDesignerLint() {
	log.debug('runDesignerLint()');
	jQuery.ajax({
		url: "/smartgrid_design/run_lint/",
		success: function(data) {
			var unreachable = data.unreachable;
			var false_unlock = data.false_unlock;
			var trees = data.tree;
			var mismatched = data.mismatched_levels;
			var pub_date = data.pub_date;
			log.debug(pub_date);
			var lintDiv = $('#designer-lint');
			var html = '';
			if (unreachable.length > 0) {
				html += '
';
				for (var i = 0; i < unreachable.length; i++) {
					html += '
' + unreachable[i] +
						' is unreachable due to unlock condition dependencies
';
				}
				html += '
';
			}
			if (mismatched.length > 0) {
				html += '
';
				for (var i = 0; i < mismatched.length; i++) {
					html += '
Warning ' + mismatched[i] +
						' depends on an action in a higher level
';
				}
				html += '
';
			}
			if (false_unlock.length > 0) {
				html += '
';
				for (var i = 0; i < false_unlock.length; i++) {
					html += '
Warning ' + false_unlock[i] +
						' is locked because it depends on an action with a False unlock condition
';
				}
				html += '
';
			}
			if (pub_date.length > 0) {
				html += '
';
				for (var i = 0; i < pub_date.length; i++) {
					html += '
Warning ' + pub_date[i] +
						'\'s publication or expiration date are outside the competition
';
				}
				html += '
';
			}
			html += 'Unlock Condition Dependency:
';
			html += trees;
			html += '
';
			lintDiv.html(html);
		}
	})
}

/**
 * Returns a jQuery object that represents the dropped Action.
 * @param slug a String the Action slug.
 * @param type a String the type of Action (Activity, commitment, event, filler)
 * @param row an int, the row the Action is in. This will become its priority.
 * @param column an int, the column the Action is in.
 * @param text a String the name of the Action.
 * @returns a jQuery object representing the dropped Action.
 */
function createActionDropDiv(slug, type, row, column, text, id, title) {
	log.debug("createActionDropDiv(" + slug + ", " + type + ", " + row + ", " + column + ", " + text + ", " + id + ")");
	var drop = $('
' +
		   	'
' +
		   	'' +
			trim2(text) + '

');
	return drop;
}

function createPaletteDropDiv(slug, type, text, id, title) {
	log.debug("createPaletteDropDiv(" + slug + ", " + type + ", " + text + ", " + id + ", " + title + ")");
	var drop = $('

' +
			'' +
			trim2(text) + '

');
	return drop;
}

function activateColumn(levelID, column, slug) {
	log.debug("activateColumn("+ levelID + ", " + column + ", " + slug + ")");
	for ( var i = 1; i < 11; i++) {
		var row = $('#' + levelID + ' .sgg-action-dropzone table tbody tr:nth-child(' + i + ')');
		var tdCell = row.find('td:nth-child(' + column + ')');
		var outerDiv = tdCell.children('div');
		outerDiv.removeClass('disabled');
		// Activate the div for dropping.
		outerDiv.droppable({
			accept : '.sgg-action',
			drop : handleActionDrop
		});
	}
}

function deactivateColumn(levelID, column) {
	log.debug("deactivateColumn("+ levelID + ", " + column + ")");
	for ( var i = 1; i < 11; i++) {
		var row = $('#' + levelID + ' .sgg-action-dropzone table tbody tr:nth-child(' + i + ')');
		var tdCell = row.find('td:nth-child(' + column + ')');
		var outerDiv = tdCell.children('div');
		var innerDiv = outerDiv.children('div');
		var slug = innerDiv.attr('data-slug');
		if (typeof slug == 'string') {
			deleteGridAction(slug);
			$('.library-draggable[data-slug=' + slug + ']').removeClass('hidden');
		}
		outerDiv.addClass('disabled');
		outerDiv.html('');
	}
}

function deleteGridAction(actionSlug) {
	log.debug("deleteGridAction(" + actionSlug + ")");
//	$.get("/smartgrid_design/delete_action/" + actionSlug + "/");
    jQuery.ajax({
        url: "/smartgrid_design/delete_action/" + actionSlug + "/",
        success: function(data) {
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

function deleteGridColumn(colSlug) {
	log.debug("deleteGridColumn(" + colSlug + ")");
    jQuery.ajax({
        url: "/smartgrid_design/delete_column/" + colSlug + "/",
        success: function(data) {
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

function clearLevelColumnPriority(actionSlug) {
	log.debug("clearLevelColumnPriority(" + actionSlug + ")");
    jQuery.ajax({
        url: "/smartgrid_design/clear_from_grid/" + actionSlug + "/",
        success: function(data) {
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });

}

/**
 * Trims the whitespace from front and end of str.
 * @param str the string.
 * @returns The string without any spaces in the begging or end.
 */
function trim1 (str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function trim2(str) {
	if (typeof str == 'string') {
		str = trim1(str);
		var i = str.indexOf('"');
		if (i == 0) {
			str = str.slice(i + 1, str.length - 1);
		}
	}
	return str;
}

/**
 * Searches up the parent tree till data-level is found.
 * @param ele the child element.
 * @returns The level as a string.
 */
function findLevel(ele) {
	var p = ele.parentNode;

	while (p) {
		var level = $(p).attr('data-level');
		if (level) {
			return level;
		}
		p = p.parentNode;
	}
	return false;
}

function findLevelSlug(ele) {
	var p = ele.parentNode;

	while (p) {
		var level = $(p).attr('data-levelslug');
		if (level) {
			return level;
		}
		p = p.parentNode;
	}
	return false;

}

function findLevelID(ele) {
	var p = ele.parentNode;

	while (p) {
		var level = $(p).attr('data-level');
		if (level) {
			return $(p).attr('id');
		}
		p = p.parentNode;
	}
	return false;
}

function findPkForSlug(slug) {
	var ele = $('div[data-slug=' + slug + ']');
	return ele.attr('data-pk');
}

function isCompoundUnlock(unlock) {
	if (unlock) {
		if (unlock.indexOf(" or ") != -1 || unlock.indexOf(" and ")) {
			return true;
		}
	}
	return false;
}

function isSubmittedAction(unlock) {
	if (unlock) {
		var str = "submitted_action(";
		return unlock.slice(0, str.length) == str;
	}
	return false;
}

function getSlugFromUnlock(unlock) {
	if (unlock == "True") {
		return "T";
	}
	if (unlock == "False") {
		return "F";
	}
	if (isSubmittedAction(unlock)) {
		var slug = unlock.slice(17, -1);
		return slug;
	}
	return "";
}

function isSlugInGrid(slug) {
	var ele = $('.sgg-action-slot div[data-slug=' + slug + ']');
	if (ele.length > 0) {
		return true;
	}
	return false;
}

function createUnlockStr(unlockCondText) {
	var unlockText = "";
	if (unlockCondText == "True") {
		unlockText = "T";
	} else if (unlockCondText == "False") {
		unlockText = "F";
	} else if (isCompoundUnlock(unlockCondText)) {
		var conditions = unlockCondText.split(" ");
		unlockText += "[";
		for (var i = 0; i < conditions.length; i++) {
			if (i % 2 == 0) {
				var unlockSlug = getSlugFromUnlock(conditions[i]);
				var pk = findPkForSlug(unlockSlug);
				if (isSlugInGrid(unlockSlug)) {
					unlockText += "" + pk;
				} else {
					unlockText += "" + pk + "";
				}
			} else {
				if (conditions[i] == "or") {
					unlockText += ",";
				} else if (conditions[i] == "and") {
					unlockText += "+";
				}
			}
		}
		unlockText += "]";
	} else if (isSubmittedAction(unlockCondText)) {
		var unlockSlug = getSlugFromUnlock(trim1(unlockCondText));
		var pk = findPkForSlug(unlockSlug);
		if (isSlugInGrid(unlockSlug)) {
			unlockText = "[" + pk + "]";
		} else {
			unlockText = "[" + pk + "]";
		}
	}
	return unlockText;
}


text:
import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
import * as serviceWorker from './serviceWorker';

import { BrowserRouter } from 'react-router-dom';

import { Provider } from 'react-redux';
import store from "./redux/store";

ReactDOM.render(
	<BrowserRouter>
		<Provider store={store}>
			<App />
		</Provider>
	</BrowserRouter>, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


text:
package leap.orm.command;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.List;

public interface UpgradeSchemaCommand extends DmoCommand {

	/**
	 * Be careful calling this method. It may cause data loss.
	 *
	 *

	 * Enables or Disables dropping table.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setDropTableEnabled(boolean dropTableEnabled);

	/**
	 * Returns true if {@link #isDropTableObjectsEnabled()} is true or enable dropping table.
	 */
	boolean isDropTableEnabled();

	/**
	 * Be careful calling this method. It may cause data loss.
	 *
	 *

	 * Enables or Disables dropping any objects in table, such as column,foreign key, index, etc.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setDropTableObjectsEnabled(boolean dropTableObjectsEnabled);

	/**
	 * Returns true if enable dropping any schema objects .
	 */
	boolean isDropTableObjectsEnabled();

	/**
	 * Be careful calling this method. It may cause data loss.
	 *
	 *

	 * Enables or Disables dropping column.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setDropColumnEnabled(boolean dropColumnEnabled);

	/**
	 * Returns true if {@link #isDropTableObjectsEnabled()} is true or enable dropping column.
	 */
	boolean isDropColumnEnabled();

	/**
	 * Enables or Disables dropping primary key.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setDropPrimaryKeyEnabled(boolean dropPrimaryKeyEnabled);

	/**
	 * Returns true if {@link #isDropTableObjectsEnabled()} is true or enable dropping primary key.
	 */
	boolean isDropPrimaryKeyEnabled();

	/**
	 * Enables or Disables dropping foreign key.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setDropForeignKeyEnabled(boolean dropForeignKeyEnabled);

	/**
	 * Returns true if {@link #isDropTableObjectsEnabled()} is true or enable dropping foreign key.
	 */
	boolean isDropForeignKeyEnabled();

	/**
	 * Enables or Disables dropping index.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setDropIndexEnabled(boolean dropIndexEnabled);

	/**
	 * Returns true if {@link #isDropTableObjectsEnabled()} is true or enable dropping index.
	 */
	boolean isDropIndexEnabled();

	/**
	 * Enables or Disables altering column.
	 *
	 *

	 * Default is disabled.
	 */
	UpgradeSchemaCommand setAlterColumnEnabled(boolean alterColumnEnabled);

	/**
	 * Returns true if altering column's definition is enabled.
	 */
	boolean isAlterColumnEnabled();

    /**
     * Returns the upgrade scripts.
     */
    List<String> getUpgradeScripts();

    /**
     * Prints the upgrade scripts.
     */
    void printUpgradeScripts(PrintWriter out);

    /**
     * Prints the upgrade scripts.
     */
    void printUpgradeScripts(PrintStream out);

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>GigaGrid</title>
    <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.css">


text:
ActiveRecord::Base.class_eval do
  include ActsAsVerifiable
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Proyek_model extends CI_Model
{

	function __construct()
	{
		parent::__construct();
	}

	public function insert_new_proyek($data)
	{
		$result = $this->db->insert('proyek', $data);

		return $this->db->insert_id();
	}

	public function get_all_proyek()
	{
		return $this->db->get('proyek')->result_array();
	}

	public function get_proyek_by_id($id)
	{
		$this->db->from('proyek');
		$this->db->where('id', $id);

		return $this->db->get()->row_array();
	}

	public function get_proyek_by_client($username_klien)
	{
		$this->db->from('proyek');
		$this->db->where('username_klien', $username_klien);

		return $this->db->get()->row_array();
	}

}

?>


text:
from __future__ import print_function

import os.path
import shutil

from datetime import datetime
from subprocess import call
from util import render

from util import tempdir
from s3 import S3

class LambdaBuilder(object):
    """
    Create and upload ZIP archive to S3 for AWS lambda function from CFN.
    """

    def __init__(self, *zip_args, **zip_kwargs):
        self._zip_args = zip_args
        self._zip_kwargs = zip_kwargs
        self._created = {}  # "filename": "file body"
        self._copied = {}  # "filename": "source filename"

    def create_file(self, file_body, path, render_mapping=None):
        print("  * created `%s` from LambdaBuilder" % path)
        self._created[path] = file_body if render_mapping is None else render(file_body, render_mapping)
        return self

    def append(self, file_name, path=None, render_mapping=None):
        assert os.path.exists(file_name)
        assert os.path.isfile(file_name) or not render_mapping
        path = path or os.path.basename(file_name)

        if render_mapping:
            with open(file_name) as fp:
                self.create_file(fp.read(), path, render_mapping)
        else:
            print("  * copied `%s` from LambdaBuilder" % path)
            self._copied[path] = file_name

        return self

    def upload_to_s3(self, bucket_name, prefix=None, key_name=None):
        """
        Upload composed archive (.zip) to S3

        :param str prefix: without leading and trailing slashes
        """
        s3 = S3()

        prefix = prefix or "lambda-src"
        key_name = key_name or datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ.zip")

        uploaded_path = "%s/%s" % (prefix, key_name)

        with tempdir() as td:
            archive_name = self._compile(td.path, key_name)
            s3.upload(archive_name, bucket_name, uploaded_path)

        return uploaded_path

    def _compile(self, temp_path, archive_name):
        """
        Compiles to an zip archive and return its fullpath.
        Uses temp_path as working directory.

        :param temp_path:
        :param archive_name:
        :return: Fullpath to archive
        """
        old_umask = os.umask(0o022)

        build_path = os.path.join(temp_path, "build")
        os.mkdir(build_path, 0o755)

        archive_name = os.path.join(temp_path, archive_name)
        try:
            for filename, body in self._created.items():
                filename = os.path.join(build_path, filename)

                with open(filename, "wb") as fp:
                    fp.write(body)

            for filename, source in self._copied.items():
                filename = os.path.join(build_path, filename)

                if os.path.isdir(source):
                    shutil.copytree(source, filename)
                else:
                    shutil.copy(source, filename)

            call(["chmod", "-R", "go+rX", temp_path])
            call(["zip", "-qr", archive_name, ".", "-x", ".*", "*/.*", "__pycache__", "*/__pycache__"], cwd=build_path)

        finally:
            os.umask(old_umask)

        return archive_name


text:
require 'chef/resource'
require 'chef/provider'

class Chef
  class Resource::NetdevLinkAggregationGroup < Resource
    provides      :netdev_lag
    identity_attr :lag_name
    state_attrs   :links, :minimum_links, :lacp

    attr_accessor :active, :exists
    alias active? active
    alias exists? exists

    resource_name :netdev_lag

    default_action :create

    def initialize(name, run_context = nil)
      super

      # Set default actions and allowed actions
      @allowed_actions.push(:create, :delete)

      # Set the name attribute and default attributes
      @lag_name = name
      @lacp     = 'disable'

      # State attributes that are set by the provider
      @exists   = false
    end

    #
    # The name of the link aggregation group.
    #
    # @param [String] arg
    # @return [String]
    #
    def lag_name(arg = nil)
      set_or_return(:lag_name, arg, kind_of: String)
    end

    #
    # An array of interfaces to be configured as members of the link
    # aggregation group.
    #
    # @param [String] arg
    # @return [String]
    #
    def links(arg = nil)
      set_or_return(:links, arg, kind_of: Array)
    end

    #
    # The minimum number of physical links that are required to ensure the
    # availability of the link aggregation group.
    #
    # @param [String] arg
    # @return [String]
    #
    def minimum_links(arg = nil)
      set_or_return(:minimum_links, arg, kind_of: Integer)
    end

    #
    # The link aggregation control protocol mode. Possible values: active
    # (active mode), disable (not used), or passive (passive mode).
    #
    # @param [String] arg
    # @return [String]
    #
    def lacp(arg = nil)
      set_or_return(
        :lacp,
        arg,
        kind_of: String,
        equal_to: %w(disable active passive)
      )
    end
  end
end

class Chef::Provider::NetdevLinkAggregationGroup; end


text:
module Puppet::Parser::Functions
  newfunction(:round, :type => :rvalue, :doc => <<-DOC
    Rounds a number to the nearest integer

    *Examples:*

    round(2.9)

    returns: 3

    round(2.4)

    returns: 2

  DOC
             ) do |args|

    raise Puppet::ParseError, "round(): Wrong number of arguments given #{args.size} for 1" if args.size != 1
    raise Puppet::ParseError, "round(): Expected a Numeric, got #{args[0].class}" unless args[0].is_a? Numeric

    value = args[0]

    if value >= 0
      Integer(value + 0.5)
    else
      Integer(value - 0.5)
    end
  end
end


text:
package org.onosproject.incubator.net.virtual.impl;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import org.onlab.metrics.MetricsService;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.RoleInfo;
import org.onosproject.core.MetricsHelper;
import org.onosproject.incubator.net.virtual.NetworkId;
import org.onosproject.incubator.net.virtual.VirtualDevice;
import org.onosproject.incubator.net.virtual.VirtualNetworkMastershipStore;
import org.onosproject.incubator.net.virtual.VirtualNetworkService;
import org.onosproject.incubator.net.virtual.event.AbstractVirtualListenerManager;
import org.onosproject.mastership.MastershipAdminService;
import org.onosproject.mastership.MastershipEvent;
import org.onosproject.mastership.MastershipInfo;
import org.onosproject.mastership.MastershipListener;
import org.onosproject.mastership.MastershipService;
import org.onosproject.mastership.MastershipStoreDelegate;
import org.onosproject.mastership.MastershipTerm;
import org.onosproject.mastership.MastershipTermService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.slf4j.Logger;
import com.codahale.metrics.Timer;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.onlab.metrics.MetricsUtil.startTimer;
import static org.onlab.metrics.MetricsUtil.stopTimer;
import static org.slf4j.LoggerFactory.getLogger;

public class VirtualNetworkMastershipManager
        extends AbstractVirtualListenerManager<MastershipEvent, MastershipListener>
        implements MastershipService, MastershipAdminService, MastershipTermService,
        MetricsHelper {

    private static final String NODE_ID_NULL = "Node ID cannot be null";
    private static final String DEVICE_ID_NULL = "Device ID cannot be null";
    private static final String ROLE_NULL = "Mastership role cannot be null";

    private final Logger log = getLogger(getClass());

    protected ClusterService clusterService;

    VirtualNetworkMastershipStore store;
    MastershipStoreDelegate storeDelegate;

    private NodeId localNodeId;
    private Timer requestRoleTimer;

    /**
     * Creates a new VirtualNetworkMastershipManager object.
     *
     * @param manager virtual network manager service
     * @param networkId virtual network identifier
     */
    public VirtualNetworkMastershipManager(VirtualNetworkService manager, NetworkId networkId) {
        super(manager, networkId, MastershipEvent.class);

        clusterService = serviceDirectory.get(ClusterService.class);

        store = serviceDirectory.get(VirtualNetworkMastershipStore.class);
        this.storeDelegate = new InternalDelegate();
        store.setDelegate(networkId, this.storeDelegate);

        requestRoleTimer = createTimer("Virtual-mastership", "requestRole", "responseTime");
        localNodeId = clusterService.getLocalNode().id();
    }

    @Override
    public CompletableFuture<Void> setRole(NodeId nodeId, DeviceId deviceId,
                                           MastershipRole role) {
        checkNotNull(nodeId, NODE_ID_NULL);
        checkNotNull(deviceId, DEVICE_ID_NULL);
        checkNotNull(role, ROLE_NULL);

        CompletableFuture<MastershipEvent> eventFuture = null;

        switch (role) {
            case MASTER:
                eventFuture = store.setMaster(networkId, nodeId, deviceId);
                break;
            case STANDBY:
                eventFuture = store.setStandby(networkId, nodeId, deviceId);
                break;
            case NONE:
                eventFuture = store.relinquishRole(networkId, nodeId, deviceId);
                break;
            default:
                log.info("Unknown role; ignoring");
                return CompletableFuture.completedFuture(null);
        }

        return eventFuture.thenAccept(this::post).thenApply(v -> null);
    }

    @Override
    public MastershipRole getLocalRole(DeviceId deviceId) {
        checkNotNull(deviceId, DEVICE_ID_NULL);

        return store.getRole(networkId, localNodeId, deviceId);
    }

    @Override
    public CompletableFuture<MastershipRole> requestRoleFor(DeviceId deviceId) {
        checkNotNull(deviceId, DEVICE_ID_NULL);

        final Timer.Context timer = startTimer(requestRoleTimer);
        return store.requestRole(networkId, deviceId)
                .whenComplete((result, error) -> stopTimer(timer));
    }

    @Override
    public CompletableFuture<Void> relinquishMastership(DeviceId deviceId) {
        return store.relinquishRole(networkId, localNodeId, deviceId)
                .thenAccept(this::post)
                .thenApply(v -> null);
    }

    @Override
    public NodeId getMasterFor(DeviceId deviceId) {
        checkNotNull(deviceId, DEVICE_ID_NULL);

        return store.getMaster(networkId, deviceId);
    }

    @Override
    public RoleInfo getNodesFor(DeviceId deviceId) {
        checkNotNull(deviceId, DEVICE_ID_NULL);

        return store.getNodes(networkId, deviceId);
    }

    @Override
    public MastershipInfo getMastershipFor(DeviceId deviceId) {
        checkNotNull(deviceId, DEVICE_ID_NULL);
        return store.getMastership(networkId, deviceId);
    }

    @Override
    public Set<DeviceId> getDevicesOf(NodeId nodeId) {
        checkNotNull(nodeId, NODE_ID_NULL);

        return store.getDevices(networkId, nodeId);
    }

    @Override
    public MastershipTerm getMastershipTerm(DeviceId deviceId) {
        return store.getTermFor(networkId, deviceId);
    }

    @Override
    public MetricsService metricsService() {
        //TODO: support metric service for virtual network
        log.warn("Currently, virtual network does not support metric service.");
        return null;
    }

    @Override
    public void balanceRoles() {
        //FIXME: More advanced logic for balancing virtual network roles.
        List<ControllerNode> nodes = clusterService.getNodes().stream()
                .filter(n -> clusterService.getState(n.id())
                        .equals(ControllerNode.State.ACTIVE))
                .collect(Collectors.toList());

        nodes.sort(Comparator.comparing(ControllerNode::id));

        //Pick a node using network Id,
        NodeId masterNode = nodes.get((int) ((networkId.id() - 1) % nodes.size())).id();

        List<CompletableFuture<Void>> setRoleFutures = Lists.newLinkedList();
        for (VirtualDevice device : manager.getVirtualDevices(networkId)) {
            setRoleFutures.add(setRole(masterNode, device.id(), MastershipRole.MASTER));
        }

        CompletableFuture<Void> balanceRolesFuture = CompletableFuture.allOf(
                setRoleFutures.toArray(new CompletableFuture[setRoleFutures.size()]));

        Futures.getUnchecked(balanceRolesFuture);
    }

    public class InternalDelegate implements MastershipStoreDelegate {
        @Override
        public void notify(MastershipEvent event) {
            post(event);
        }
    }
}


text:
module Braintree
  class Transaction
    include BaseModule

    module CreatedUsing
      FullInformation = 'full_information'
      Token = 'token'
      Unrecognized = 'unrecognized'
    end

    module EscrowStatus
      HoldPending    = 'hold_pending'
      Held           = 'held'
      ReleasePending = 'release_pending'
      Released       = 'released'
      Refunded       = 'refunded'
      Unrecognized   = 'unrecognized'
    end

    module GatewayRejectionReason
      ApplicationIncomplete = "application_incomplete"
      AVS          = "avs"
      AVSAndCVV    = "avs_and_cvv"
      CVV          = "cvv"
      Duplicate    = "duplicate"
      Fraud        = "fraud"
      ThreeDSecure = "three_d_secure"
      Unrecognized = "unrecognized"
    end

    module Status
      AuthorizationExpired   = 'authorization_expired'
      Authorizing            = 'authorizing'
      Authorized             = 'authorized'
      GatewayRejected        = 'gateway_rejected'
      Failed                 = 'failed'
      ProcessorDeclined      = 'processor_declined'
      Settled                = 'settled'
      SettlementConfirmed    = 'settlement_confirmed'
      SettlementDeclined     = 'settlement_declined'
      SettlementPending      = 'settlement_pending'
      Settling               = 'settling'
      SubmittedForSettlement = 'submitted_for_settlement'
      Voided                 = 'voided'
      Unrecognized           = 'unrecognized'

      All = constants.map { |c| const_get(c) }
    end

    module Source
      Api          = "api"
      ControlPanel = "control_panel"
      Recurring    = "recurring"
      Unrecognized = "unrecognized"
    end

    module IndustryType
      Lodging = "lodging"
      TravelAndCruise = "travel_cruise"

      All = constants.map { |c| const_get(c) }
    end

    module Type # :nodoc:
      Credit = "credit" # :nodoc:
      Sale = "sale" # :nodoc:

      All = constants.map { |c| const_get(c) }
    end

    attr_reader :avs_error_response_code, :avs_postal_code_response_code, :avs_street_address_response_code
    attr_reader :amount, :created_at, :credit_card_details, :customer_details, :subscription_details, :service_fee_amount, :id
    attr_reader :currency_iso_code
    attr_reader :custom_fields
    attr_reader :cvv_response_code
    attr_reader :disbursement_details
    attr_reader :disputes
    attr_reader :descriptor
    attr_reader :escrow_status
    attr_reader :gateway_rejection_reason
    attr_reader :merchant_account_id
    attr_reader :order_id
    attr_reader :channel
    attr_reader :billing_details, :shipping_details
    attr_reader :paypal_details
    attr_reader :apple_pay_details
    attr_reader :android_pay_details
    attr_reader :coinbase_details
    attr_reader :plan_id
    # The authorization code from the processor.
    attr_reader :processor_authorization_code
    # The response code from the processor.
    attr_reader :processor_response_code
    # The response text from the processor.
    attr_reader :processor_response_text
    # The raw response from the processor.
    attr_reader :additional_processor_response
    # The settlement response code from the processor.
    attr_reader :processor_settlement_response_code
    # The settlement response text from the processor.
    attr_reader :processor_settlement_response_text
    attr_reader :voice_referral_number
    attr_reader :purchase_order_number
    attr_reader :recurring
    attr_reader :refund_ids, :refunded_transaction_id
    attr_reader :settlement_batch_id
    # See Transaction::Status
    attr_reader :status
    attr_reader :status_history
    attr_reader :subscription_id
    attr_reader :tax_amount
    attr_reader :tax_exempt
    # Will either be "sale" or "credit"
    attr_reader :type
    attr_reader :updated_at
    attr_reader :add_ons, :discounts
    attr_reader :payment_instrument_type
    attr_reader :risk_data
    attr_reader :three_d_secure_info

    def self.create(attributes)
      Configuration.gateway.transaction.create(attributes)
    end

    def self.create!(attributes)
      return_object_or_raise(:transaction) { create(attributes) }
    end

    def self.cancel_release(transaction_id)
      Configuration.gateway.transaction.cancel_release(transaction_id)
    end

    def self.cancel_release!(transaction_id)
      return_object_or_raise(:transaction) { cancel_release(transaction_id) }
    end

    def self.clone_transaction(transaction_id, attributes)
      Configuration.gateway.transaction.clone_transaction(transaction_id, attributes)
    end

    def self.clone_transaction!(transaction_id, attributes)
      return_object_or_raise(:transaction) { clone_transaction(transaction_id, attributes) }
    end

    # Deprecated. Use Braintree::TransparentRedirect.confirm
    def self.create_from_transparent_redirect(query_string)
      warn "[DEPRECATED] Transaction.create_from_transparent_redirect is deprecated. Please use TransparentRedirect.confirm"
      Configuration.gateway.transaction.create_from_transparent_redirect(query_string)
    end

    # Deprecated. Use Braintree::TransparentRedirect.url
    def self.create_transaction_url
      warn "[DEPRECATED] Transaction.create_transaction_url is deprecated. Please use TransparentRedirect.url"
      Configuration.gateway.transaction.create_transaction_url
    end

    def self.credit(attributes)
      Configuration.gateway.transaction.credit(attributes)
    end

    def self.credit!(attributes)
      return_object_or_raise(:transaction) { credit(attributes) }
    end

    def self.find(id)
      Configuration.gateway.transaction.find(id)
    end

    def self.hold_in_escrow(id)
      Configuration.gateway.transaction.hold_in_escrow(id)
    end

    def self.hold_in_escrow!(id)
      return_object_or_raise(:transaction) { hold_in_escrow(id) }
    end

    def self.refund(id, amount = nil)
      Configuration.gateway.transaction.refund(id, amount)
    end

    def self.refund!(id, amount = nil)
      return_object_or_raise(:transaction) { refund(id, amount) }
    end

    def self.sale(attributes)
      Configuration.gateway.transaction.sale(attributes)
    end

    def self.sale!(attributes)
      return_object_or_raise(:transaction) { sale(attributes) }
    end

    def self.search(&block)
      Configuration.gateway.transaction.search(&block)
    end

    def self.release_from_escrow(transaction_id)
      Configuration.gateway.transaction.release_from_escrow(transaction_id)
    end

    def self.release_from_escrow!(transaction_id)
      return_object_or_raise(:transaction) { release_from_escrow(transaction_id) }
    end

    def self.submit_for_settlement(transaction_id, amount = nil)
      Configuration.gateway.transaction.submit_for_settlement(transaction_id, amount)
    end

    def self.submit_for_settlement!(transaction_id, amount = nil)
      return_object_or_raise(:transaction) { submit_for_settlement(transaction_id, amount) }
    end

    def self.void(transaction_id)
      Configuration.gateway.transaction.void(transaction_id)
    end

    def self.void!(transaction_id)
      return_object_or_raise(:transaction) { void(transaction_id) }
    end

    def initialize(gateway, attributes) # :nodoc:
      @gateway = gateway
      set_instance_variables_from_hash(attributes)
      @amount = Util.to_big_decimal(amount)
      @credit_card_details = CreditCardDetails.new(@credit_card)
      @service_fee_amount = Util.to_big_decimal(service_fee_amount)
      @subscription_details = SubscriptionDetails.new(@subscription)
      @customer_details = CustomerDetails.new(@customer)
      @billing_details = AddressDetails.new(@billing)
      @disbursement_details = DisbursementDetails.new(@disbursement_details)
      @shipping_details = AddressDetails.new(@shipping)
      @status_history = attributes[:status_history] ? attributes[:status_history].map { |s| StatusDetails.new(s) } : []
      @tax_amount = Util.to_big_decimal(tax_amount)
      @descriptor = Descriptor.new(@descriptor)
      @paypal_details = PayPalDetails.new(@paypal)
      @apple_pay_details = ApplePayDetails.new(@apple_pay)
      @android_pay_details = AndroidPayDetails.new(@android_pay_card)
      @coinbase_details = CoinbaseDetails.new(@coinbase_account)
      disputes.map! { |attrs| Dispute._new(attrs) } if disputes
      @custom_fields = attributes[:custom_fields].is_a?(Hash) ? attributes[:custom_fields] : {}
      add_ons.map! { |attrs| AddOn._new(attrs) } if add_ons
      discounts.map! { |attrs| Discount._new(attrs) } if discounts
      @payment_instrument_type = attributes[:payment_instrument_type]
      @risk_data = RiskData.new(attributes[:risk_data]) if attributes[:risk_data]
      @three_d_secure_info = ThreeDSecureInfo.new(attributes[:three_d_secure_info]) if attributes[:three_d_secure_info]
    end

    # True if <tt>other</tt> is a Braintree::Transaction with the same id.
    def ==(other)
      return false unless other.is_a?(Transaction)
      id == other.id
    end

    def inspect # :nodoc:
      first = [:id, :type, :amount, :status]
      order = first + (self.class._attributes - first)
      nice_attributes = order.map do |attr|
        if attr == :amount
          self.amount ? "amount: #{self.amount.to_s("F").inspect}" : "amount: nil"
        else
          "#{attr}: #{send(attr).inspect}"
        end
      end
      "#<#{self.class} #{nice_attributes.join(', ')}>"
    end

    # Deprecated. Use Braintree::Transaction.refund
    def refund(amount = nil)
      warn "[DEPRECATED] refund as an instance method is deprecated. Please use Transaction.refund"
      result = @gateway.transaction.refund(id, amount)

      if result.success?
        SuccessfulResult.new(:new_transaction => result.transaction)
      else
        result
      end
    end

    # Returns true if the transaction has been refunded. False otherwise.
    def refunded?
      !@refund_id.nil?
    end

    # Returns true if the transaction has been disbursed. False otherwise.
    def disbursed?
      @disbursement_details.valid?
    end

    def refund_id
      warn "[DEPRECATED] Transaction.refund_id is deprecated. Please use Transaction.refund_ids"
      @refund_id
    end

    # Deprecated. Use Braintree::Transaction.submit_for_settlement
    def submit_for_settlement(amount = nil)
      warn "[DEPRECATED] submit_for_settlement as an instance method is deprecated. Please use Transaction.submit_for_settlement"
      result = @gateway.transaction.submit_for_settlement(id, amount)
      if result.success?
        copy_instance_variables_from_object result.transaction
      end
      result
    end

    # Deprecated. Use Braintree::Transaction.submit_for_settlement!
    def submit_for_settlement!(amount = nil)
      warn "[DEPRECATED] submit_for_settlement! as an instance method is deprecated. Please use Transaction.submit_for_settlement!"
      return_object_or_raise(:transaction) { submit_for_settlement(amount) }
    end

    # If this transaction was stored in the vault, or created from vault records,
    # vault_billing_address will return the associated Braintree::Address. Because the
    # vault billing address can be updated after the transaction was created, the attributes
    # on vault_billing_address may not match the attributes on billing_details.
    def vault_billing_address
      return nil if billing_details.id.nil?
      @gateway.address.find(customer_details.id, billing_details.id)
    end

    # If this transaction was stored in the vault, or created from vault records,
    # vault_credit_card will return the associated Braintree::CreditCard. Because the
    # vault credit card can be updated after the transaction was created, the attributes
    # on vault_credit_card may not match the attributes on credit_card_details.
    def vault_credit_card
      return nil if credit_card_details.token.nil?
      @gateway.credit_card.find(credit_card_details.token)
    end

    # If this transaction was stored in the vault, or created from vault records,
    # vault_customer will return the associated Braintree::Customer. Because the
    # vault customer can be updated after the transaction was created, the attributes
    # on vault_customer may not match the attributes on customer_details.
    def vault_customer
      return nil if customer_details.id.nil?
      @gateway.customer.find(customer_details.id)
    end

    # If this transaction was stored in the vault, or created from vault records,
    # vault_shipping_address will return the associated Braintree::Address. Because the
    # vault shipping address can be updated after the transaction was created, the attributes
    # on vault_shipping_address may not match the attributes on shipping_details.
    def vault_shipping_address
      return nil if shipping_details.id.nil?
      @gateway.address.find(customer_details.id, shipping_details.id)
    end

    # Deprecated. Use Braintree::Transaction.void
    def void
      warn "[DEPRECATED] void as an instance method is deprecated. Please use Transaction.void"
      result = @gateway.transaction.void(id)
      if result.success?
        copy_instance_variables_from_object result.transaction
      end
      result
    end

    # Deprecated. Use Braintree::Transaction.void!
    def void!
      warn "[DEPRECATED] void! as an instance method is deprecated. Please use Transaction.void!"
      return_object_or_raise(:transaction) { void }
    end

    class << self
      protected :new
      def _new(*args) # :nodoc:
        self.new *args
      end
    end

    def self._attributes # :nodoc:
      [:amount, :created_at, :credit_card_details, :customer_details, :id, :status, :subscription_details, :type, :updated_at]
    end
  end
end


text:
package com.java110.job.adapt.hcIot.staff;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.dto.attendanceClasses.AttendanceClassesDto;
import com.java110.dto.org.OrgStaffRelDto;
import com.java110.dto.store.StoreUserDto;
import com.java110.entity.order.Business;
import com.java110.intf.common.IAttendanceClassesInnerServiceSMO;
import com.java110.intf.user.IOrgStaffRelInnerServiceSMO;
import com.java110.job.adapt.DatabusAdaptImpl;
import com.java110.job.adapt.hcIot.asyn.IIotSendAsyn;
import com.java110.po.store.StoreUserPo;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * HC iot 车辆同步适配器
 * <p>
 * 接口协议地址: https://gitee.com/java110/MicroCommunityThings/blob/master/back/docs/api.md
 *
 * @desc add by 吴学文 18:58
 */
@Component(value = "addStaffToIotAdapt")
public class AddStaffToIotAdapt extends DatabusAdaptImpl {

    @Autowired
    private IIotSendAsyn hcStoreUserAsynImpl;

    @Autowired
    private IOrgStaffRelInnerServiceSMO orgStaffRelInnerServiceSMOImpl;

    @Autowired
    private IAttendanceClassesInnerServiceSMO attendanceClassesInnerServiceSMOImpl;

    /**
     * accessToken={access_token}
     * &extCommunityUuid=01000
     * &extCommunityId=1
     * &devSn=111111111
     * &name=设备名称
     * &positionType=0
     * &positionUuid=1
     *
     * @param business   当前处理业务
     * @param businesses 所有业务信息
     */
    @Override
    public void execute(Business business, List<Business> businesses) {
        JSONObject data = business.getData();
        if (data.containsKey(StoreUserPo.class.getSimpleName())) {
            Object bObj = data.get(StoreUserPo.class.getSimpleName());
            JSONArray businessStoreUsers = null;
            if (bObj instanceof JSONObject) {
                businessStoreUsers = new JSONArray();
                businessStoreUsers.add(bObj);
            } else if (bObj instanceof List) {
                businessStoreUsers = JSONArray.parseArray(JSONObject.toJSONString(bObj));
            } else {
                businessStoreUsers = (JSONArray) bObj;
            }
            //JSONObject businessStoreUser = data.getJSONObject("businessStoreUser");
            for (int bStoreUserIndex = 0; bStoreUserIndex < businessStoreUsers.size(); bStoreUserIndex++) {
                JSONObject businessStoreUser = businessStoreUsers.getJSONObject(bStoreUserIndex);
                doSendStoreUser(business, businessStoreUser);
            }
        }
    }

    private void doSendStoreUser(Business business, JSONObject businessStoreUser) {

        StoreUserPo storeUserPo = BeanConvertUtil.covertBean(businessStoreUser, StoreUserPo.class);

        //查询员工部门
        OrgStaffRelDto orgStaffRelDto = new OrgStaffRelDto();
        orgStaffRelDto.setStaffId(storeUserPo.getUserId());
        orgStaffRelDto.setStoreId(storeUserPo.getStoreId());
        List<OrgStaffRelDto> orgStaffRelDtos = orgStaffRelInnerServiceSMOImpl.queryOrgStaffRels(orgStaffRelDto);

        Assert.listOnlyOne(orgStaffRelDtos, "未包含员工信息");

        //查询员工部门是否参与考勤
        AttendanceClassesDto attendanceClassesDto = new AttendanceClassesDto();
        attendanceClassesDto.setClassesObjType(AttendanceClassesDto.CLASSES_OBJ_TYPE_PARTMENT);
        attendanceClassesDto.setClassesObjId(orgStaffRelDtos.get(0).getDepartmentId());
        List<AttendanceClassesDto> attendanceClassesDtos = attendanceClassesInnerServiceSMOImpl.queryAttendanceClassess(attendanceClassesDto);

        //员工部门没有考勤,不用处理
        if (attendanceClassesDtos == null || attendanceClassesDtos.size() < 1) {
            return;
        }
        JSONObject storeUserObj = null;
        List<JSONObject> storeUserObjs = new ArrayList<>();
        for(AttendanceClassesDto tmpAttendanceClassesDto : attendanceClassesDtos ){
            storeUserObj = new JSONObject();
            storeUserObj.put("extClassesId", tmpAttendanceClassesDto.getClassesId());
            storeUserObj.put("extStaffId", orgStaffRelDtos.get(0).getStaffId());
            storeUserObj.put("staffName", orgStaffRelDtos.get(0).getStaffName());
            storeUserObj.put("departmentId", orgStaffRelDtos.get(0).getDepartmentId());
            storeUserObj.put("departmentName", orgStaffRelDtos.get(0).getDepartmentName());
            storeUserObjs.add(storeUserObj);
        }
        JSONObject postParameters = new JSONObject();
        postParameters.put("classesName", attendanceClassesDtos.get(0).getClassesName());
        postParameters.put("extClassesId", attendanceClassesDtos.get(0).getClassesId());
        postParameters.put("extCommunityId", "-1");
        hcStoreUserAsynImpl.addAttendanceStaff(postParameters, storeUserObjs);
    }
}


text:
import {
  Component,
  OnInit
} from '@angular/core';

import {
   FormGroup, FormControl, Validators
} from '@angular/forms';

@Component({
  selector: "reactive-form",
  templateUrl: './reactive-form.component.html',
  styleUrls : ['./reactive-form.component.scss']
})

export class ReactiveFormComponent implements OnInit  {
   reactiveForm : FormGroup;

   constructor(){ }

   ngOnInit(){
       this.reactiveForm = new FormGroup({
           'firstname' : new FormControl("",Validators.compose([
               //this.nameRequiredValidator,
               //this.nameMinLengthValidator(5)
           ]), Validators.composeAsync([
               this.nameAsyncRequiredValidators
           ])) ,
           'lastname' : new FormControl(""),
           'age': new FormControl(0)
       });
    }

  nameAsyncRequiredValidators(control : FormControl){
      return  new Promise((resolve) => {
           setTimeout(()=>{
               if(!control.value){
                    resolve({
                        asyncRequired :true

                    });
               }
               else{
                    resolve(null);
               }
           },1000);
      })
  }

  nameRequiredValidator(control : FormControl)
   {
       if(!control.value){
             return {
                 required :true
             }
       }
       return null;
   }

   nameMinLengthValidator(minValue : number)
   {
       return (control : FormControl) =>{
           if(control.value.length < minValue){
                  return {
                      minLength : true,
                      errorText : "min length error!"
                  }
           }
           return null;
       }
   }

   onSubmit()
   {
       console.log(this.reactiveForm);
   }

}


text:
package server

import (
	"circuit/kit/sched/limiter"
	"circuit/use/circuit"
	"vena"
)

func Spawn(config *vena.Config) {
	lmtr := limiter.New(20)
	for _, sh_ := range config.Shard {
		sh := sh_
		lmtr.Go(func() { spawn(sh, config.ShardAnchor(sh.Key)) })
	}
	lmtr.Wait()
}

func spawn(config *vena.ShardConfig, anchor string) {
	_, addr, err := circuit.Spawn(config.Host, []string{anchor}, start{}, config.Dir, config.Cache)
	if err != nil {
		panic(err)
	}
	println("Shard started", addr.String())
}


text:
package com.qingbo.ginkgo.ygb.project.repository;

import java.util.List;

import com.qingbo.ginkgo.ygb.base.repository.BaseRepository;
import com.qingbo.ginkgo.ygb.project.entity.Investment;

public interface InvestmentRepository extends BaseRepository<Investment> {
	List<Investment> findByProjectIdAndDeletedFalse(Long id);
}


text:
package ru.job4j.collections.banktransfers;

import java.util.*;

/**
 * Class Bank Task Solution: Bank transfers on Stream API [#24260]
 * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
 * @since 24.04.2018
 */
class Bank {
    private TreeMap<User, ArrayList<Account>> storage = new TreeMap<>();

    /**
     * Add user to storage.
     * @param user user.
     */
    void addUser(User user) {
        this.storage.putIfAbsent(user, new ArrayList<>());
    }

    /**
     * Remove user from storage.
     * @param user user.
     */
    void deleteUser(User user) {
        this.storage.remove(user);
    }

    /**
     * Add account to user in storage.
     * @param user user.
     * @param account account.
     */
    void addAccount(User user, Account account) {
        this.storage.get(user).add(account);

    }

    /**
     * Remove account from user in storage.
     * @param user user.
     * @param account account.
     */
    void deleteAccount(User user, Account account) {
        this.storage.get(user).remove(account);
    }

    /**
     * Get all user's account from storage.
     * @param user user.
     * @return List with user's accounts
     */
    List<Account> getUserAccounts(User user) {
        return this.storage.get(user);
    }

    /**
     * Find user in storage.
     * @param passport passport.
     * @return found user or null
     */
    User findUserInStorage(String passport) {
        User result = null;
        Optional<User> optionalUser;
        optionalUser = storage.keySet()
                .stream()
                .filter(user -> user.getPassport().equals(passport))
                .findFirst();
        if (optionalUser.isPresent()) {
            result = optionalUser.get();
        }
        return result;
    }

    /**
     * Find account in storage.
     * @param requisites requisites.
     * @return found account or null
     */
    Account findAccountInStorage(String requisites) {
        Account result = null;
        Optional<Account> optionalAccount;
        List<Account> accountsList = new ArrayList<>();
        this.storage.forEach((user, accounts) -> accountsList.addAll(accounts));
        optionalAccount = accountsList.stream()
                .filter(account -> account.getRequisites().equals(requisites))
                .findFirst();
        if (optionalAccount.isPresent()) {
            result = optionalAccount.get();
        }
        return result;
    }

    /**
     * Validate possibility of money transfer.
     * @param srcPassport srcPassport.
     * @param srcRequisites srcRequisites.
     * @param destPassport destPassport.
     * @param destRequisites destRequisites.
     * @param amount amount.
     * @return validated (true) or not validated (false)
     */
    private boolean transferValidate(String srcPassport,
                                     String srcRequisites,
                                     String destPassport,
                                     String destRequisites,
                                     double amount) {
        boolean result = false;
        User srcUser = findUserInStorage(srcPassport);
        Account srcAccount = findAccountInStorage(srcRequisites);
        User destUser = findUserInStorage(destPassport);
        Account destAccount = findAccountInStorage(destRequisites);
        if ((srcUser != null)
                && (srcAccount != null)
                && (destUser != null)
                && (destAccount != null)
                && (storage.get(srcUser).contains(srcAccount))
                && (storage.get(destUser).contains(destAccount))
                && (srcAccount.getValue() >= amount)) {
            result = true;
        }
        return result;
    }

    /**
     * Transfer money from account to other account.
     * @param srcPassport srcPassport.
     * @param srcRequisites srcRequisites.
     * @param destPassport destPassport.
     * @param destRequisites destRequisites.
     * @param amount amount.
     * @return money transferred (true) or not transferred (false)
     */
    boolean transferMoney(String srcPassport, String srcRequisites,
                                 String destPassport, String destRequisites,
                                 double amount) {
        boolean result = false;
        if (transferValidate(srcPassport,
                             srcRequisites,
                             destPassport,
                             destRequisites,
                             amount)) {
            Account srcAccount = findAccountInStorage(srcRequisites);
            Account destAccount = findAccountInStorage(destRequisites);
            if ((srcAccount != null) && (destAccount != null)) {
                srcAccount.setValue(srcAccount.getValue() - amount);
                destAccount.setValue(destAccount.getValue() + amount);
                result = true;
            }
        }
        return result;
    }
}


text:
//   Copyright 2015 Patrick Putnam
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#ifndef CLOTHO_SIM_ENGINE_MT_HPP_
#define CLOTHO_SIM_ENGINE_MT_HPP_

#ifdef DEBUG_MODE
#define DEBUGGING 0
#endif  // DEBUG_MODE

#include "qtlsim_logger.hpp"

#include <boost/property_tree/ptree.hpp>

#include "clotho/genetics/population_growth_toolkit.hpp"

#include "clotho/data_spaces/allele_space/allele_space.hpp"
#include "clotho/data_spaces/population_space/genetic_space.hpp"
#include "clotho/data_spaces/phenotype_evaluator/trait_accumulator.hpp"
#include "clotho/data_spaces/free_space/free_space_mt.hpp"

#ifdef USE_BATCH_JOBS
#include "clotho/data_spaces/crossover/batch_crossover_mt.hpp"
#define CROSSOVER_TYPE clotho::genetics::BatchCrossoverMT

#include "clotho/data_spaces/phenotype_evaluator/batch_phenotype_mt.hpp"
#define PHENOTYPE_TYPE clotho::genetics::BatchPhenotypeMT

#else
#include "clotho/data_spaces/crossover/crossover_mt.hpp"
#define CROSSOVER_TYPE clotho::genetics::CrossoverMT

#include "clotho/data_spaces/phenotype_evaluator/phenotype_mt.hpp"
#define PHENOTYPE_TYPE clotho::genetics::PhenotypeMT
#endif  // USE_BATCH_JOBS

#include "clotho/data_spaces/selection/selection.hpp"
#include "clotho/data_spaces/mutation/mutation_generator.hpp"
#include "clotho/data_spaces/mutation/mutation_allocator.hpp"

//#include "clotho/data_spaces/crossover/crossover_task_list.hpp"

//#include "clotho/data_spaces/phenotype_evaluator/evaluator.hpp"
#include "clotho/data_spaces/fitness/general_fitness.hpp"

#include "clotho/utility/state_object.hpp"

#include "clotho/data_spaces/task/thread_pool.hpp"

template < class RNG, class RealType = double, class BlockType = unsigned long long >
class EngineMT {
public:
    typedef EngineMT< RNG >             self_type;

    typedef RealType                    position_type;
    typedef RealType                    weight_type;
    typedef weight_type *               phenotype_type;
    typedef BlockType                   block_type;

    typedef RNG                         random_engine_type;

    typedef clotho::genetics::thread_pool< RNG >                                                    thread_pool_type;
    typedef clotho::genetics::qtl_allele_vectorized< position_type, weight_type >                   allele_type;

    typedef clotho::genetics::genetic_space< allele_type, block_type, __ALIGNMENT_TYPE__ > genetic_space_type;

    typedef clotho::genetics::mutation_allocator< random_engine_type, size_t >                      mutation_alloc_type;
    typedef clotho::genetics::MutationGenerator< random_engine_type, genetic_space_type >           mutation_type;
    typedef clotho::genetics::TraitWeightAccumulator< genetic_space_type >                          trait_accumulator_type;
    typedef clotho::genetics::FreeSpaceAnalyzerMT<>                                                 free_space_type;
    typedef clotho::genetics::SelectionGenerator< random_engine_type, clotho::genetics::fitness_selection< genetic_space_type > >          selection_type;
    typedef CROSSOVER_TYPE< random_engine_type, genetic_space_type >                                crossover_type;
//    typedef clotho::genetics::linear_combination< trait_accumulator_type, phenotype_type >          trait_reduction_type;
//    typedef clotho::genetics::phenotype_evaluator< trait_reduction_type >                           phenotype_eval_type;
//
    typedef PHENOTYPE_TYPE< genetic_space_type >                                                    phenotype_eval_type;
    typedef clotho::genetics::GeneralFitness                                                        fitness_type;

    typedef std::shared_ptr< ipopulation_growth_generator >                                         population_growth_generator_type;
    typedef std::shared_ptr< ipopulation_growth >                                                   population_growth_type;

    friend struct clotho::utility::state_getter< self_type >;

    EngineMT( random_engine_type * rng, boost::property_tree::ptree & config ) :
        m_rand( rng )
        , m_parent( &m_pop0 )
        , m_child( &m_pop1 )
        , m_thread_pool( rng, config )
        , m_pheno( config )
        , m_free_space( )
        , select_gen( rng, config )
        , mutate_gen( rng, config )
        , cross_gen( rng, config )
        , m_fit( config )
        , m_generation( 0 )
        , m_pop_growth()
        , m_mut_alloc( rng, config )
    {
        population_growth_generator_type tmp  = population_growth_toolkit::getInstance()->get_tool( config );
        if( tmp ) {
            m_pop_growth = tmp->generate();
            if( m_pop_growth ) {
                m_pop_growth->log( std::cerr );
                std::cerr << std::endl;
            }
        } else {
            population_growth_toolkit::getInstance()->tool_configurations( config );
        }

        m_pop0.getSequenceSpace().clear();
        m_pop1.getSequenceSpace().clear();

        size_t acount = m_pop0.getAlleleSpace().allele_count();
        m_pop0.getAlleleSpace().grow(acount, m_pheno.trait_count());
        m_pop1.getAlleleSpace().grow(acount, m_pheno.trait_count());

        init(acount);
    }

    size_t getGeneration() const {
        return m_generation;
    }

    void init( size_t aN ) {
        size_t pN = m_parent->individual_count();
        if( m_pop_growth ) {
            pN = m_pop_growth->operator()( pN, m_generation );
        }

        m_pop1.grow( pN, aN );

#ifdef USE_ROW_VECTOR
        m_pop1.getSequenceSpace().fill_empty();
        m_pop1.getSequenceSpace().finalize();
#endif // USE_ROW_VECTOR
        ++m_generation;
    }

    void simulate( ) {
        std::swap( m_child, m_parent );     // use the current child population as the parent population for the next round

        // at the start of each simulate round, m_fit has already been updated from the previous
        // round with the fitness of the "then child/now parent" popualtions fitness
        //
        size_t pN = m_parent->individual_count();
        if( m_pop_growth ) {
            pN = m_pop_growth->operator()( pN, m_generation );
        }

        size_t pM = m_mut_alloc.allocate( 2 * pN );        // generate the number of new mutations

        BOOST_LOG_TRIVIAL( debug ) << "Generation " << m_generation << ": " << pN << " individuals; " << pM << " new alleles";

        size_t free_count = updateFixedAlleles( m_parent );    // update the fixed alleles with those of parent population
        select_gen.update( m_parent, pN );

        size_t all_size = child_max_alleles( m_parent->allele_count(), free_count, pM );   // rescale allele space for child population given free space from parent population and new allele count (pM)

        BOOST_LOG_TRIVIAL( info ) << "Rescaling child population to be: " << pN << " individuals x " << all_size << " alleles";

        m_child->grow( pN, all_size );                        // grow the child population accordingly
        m_child->inherit_alleles( m_parent, m_free_space.free_begin(), m_free_space.free_end() );

        cross_gen( m_parent, select_gen.getMatePairs(), m_child, m_thread_pool );

        mutate_gen( m_child, pM );

//        m_trait_accum.update( *m_child );
//        m_pheno.update( m_child, m_trait_accum );

        m_pheno( m_child, m_thread_pool );
        m_fit( m_child, m_pheno );

        ++m_generation;
    }

/*
    void dump( boost::property_tree::ptree & l ) {
        boost::property_tree::ptree par, chi;

        m_parent->dump(par);
        l.put_child( "parent", par );

        m_child->dump(chi);
        l.put_child( "child", chi );

        boost::property_tree::ptree free;
        m_free_space.dump(free);
        l.put_child( "free", free );

        boost::property_tree::ptree tra;
        m_trait_accum.dump( tra );
        l.put_child( "trait", tra );

        boost::property_tree::ptree phe;
        m_pheno.dump(phe);
        l.put_child( "phenotype", phe);

        boost::property_tree::ptree fit;
        m_fit.update(fit);
        l.put_child( "fitness", fit );
    }*/

    genetic_space_type * getChildPopulation() const {
        return m_child;
    }

    genetic_space_type * getParentPopulation() const {
        return m_parent;
    }

    virtual ~EngineMT() { }

protected:

/**
 * estimate the maximum number of alleles in the child
 *
 * N_parent - number of alleles in the parent population
 * F_parent - number of free alleles in the parent population
 * M_child  - number of new alleles to be added the child population
 */
    size_t child_max_alleles( size_t N_parent, size_t F_parent, size_t M_child ) const {
        BOOST_LOG_TRIVIAL(info) << "Parent alleles: " << N_parent << "; Free: " << F_parent << "; New Alleles: " << M_child;

        if( F_parent >= M_child ) {
            // if there are more free alleles in the parent generation
            // than there are new alleles to be added to the child generation
            // then do not adjust scale of the allele space
            return N_parent;
        } else {
            return N_parent + (M_child - F_parent);
        }
    }

    size_t updateFixedAlleles( genetic_space_type * gs ) {
        m_free_space( gs->getSequenceSpace(), m_thread_pool );               // analyze the parent population sequence space

        typedef typename free_space_type::iterator  fixed_iterator;

        fixed_iterator  fix_it = m_free_space.fixed_begin();
        fixed_iterator  fix_end = m_free_space.fixed_end();

        while( fix_it != fix_end ) {
            size_t  fixed_index = *fix_it++;

            gs->getSequenceSpace().flipColumn( fixed_index );

            m_fixed.push_back( gs->getAlleleSpace(), fixed_index );
        }

#ifdef DEBUGGING
        typedef typename free_space_type::iterator free_iterator;
        free_iterator fr_it = m_free_space.free_begin();
        free_iterator fr_end = m_free_space.free_end();

        while( fr_it != fr_end ) {
            size_t i = *fr_it++;

            if( !gs->getSequenceSpace().freeColumn( i ) ) {
                std::cerr << "Column is not actually free: " << i << " out of " << gs->getAlleleSpace().size() << std::endl;
                assert(false);
            }
        }
#endif // DEBUGGING

        return m_free_space.free_size();
    }

    random_engine_type  * m_rand;
    genetic_space_type  m_pop0, m_pop1;
    genetic_space_type  * m_parent, * m_child;

    allele_type             m_fixed;

    thread_pool_type         m_thread_pool;
//    trait_accumulator_type  m_trait_accum;
    phenotype_eval_type     m_pheno;
    free_space_type         m_free_space;

    selection_type          select_gen;
    mutation_type           mutate_gen;
    crossover_type          cross_gen;
    fitness_type            m_fit;

    size_t                  m_generation;

    population_growth_type  m_pop_growth;
    mutation_alloc_type     m_mut_alloc;
};

namespace clotho {
namespace utility {

template < class RNG, class RealType, class BlockType >
struct state_getter< EngineMT< RNG, RealType, BlockType > > {
    typedef EngineMT< RNG, RealType, BlockType >           object_type;

    void operator()( boost::property_tree::ptree & s, object_type & obj ) {
//        boost::property_tree::ptree tr;
//        state_getter< typename object_type::trait_accumulator_type > tr_logger;
//        tr_logger( tr, obj.m_trait_accum );

        boost::property_tree::ptree ph;
        state_getter< typename object_type::phenotype_eval_type > pheno_logger;
        pheno_logger( ph, obj.m_pheno );

        boost::property_tree::ptree fr;
        state_getter< typename object_type::free_space_type > free_logger;
        free_logger( fr, obj.m_free_space );

        boost::property_tree::ptree fx;
        state_getter< typename object_type::allele_type > all_logger;
        all_logger( fx, obj.m_fixed );

        boost::property_tree::ptree c_pop, p_pop;
        state_getter< typename object_type::genetic_space_type > pop_logger;
//        pop_logger( p_pop, *(obj.m_parent) );
        pop_logger( c_pop, *(obj.m_child) );

//        s.put_child( "traits", tr );
        s.put_child( "phenotypes", ph );
        s.put_child( "free_space", fr );
        s.put_child( "fixed_alleles", fx );

        //s.put_child( "parent", p_pop );
        s.put_child( "child", c_pop );
    }
};

}
}

#endif  // CLOTHO_SIM_ENGINE_MT_HPP_


text:
package io.pravega.segmentstore.storage.noop;

import io.pravega.segmentstore.storage.chunklayer.ChunkedRollingStorageTests;
import io.pravega.segmentstore.storage.chunklayer.ChunkStorage;
import io.pravega.segmentstore.storage.chunklayer.ChunkStorageTests;
import io.pravega.segmentstore.storage.chunklayer.SimpleStorageTests;

/**
 * Unit tests for {@link NoOpChunkStorage} using {@link SimpleStorageTests}.
 */
public class NoOpSimpleStorageTests extends SimpleStorageTests {
    @Override
    protected ChunkStorage getChunkStorage() throws Exception {
        return new NoOpChunkStorage(executorService());
    }

    @Override
    protected void populate(byte[] data) {
        // Do nothing keep data uninitialized.
    }

    /**
     * Unit tests for {@link NoOpChunkStorage} using {@link ChunkedRollingStorageTests}.
     */
    public static class NoOpRollingStorageTests extends ChunkedRollingStorageTests {
        @Override
        protected ChunkStorage getChunkStorage() {
            return new NoOpChunkStorage(executorService());
        }

        @Override
        protected void populate(byte[] data) {
            // Do nothing keep data uninitialized.
        }
    }

    /**
     * Unit tests for {@link NoOpChunkStorage} using {@link ChunkStorageTests}.
     */
    public static class NoOpChunkStorageTests extends ChunkStorageTests {
        @Override
        protected ChunkStorage createChunkStorage() {
            return new NoOpChunkStorage(executorService());
        }

        @Override
        protected void populate(byte[] data) {
            // Do nothing keep data uninitialized.
        }
    }
}


text:
package com.tikinou.schedulesdirect.core.commands.message;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tikinou.schedulesdirect.core.commands.AuthenticatedBaseCommandParameter;
import com.tikinou.schedulesdirect.core.domain.SchedulesDirectApiVersion;

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

/**
 * @author Sebastien Astie
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class DeleteMessageCommandParameters extends AuthenticatedBaseCommandParameter {
    @JsonProperty("request")
    private List<String> messageIds;

    public DeleteMessageCommandParameters(){
        this(null);
    }

    public DeleteMessageCommandParameters(List<String> messageIds){
        this(null, messageIds);
    }

    public DeleteMessageCommandParameters(SchedulesDirectApiVersion version, List<String> messageIds){
        super(version);
        this.messageIds = messageIds;
    }

    public List<String> getMessageIds() {
        return messageIds;
    }

    public void setMessageIds(List<String> messageIds) {
        this.messageIds = messageIds;
    }

    @Override
    public String toString() {
        return "DeleteMessageCommandParameters{" + toStringMembers() + '}';
    }

    @Override
    protected String toStringMembers() {
        return super.toStringMembers() +
            ", messageIds=" + (messageIds != null ? Arrays.toString(messageIds.toArray()) : messageIds);
    }
}