text:
import frappe

from frappe.core.doctype.communication.comment import update_comment_in_doc

def execute():
	for d in frappe.db.get_all("Communication",
		fields = ['name', 'reference_doctype', 'reference_name', 'SUBSTRING(content,1,102)', 'communication_type'],
		filters = {"reference_name":None,"reference_doctype":None,'communication_type': 'Communication'}):

		try:
			update_comment_in_doc(d)
		except frappe.ImplicitCommitError:
			pass

redpajama_set_name: RedPajamaGithub


text:
#include "seq_oss_device.h"
#include "seq_oss_synth.h"
#include "seq_oss_midi.h"
#include "seq_oss_writeq.h"
#include "seq_oss_readq.h"
#include "seq_oss_timer.h"
#include "seq_oss_event.h"
#include <linux/init.h>
#include <linux/export.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>

/*
 * common variables
 */
static int maxqlen = SNDRV_SEQ_OSS_MAX_QLEN;
module_param(maxqlen, int, 0444);
MODULE_PARM_DESC(maxqlen, "maximum queue length");

static int system_client = -1; /* ALSA sequencer client number */
static int system_port = -1;

static int num_clients;
static struct seq_oss_devinfo *client_table[SNDRV_SEQ_OSS_MAX_CLIENTS];

/*
 * prototypes
 */
static int receive_announce(struct snd_seq_event *ev, int direct, void *private, int atomic, int hop);
static int translate_mode(struct file *file);
static int create_port(struct seq_oss_devinfo *dp);
static int delete_port(struct seq_oss_devinfo *dp);
static int alloc_seq_queue(struct seq_oss_devinfo *dp);
static int delete_seq_queue(int queue);
static void free_devinfo(void *private);

#define call_ctl(type,rec) snd_seq_kernel_client_ctl(system_client, type, rec)

/*
 * create sequencer client for OSS sequencer
 */
int __init
snd_seq_oss_create_client(void)
{
	int rc;
	struct snd_seq_port_info *port;
	struct snd_seq_port_callback port_callback;

	port = kmalloc(sizeof(*port), GFP_KERNEL);
	if (!port) {
		rc = -ENOMEM;
		goto __error;
	}

	/* create ALSA client */
	rc = snd_seq_create_kernel_client(NULL, SNDRV_SEQ_CLIENT_OSS,
					  "OSS sequencer");
	if (rc < 0)
		goto __error;

	system_client = rc;
	debug_printk(("new client = %d\n", rc));

	/* look up midi devices */
	snd_seq_oss_midi_lookup_ports(system_client);

	/* create annoucement receiver port */
	memset(port, 0, sizeof(*port));
	strcpy(port->name, "Receiver");
	port->addr.client = system_client;
	port->capability = SNDRV_SEQ_PORT_CAP_WRITE; /* receive only */
	port->type = 0;

	memset(&port_callback, 0, sizeof(port_callback));
	/* don't set port_callback.owner here. otherwise the module counter
	 * is incremented and we can no longer release the module..
	 */
	port_callback.event_input = receive_announce;
	port->kernel = &port_callback;

	call_ctl(SNDRV_SEQ_IOCTL_CREATE_PORT, port);
	if ((system_port = port->addr.port) >= 0) {
		struct snd_seq_port_subscribe subs;

		memset(&subs, 0, sizeof(subs));
		subs.sender.client = SNDRV_SEQ_CLIENT_SYSTEM;
		subs.sender.port = SNDRV_SEQ_PORT_SYSTEM_ANNOUNCE;
		subs.dest.client = system_client;
		subs.dest.port = system_port;
		call_ctl(SNDRV_SEQ_IOCTL_SUBSCRIBE_PORT, &subs);
	}
	rc = 0;

 __error:
	kfree(port);
	return rc;
}

/*
 * receive annoucement from system port, and check the midi device
 */
static int
receive_announce(struct snd_seq_event *ev, int direct, void *private, int atomic, int hop)
{
	struct snd_seq_port_info pinfo;

	if (atomic)
		return 0; /* it must not happen */

	switch (ev->type) {
	case SNDRV_SEQ_EVENT_PORT_START:
	case SNDRV_SEQ_EVENT_PORT_CHANGE:
		if (ev->data.addr.client == system_client)
			break; /* ignore myself */
		memset(&pinfo, 0, sizeof(pinfo));
		pinfo.addr = ev->data.addr;
		if (call_ctl(SNDRV_SEQ_IOCTL_GET_PORT_INFO, &pinfo) >= 0)
			snd_seq_oss_midi_check_new_port(&pinfo);
		break;

	case SNDRV_SEQ_EVENT_PORT_EXIT:
		if (ev->data.addr.client == system_client)
			break; /* ignore myself */
		snd_seq_oss_midi_check_exit_port(ev->data.addr.client,
						ev->data.addr.port);
		break;
	}
	return 0;
}

/*
 * delete OSS sequencer client
 */
int
snd_seq_oss_delete_client(void)
{
	if (system_client >= 0)
		snd_seq_delete_kernel_client(system_client);

	snd_seq_oss_midi_clear_all();

	return 0;
}

/*
 * open sequencer device
 */
int
snd_seq_oss_open(struct file *file, int level)
{
	int i, rc;
	struct seq_oss_devinfo *dp;

	dp = kzalloc(sizeof(*dp), GFP_KERNEL);
	if (!dp) {
		snd_printk(KERN_ERR "can't malloc device info\n");
		return -ENOMEM;
	}
	debug_printk(("oss_open: dp = %p\n", dp));

	dp->cseq = system_client;
	dp->port = -1;
	dp->queue = -1;

	for (i = 0; i < SNDRV_SEQ_OSS_MAX_CLIENTS; i++) {
		if (client_table[i] == NULL)
			break;
	}

	dp->index = i;
	if (i >= SNDRV_SEQ_OSS_MAX_CLIENTS) {
		snd_printk(KERN_ERR "too many applications\n");
		rc = -ENOMEM;
		goto _error;
	}

	/* look up synth and midi devices */
	snd_seq_oss_synth_setup(dp);
	snd_seq_oss_midi_setup(dp);

	if (dp->synth_opened == 0 && dp->max_mididev == 0) {
		/* snd_printk(KERN_ERR "no device found\n"); */
		rc = -ENODEV;
		goto _error;
	}

	/* create port */
	debug_printk(("create new port\n"));
	rc = create_port(dp);
	if (rc < 0) {
		snd_printk(KERN_ERR "can't create port\n");
		goto _error;
	}

	/* allocate queue */
	debug_printk(("allocate queue\n"));
	rc = alloc_seq_queue(dp);
	if (rc < 0)
		goto _error;

	/* set address */
	dp->addr.client = dp->cseq;
	dp->addr.port = dp->port;
	/*dp->addr.queue = dp->queue;*/
	/*dp->addr.channel = 0;*/

	dp->seq_mode = level;

	/* set up file mode */
	dp->file_mode = translate_mode(file);

	/* initialize read queue */
	debug_printk(("initialize read queue\n"));
	if (is_read_mode(dp->file_mode)) {
		dp->readq = snd_seq_oss_readq_new(dp, maxqlen);
		if (!dp->readq) {
			rc = -ENOMEM;
			goto _error;
		}
	}

	/* initialize write queue */
	debug_printk(("initialize write queue\n"));
	if (is_write_mode(dp->file_mode)) {
		dp->writeq = snd_seq_oss_writeq_new(dp, maxqlen);
		if (!dp->writeq) {
			rc = -ENOMEM;
			goto _error;
		}
	}

	/* initialize timer */
	debug_printk(("initialize timer\n"));
	dp->timer = snd_seq_oss_timer_new(dp);
	if (!dp->timer) {
		snd_printk(KERN_ERR "can't alloc timer\n");
		rc = -ENOMEM;
		goto _error;
	}
	debug_printk(("timer initialized\n"));

	/* set private data pointer */
	file->private_data = dp;

	/* set up for mode2 */
	if (level == SNDRV_SEQ_OSS_MODE_MUSIC)
		snd_seq_oss_synth_setup_midi(dp);
	else if (is_read_mode(dp->file_mode))
		snd_seq_oss_midi_open_all(dp, SNDRV_SEQ_OSS_FILE_READ);

	client_table[dp->index] = dp;
	num_clients++;

	debug_printk(("open done\n"));
	return 0;

 _error:
	snd_seq_oss_synth_cleanup(dp);
	snd_seq_oss_midi_cleanup(dp);
	delete_seq_queue(dp->queue);
	delete_port(dp);

	return rc;
}

/*
 * translate file flags to private mode
 */
static int
translate_mode(struct file *file)
{
	int file_mode = 0;
	if ((file->f_flags & O_ACCMODE) != O_RDONLY)
		file_mode |= SNDRV_SEQ_OSS_FILE_WRITE;
	if ((file->f_flags & O_ACCMODE) != O_WRONLY)
		file_mode |= SNDRV_SEQ_OSS_FILE_READ;
	if (file->f_flags & O_NONBLOCK)
		file_mode |= SNDRV_SEQ_OSS_FILE_NONBLOCK;
	return file_mode;
}

/*
 * create sequencer port
 */
static int
create_port(struct seq_oss_devinfo *dp)
{
	int rc;
	struct snd_seq_port_info port;
	struct snd_seq_port_callback callback;

	memset(&port, 0, sizeof(port));
	port.addr.client = dp->cseq;
	sprintf(port.name, "Sequencer-%d", dp->index);
	port.capability = SNDRV_SEQ_PORT_CAP_READ|SNDRV_SEQ_PORT_CAP_WRITE; /* no subscription */
	port.type = SNDRV_SEQ_PORT_TYPE_SPECIFIC;
	port.midi_channels = 128;
	port.synth_voices = 128;

	memset(&callback, 0, sizeof(callback));
	callback.owner = THIS_MODULE;
	callback.private_data = dp;
	callback.event_input = snd_seq_oss_event_input;
	callback.private_free = free_devinfo;
	port.kernel = &callback;

	rc = call_ctl(SNDRV_SEQ_IOCTL_CREATE_PORT, &port);
	if (rc < 0)
		return rc;

	dp->port = port.addr.port;
	debug_printk(("new port = %d\n", port.addr.port));

	return 0;
}

/*
 * delete ALSA port
 */
static int
delete_port(struct seq_oss_devinfo *dp)
{
	if (dp->port < 0) {
		kfree(dp);
		return 0;
	}

	debug_printk(("delete_port %i\n", dp->port));
	return snd_seq_event_port_detach(dp->cseq, dp->port);
}

/*
 * allocate a queue
 */
static int
alloc_seq_queue(struct seq_oss_devinfo *dp)
{
	struct snd_seq_queue_info qinfo;
	int rc;

	memset(&qinfo, 0, sizeof(qinfo));
	qinfo.owner = system_client;
	qinfo.locked = 1;
	strcpy(qinfo.name, "OSS Sequencer Emulation");
	if ((rc = call_ctl(SNDRV_SEQ_IOCTL_CREATE_QUEUE, &qinfo)) < 0)
		return rc;
	dp->queue = qinfo.queue;
	return 0;
}

/*
 * release queue
 */
static int
delete_seq_queue(int queue)
{
	struct snd_seq_queue_info qinfo;
	int rc;

	if (queue < 0)
		return 0;
	memset(&qinfo, 0, sizeof(qinfo));
	qinfo.queue = queue;
	rc = call_ctl(SNDRV_SEQ_IOCTL_DELETE_QUEUE, &qinfo);
	if (rc < 0)
		printk(KERN_ERR "seq-oss: unable to delete queue %d (%d)\n", queue, rc);
	return rc;
}

/*
 * free device informations - private_free callback of port
 */
static void
free_devinfo(void *private)
{
	struct seq_oss_devinfo *dp = (struct seq_oss_devinfo *)private;

	if (dp->timer)
		snd_seq_oss_timer_delete(dp->timer);

	if (dp->writeq)
		snd_seq_oss_writeq_delete(dp->writeq);

	if (dp->readq)
		snd_seq_oss_readq_delete(dp->readq);

	kfree(dp);
}

/*
 * close sequencer device
 */
void
snd_seq_oss_release(struct seq_oss_devinfo *dp)
{
	int queue;

	client_table[dp->index] = NULL;
	num_clients--;

	debug_printk(("resetting..\n"));
	snd_seq_oss_reset(dp);

	debug_printk(("cleaning up..\n"));
	snd_seq_oss_synth_cleanup(dp);
	snd_seq_oss_midi_cleanup(dp);

	/* clear slot */
	debug_printk(("releasing resource..\n"));
	queue = dp->queue;
	if (dp->port >= 0)
		delete_port(dp);
	delete_seq_queue(queue);

	debug_printk(("release done\n"));
}

/*
 * Wait until the queue is empty (if we don't have nonblock)
 */
void
snd_seq_oss_drain_write(struct seq_oss_devinfo *dp)
{
	if (! dp->timer->running)
		return;
	if (is_write_mode(dp->file_mode) && !is_nonblock_mode(dp->file_mode) &&
	    dp->writeq) {
		debug_printk(("syncing..\n"));
		while (snd_seq_oss_writeq_sync(dp->writeq))
			;
	}
}

/*
 * reset sequencer devices
 */
void
snd_seq_oss_reset(struct seq_oss_devinfo *dp)
{
	int i;

	/* reset all synth devices */
	for (i = 0; i < dp->max_synthdev; i++)
		snd_seq_oss_synth_reset(dp, i);

	/* reset all midi devices */
	if (dp->seq_mode != SNDRV_SEQ_OSS_MODE_MUSIC) {
		for (i = 0; i < dp->max_mididev; i++)
			snd_seq_oss_midi_reset(dp, i);
	}

	/* remove queues */
	if (dp->readq)
		snd_seq_oss_readq_clear(dp->readq);
	if (dp->writeq)
		snd_seq_oss_writeq_clear(dp->writeq);

	/* reset timer */
	snd_seq_oss_timer_stop(dp->timer);
}

#ifdef CONFIG_PROC_FS
/*
 * misc. functions for proc interface
 */
char *
enabled_str(int bool)
{
	return bool ? "enabled" : "disabled";
}

static char *
filemode_str(int val)
{
	static char *str[] = {
		"none", "read", "write", "read/write",
	};
	return str[val & SNDRV_SEQ_OSS_FILE_ACMODE];
}

/*
 * proc interface
 */
void
snd_seq_oss_system_info_read(struct snd_info_buffer *buf)
{
	int i;
	struct seq_oss_devinfo *dp;

	snd_iprintf(buf, "ALSA client number %d\n", system_client);
	snd_iprintf(buf, "ALSA receiver port %d\n", system_port);

	snd_iprintf(buf, "\nNumber of applications: %d\n", num_clients);
	for (i = 0; i < num_clients; i++) {
		snd_iprintf(buf, "\nApplication %d: ", i);
		if ((dp = client_table[i]) == NULL) {
			snd_iprintf(buf, "*empty*\n");
			continue;
		}
		snd_iprintf(buf, "port %d : queue %d\n", dp->port, dp->queue);
		snd_iprintf(buf, "  sequencer mode = %s : file open mode = %s\n",
			    (dp->seq_mode ? "music" : "synth"),
			    filemode_str(dp->file_mode));
		if (dp->seq_mode)
			snd_iprintf(buf, "  timer tempo = %d, timebase = %d\n",
				    dp->timer->oss_tempo, dp->timer->oss_timebase);
		snd_iprintf(buf, "  max queue length %d\n", maxqlen);
		if (is_read_mode(dp->file_mode) && dp->readq)
			snd_seq_oss_readq_info_read(dp->readq, buf);
	}
}
#endif /* CONFIG_PROC_FS */


text:
class Object
  def as_(key, options = {})
    unless key.blank?
      text = I18n.translate("#{key}", {:scope => [:active_scaffold, *options.delete(:scope)], :default => key.is_a?(String) ? key : key.to_s.titleize}.merge(options)).html_safe
      # text = nil if text.include?('translation missing:')
    end
    text ||= key
    text
  end
end


text:
package com.andrewreitz.onthisday.data.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.andrewreitz.onthisday.data.api.reddit.model.Data;
import shillelagh.Shillelagh;

public class OnThisDaySalineOpenHelper extends SQLiteOpenHelper {

  private static final String DATABASE_NAME = "shillelagh_example.db";
  private static final int DATABASE_VERSION = 1;

  public OnThisDaySalineOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override public void onCreate(SQLiteDatabase db) {
    Shillelagh.createTable(db, Data.class);
  }

  @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    throw new UnsupportedOperationException("Not Implmented");
  }
}


text:
<project name="structs" default="structs">
    <import name="ppci.build.buildtasks" />

    <target name="structs">
        <assemble source="../startup_a9.asm" arch="arm" output="start.oj" />
        <c3compile
            arch="arm"
            sources='../arch.c3'
            output="bsp.oj" />
        <ccompile
            arch="arm"
            sources="../../src/structs/structs.c;../../../librt/libc/lib.c"
            includes="../../../librt/libc/include"
            report="ccode_report.html"
            optimize="2"
            output="ccode.oj" />
        <link objects="start.oj;ccode.oj;bsp.oj" output="structs.oj"
            layout="../memory.mmap" />
        <objcopy
            objectfile="structs.oj"
            imagename="flash"
            format="uimage"
            output="structs.bin" />
    </target>
</project>


text:
require 'nack/server'

require 'minitest/autorun'
require 'json'

class TestNackWorker < Minitest::Test
  include Nack

  attr_accessor :sock, :pid, :heartbeat

  def spawn(fixture)
    config = File.expand_path("../fixtures/#{fixture}.ru", __FILE__)

    pid  = Process.pid
    rand = (rand() * 10000000000).floor

    self.sock = "/tmp/nack.#{pid}.#{rand}.sock"

    self.pid = fork do
      exec "nack_worker", config, sock
    end

    until File.exist?(sock); end
    self.heartbeat = UNIXSocket.open(sock)
  end

  def wait
    Process.kill('TERM', self.pid)
    Process.wait(self.pid)
    self.heartbeat.close if self.heartbeat
  rescue Errno::ESRCH
  end

  def start(fixture = :echo)
    spawn(fixture)
    assert_equal "#{self.pid}\n", heartbeat.readline
    yield
  ensure
    wait
  end

  def request(env = {}, body = nil)
    socket = UNIXSocket.open(sock)

    NetString.write(socket, JSON.generate(env))
    NetString.write(socket, body) if body
    NetString.write(socket, "")

    socket.close_write

    status, headers, body = nil, nil, []

    NetString.read(socket) do |data|
      if status.nil?
        status = data.to_i
      elsif headers.nil?
        headers = JSON.parse(data)
      elsif data.length > 0
        body << data
      else
        # break
      end
    end

    [status, headers, body]
  end

  def test_request
    start do
      status, headers, body = request({}, "foo=bar")

      assert_equal 200, status
      assert_equal "text/plain", headers['Content-Type']
      assert_equal "foo=1\nbar=2", headers['Set-Cookie']
      assert_equal ["foo=bar"], body
    end
  end

  def test_multiple_requests
    start do
      status, headers, body = request
      assert_equal 200, status

      status, headers, body = request
      assert_equal 200, status
    end
  end

  def test_invalid_json_env
    start do
      socket = UNIXSocket.open(sock)

      NetString.write(socket, "")
      socket.close_write

      error = nil

      NetString.read(socket) do |data|
        error = JSON.parse(data)
      end

      assert error

      assert_equal "JSON::ParserError", error['name']
      assert_equal "A JSON text must at least contain two octets!", error['message']
    end
  end

  def test_invalid_netstring
    start do
      socket = UNIXSocket.open(sock)

      socket.write("1:{},")
      socket.close_write

      error = nil

      NetString.read(socket) do |data|
        error = JSON.parse(data)
      end

      assert error
      assert_equal "Nack::Error", error['name']
      assert_equal "Invalid netstring length, expected to be 1", error['message']
    end
  end

  def test_close_heartbeat
    start do
      status = request({}, "foo=bar")[0]
      assert_equal 200, status

      heartbeat.close
      Process.wait(pid)
    end
  end

  def test_app_error
    start :error do
      socket = UNIXSocket.open(sock)

      NetString.write(socket, JSON.generate({}))
      NetString.write(socket, "foo=bar")
      NetString.write(socket, "")

      socket.close_write

      error = nil

      NetString.read(socket) do |data|
        error = JSON.parse(data)
      end

      assert error
      assert_equal "RuntimeError", error['name']
      assert_equal "b00m", error['message']
    end
  end

  def test_spawn_error
    spawn :crash
    error = JSON.parse(heartbeat.read)

    assert error
    assert_equal "RuntimeError", error['name']
    assert_equal "b00m", error['message']
  end
end


text:
import * as angular from 'angular';
import { ButtonTypeEnum } from './buttonTypeEnum';
import { ButtonTemplateType } from './buttonTemplateType';

export interface IButtonScope extends angular.IScope {
  disabled: boolean;
  uifType: string;
}
export interface IButtonAttributes extends angular.IAttributes {
  uifType: string;
  ngHref: string;
  disabled: string;
}

/**
 * @controller
 * @name ButtonController
 * @private
 * @description
 * Used to more easily inject the Angular $log service into the directive.
 */
class ButtonController {
  public static $inject: string[] = ['$log'];
  constructor(public $log: angular.ILogService) { }
}

/**
 * @ngdoc directive
 * @name uifButton
 * @module officeuifabric.components.button
 *
 * @restrict E
 *
 * @description
 * `<uif-button>` is a button directive. This direcive implements multiple types
 * of buttons including action, primary, command, compound and hero buttons. Each type
 * may also support inclusion of icons using the `<uif-icon>` directive. Buttons are
 * rendered as a `<button>` or `<a>` element depending in an `ng-href` attribute is
 * specified. All buttons can be disabled by adding the `disabled` attribute
 *
 * @see {link http://dev.office.com/fabric/components/button}
 *
 * @usage
 *
 * Regular buttons:
 * <uif-button>Lorem Ipsum</uif-button>
 *
 * Primary buttons:
 * <uif-button uif-type="primary">Lorem Ipsum</uif-button>
 *
 * Disabled buttons:
 * <uif-button disabled="disabled">Lorem Ipsum</uif-button>
 * or
 * <uif-button ng-disabled="true">Lorem Ipsum</uif-button>
 *
 * Command buttons:
 * <uif-button uif-type="command">Lorem Ipsum</uif-button>
 * <uif-button uif-type="command">
 *   <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum
 * </uif-button>
 *
 * Compound buttons:
 * <uif-button uif-type="Compound">Lorem Ipsum</uif-button>
 * <uif-button uif-type="Compound">
 *   Lorem Ipsum
 *   <uif-button-description>Lorem Ipsum Description</uif-button-description>
 * </uif-button>
 *
 * Hero buttons:
 * <uif-button uif-type="Hero">Lorem Ipsum</uif-button>
 * <uif-button uif-type="Hero">
 *   <uif-icon uif-type="plus"></uif-icon>
 *   Lorem Ipsum
 * </uif-button>
 */
export class ButtonDirective implements angular.IDirective {

  public restrict: string = 'E';
  public transclude: boolean = true;
  public replace: boolean = true;
  public scope: {} = {};
  public controller: any = ButtonController;
  public controllerAs: string = 'button';

  // array of all the possibilities for a button
  private templateOptions: { [buttonTemplateType: number]: string } = {};

  public static factory(): angular.IDirectiveFactory {
    const directive: angular.IDirectiveFactory = ($log: angular.ILogService) => new ButtonDirective($log);
    directive.$inject = ['$log'];
    return directive;
  }

  constructor(private $log: angular.ILogService) {
    this._populateHtmlTemplates();
  }

  public template: any = ($element: angular.IAugmentedJQuery, $attrs: IButtonAttributes) => {
    // verify button type is supported
    if (!angular.isUndefined($attrs.uifType) && angular.isUndefined(ButtonTypeEnum[$attrs.uifType])) {
      this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.button - Unsupported button: ' +
        'The button (\'' + $attrs.uifType + '\') is not supported by the Office UI Fabric. ' +
        'Supported options are listed here: ' +
        'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/button/buttonTypeEnum.ts');
    }

    // determine template
    switch ($attrs.uifType) {
      // if hero, return button | link
      case ButtonTypeEnum[ButtonTypeEnum.primary]:
        return angular.isUndefined($attrs.ngHref)
          ? this.templateOptions[ButtonTemplateType.primaryButton]
          : this.templateOptions[ButtonTemplateType.primaryLink];
      // if command, return button | link
      case ButtonTypeEnum[ButtonTypeEnum.command]:
        return angular.isUndefined($attrs.ngHref)
          ? this.templateOptions[ButtonTemplateType.commandButton]
          : this.templateOptions[ButtonTemplateType.commandLink];
      // if compound, return button | link
      case ButtonTypeEnum[ButtonTypeEnum.compound]:
        return angular.isUndefined($attrs.ngHref)
          ? this.templateOptions[ButtonTemplateType.compoundButton]
          : this.templateOptions[ButtonTemplateType.compoundLink];
      // if hero, return button | link
      case ButtonTypeEnum[ButtonTypeEnum.hero]:
        return angular.isUndefined($attrs.ngHref)
          ? this.templateOptions[ButtonTemplateType.heroButton]
          : this.templateOptions[ButtonTemplateType.heroLink];
      // else no type specified, so it's an action button
      default:
        return angular.isUndefined($attrs.ngHref)
          ? this.templateOptions[ButtonTemplateType.actionButton]
          : this.templateOptions[ButtonTemplateType.actionLink];
    }
  }

  public compile(
    element: angular.IAugmentedJQuery,
    attrs: IButtonAttributes,
    transclude: angular.ITranscludeFunction): angular.IDirectivePrePost {
    return {
      post: this.postLink,
      pre: this.preLink
    };
  }

  /**
   * Update the scope before linking everything up.
   */
  private preLink(
    scope: IButtonScope,
    element: angular.IAugmentedJQuery,
    attrs: IButtonAttributes,
    controllers: any,
    transclude: angular.ITranscludeFunction): void {

    attrs.$observe('disabled', (isDisabled) => {
      scope.disabled = !!isDisabled;
    });

    // if disabled prevent click action
    element.on('click', (e: Event) => {
      if (scope.disabled) {
        e.preventDefault();
      }
    });
  }

  /**
   * Check the rendered HTML for anything that is invalid.
   */
  private postLink(
    scope: IButtonScope,
    element: angular.IAugmentedJQuery,
    attrs: IButtonAttributes,
    controllers: any,
    transclude: angular.ITranscludeFunction): void {

    // if an icon was added to the button's contents for specific button types
    //  that don't support icons, remove the icon
    if (angular.isUndefined(attrs.uifType) ||
      attrs.uifType === ButtonTypeEnum[ButtonTypeEnum.primary] ||
      attrs.uifType === ButtonTypeEnum[ButtonTypeEnum.compound]) {
      let iconElement: JQuery = element.find('uif-icon');
      if (iconElement.length !== 0) {
        iconElement.remove();
        controllers.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.button - ' +
          'Icon not allowed in primary or compound buttons: ' +
          'The primary & compound button does not support including icons in the body. ' +
          'The icon has been removed but may cause rendering errors. Consider buttons that support icons such as command or hero.');
      }
    }

    // create necessary wrappers around inner content in button depending on button type
    transclude((clone: angular.IAugmentedJQuery) => {
      let wrapper: angular.IAugmentedJQuery;

      switch (attrs.uifType) {
        // if type === command
        case ButtonTypeEnum[ButtonTypeEnum.command]:
          for (let i: number = 0; i < clone.length; i++) {
            // wrap the button label
            if (this._isValidLabel(clone[i])) {
              wrapper = angular.element('');
              wrapper.addClass('ms-Button-label').append(clone[i]);
              element.append(wrapper);
            }
            // wrap the button's icon
            if (clone[i].tagName === 'UIF-ICON') {
              wrapper = angular.element('');
              wrapper.addClass('ms-Button-icon').append(clone[i]);
              element.append(wrapper);
            }
          }
          break;
        // if type === compound
        case ButtonTypeEnum[ButtonTypeEnum.compound]:
          for (let i: number = 0; i < clone.length; i++) {
            // icon is not supported on compound button
            if (clone[i].tagName === 'UIF-ICON') {
              continue;
            }

            // wrap the button label
            if (this._isValidLabel(clone[i])) {
              wrapper = angular.element('');
              wrapper.addClass('ms-Button-label').append(clone[i]);
              element.append(wrapper);
              // add the description... just add it to the button
            } else {
              element.append(clone[i]);
            }
          }
          break;
        // if type === hero
        case ButtonTypeEnum[ButtonTypeEnum.hero]:
          for (let i: number = 0; i < clone.length; i++) {
            // wrap the label
            if (this._isValidLabel(clone[i])) {
              wrapper = angular.element('');
              wrapper.addClass('ms-Button-label').append(clone[i]);
              element.append(wrapper);
            }
            // wrap the icon
            if (clone[i].tagName === 'UIF-ICON') {
              wrapper = angular.element('');
              wrapper.addClass('ms-Button-icon').append(clone[i]);
              element.append(wrapper);
            }
          }
          break;
        default:
          break;
      }
    });

  }

  private _isValidLabel(clone: HTMLElement): boolean {
    return clone.nodeType === Node.TEXT_NODE && clone.nodeValue.trim().length > 0;
  }

  private _populateHtmlTemplates(): void {
    // regular / action button
    this.templateOptions[ButtonTemplateType.actionButton] =
      `<button class="ms-Button" ng-class="{\'is-disabled\': disabled}">

       </button>`;
    this.templateOptions[ButtonTemplateType.actionLink] =
      `

       `;

    // primary button
    this.templateOptions[ButtonTemplateType.primaryButton] =
      `<button class="ms-Button ms-Button--primary" ng-class="{\'is-disabled\': disabled}">

       </button>`;
    this.templateOptions[ButtonTemplateType.primaryLink] =
      `

       `;

    // command button
    this.templateOptions[ButtonTemplateType.commandButton] =
      `<button class="ms-Button ms-Button--command" ng-class="{\'is-disabled\': disabled}"></button>`;
    this.templateOptions[ButtonTemplateType.commandLink] =
      `<a class="ms-Button ms-Button--command" ng-class="{\'is-disabled\': disabled}"></a>`;

    // compound button
    this.templateOptions[ButtonTemplateType.compoundButton] =
      `<button class="ms-Button ms-Button--compound" ng-class="{\'is-disabled\': disabled}"></button>`;
    this.templateOptions[ButtonTemplateType.compoundLink] =
      `<a class="ms-Button ms-Button--compound" ng-class="{\'is-disabled\': disabled}"></a>`;

    // hero button
    this.templateOptions[ButtonTemplateType.heroButton] =
      `<button class="ms-Button ms-Button--hero" ng-class="{\'is-disabled\': disabled}"></button>`;
    this.templateOptions[ButtonTemplateType.heroLink] =
      `<a class="ms-Button ms-Button--hero" ng-class="{\'is-disabled\': disabled}"></a>`;
  }
}

/**
 * @ngdoc directive
 * @name uifDescriptionButton
 * @module officeuifabric.components.button
 *
 * @restrict E
 *
 * @description
 * `<uif-button-description>` is a button description directive.
 *
 * @see {link http://dev.office.com/fabric/components/button}
 *
 * @usage
 *
 * <uif-button-description>Lorem Ipsum</uif-button-description>
 */
export class ButtonDescriptionDirective implements angular.IDirective {

  public restrict: string = 'E';
  public require: string = '^uifButton';
  public transclude: boolean = true;
  public replace: boolean = true;
  public scope: boolean = false;
  public template: string = '';

  public static factory(): angular.IDirectiveFactory {
    const directive: angular.IDirectiveFactory = () => new ButtonDescriptionDirective();
    return directive;
  }

}

/**
 * @ngdoc module
 * @name officeuifabric.components.button
 *
 * @description
 * Button
 *
 */
export let module: angular.IModule = angular.module('officeuifabric.components.button', [
  'officeuifabric.components'
])
  .directive('uifButton', ButtonDirective.factory())
  .directive('uifButtonDescription', ButtonDescriptionDirective.factory());


text:
package com.wuxian99.finance.basedata.domain;

import com.google.gson.Gson;
import com.wuxian99.finance.basedata.support.annotation.Ddic;
import com.wuxian99.finance.basedata.support.annotation.UploadRef;

import javax.persistence.*;
import java.io.Serializable;

/**
 * 商品
 */
@Entity
@Table(name="mdse")
public class MdseEntity implements Serializable {

  @Id
  @GeneratedValue(strategy= GenerationType.IDENTITY)
  private Long id;

  /**
   * 酒庄编号
   */
  @Column(name = "merchantid")
  private String merchantId;

  /**
   * 产区
   */
  @Column(name = "productarea")
  private String productArea;

  /**
   * 中文名称
   */
  private String name;

  /**
   * 英文名称
   */
  @Column(name = "nameen")
  private String nameEn;

  /**
   * 价格,单位分
   */
  private Long price;

  /**
   * 状态,1:上架,0:下架,2:售罄
   */
  @Ddic(name = "mdseStatus",mapTo = "statusName")
  private Long status;

  @Transient
  private String statusName;

  /**
   * 酒品类型,1:红葡萄酒,2:白葡萄酒,3:起泡酒,4:冰酒,5:桃红葡萄酒
   */
  @Ddic(name = "mdseCatagory",mapTo = "catagoryName")
  private String catagory;

  @Transient
  private String catagoryName;

  /**
   * 葡萄品种
   */
  @Column(name = "grapetype")
  private String grapeType;

  /**
   * 生产年份
   */
  private String year;

  /**
   * 酒精度
   */
  private String degree;

  /**
   * 净含量
   */
  private String ml;

  /**
   * 平均树龄
   */
  @Column(name = "treeage")
  private String treeAge;

  /**
   * 酿酒师介绍
   */
  @Column(name = "winemaker")
  private String wineMaker;

  /**
   * 商品小图,用于列表和购物车展示
   */
  @Column(name = "smallpic")
  private String smallPic;

  @Column(name = "smallpic_ref")
  @UploadRef(ref = "smallPic")
  private String smallPicRef;

  /**
   * 商品大图1,用于商品详情页展示
   */
  @Column(name = "bigpic1")
  private String bigPic1;

  @Column(name = "bigpic1_ref")
  @UploadRef(ref = "bigPic1")
  private String bigPic1Ref;

  /**
   * 商品大图2,用于商品详情页展示
   */
  @Column(name = "bigpic2")
  private String bigPic2;

  @Column(name = "bigpic2_ref")
  @UploadRef(ref = "bigPic2")
  private String bigPic2Ref;

  /**
   * 商品大图3,用于商品详情页展示
   */
  @Column(name = "bigpic3")
  private String bigPic3;

  @Column(name = "bigpic3_ref")
  @UploadRef(ref = "bigPic3")
  private String bigPic3Ref;

  /**
   * 商品大图4,用于商品详情页展示
   */
  @Column(name = "bigpic4")
  private String bigPic4;

  @Column(name = "bigpic4_ref")
  @UploadRef(ref = "bigPic4")
  private String bigPic4Ref;

  //=======================================废弃的属性Start==========================================
  /**
   * 推荐理由
   */
  @Deprecated
  private String reason;

  /**
   * 故事和品鉴
   */
  @Column(name = "storypic")
  @Deprecated
  private String storyPic;

  @Column(name = "storypic_ref")
  @UploadRef(ref = "storyPic")
  @Deprecated
  private String storyPicRef;
  //=======================================废弃的属性End==========================================

  //=======================================新增的属性Start==========================================
  /**
   * 酿造工艺
   */
  private String technology;

  /**
   * 橡木桶
   */
  private String barrel;

  /**
   * 罐装时间
   */
  @Column(name = "fillingtime")
  private String fillingTime;

  /**
   * 保质期
   */
  @Column(name = "expirydate")
  private String expiryDate;

  /**
   * 适饮温度
   */
  @Column(name = "drinktemperature")
  private String drinkTemperature;

  /**
   * 醒酒时间
   */
  @Column(name = "sobertime")
  private String soberTime;

  /**
   * 搭配推荐
   */
  @Column(name = "collocation")
  private String collocation;

  /**
   * 产量
   */
  private String yield;

  /**
   * 库存量
   */
  private String inventory;

  /**
   * 得奖照片1
   */
  @Column(name = "prizepic1")
  private String prizePic1;

  @Column(name = "prizepic1_ref")
  @UploadRef(ref = "prizePic1")
  private String prizePic1Ref;

  /**
   * 得奖照片2
   */
  @Column(name = "prizepic2")
  private String prizePic2;

  @Column(name = "prizepic2_ref")
  @UploadRef(ref = "prizePic2")
  private String prizePic2Ref;

  /**
   * 得奖照片3
   */
  @Column(name = "prizepic3")
  private String prizePic3;

  @Column(name = "prizepic3_ref")
  @UploadRef(ref = "prizePic3")
  private String prizePic3Ref;

  /**
   * 得奖照片4
   */
  @Column(name = "prizepic4")
  private String prizePic4;

  @Column(name = "prizepic4_ref")
  @UploadRef(ref = "prizePic4")
  private String prizePic4Ref;

  /**
   * 检验报告1
   */
  @Column(name = "inspectionreportpic1")
  private String inspectionReportPic1;

  @Column(name = "inspectionreportpic1_ref")
  @UploadRef(ref = "inspectionReportPic1")
  private String inspectionReportPic1Ref;

  /**
   * 检验报告2
   */
  @Column(name = "inspectionreportpic2")
  private String inspectionReportPic2;

  @Column(name = "inspectionreportpic2_ref")
  @UploadRef(ref = "inspectionReportPic2")
  private String inspectionReportPic2Ref;

  /**
   * 检验报告3
   */
  @Column(name = "inspectionreportpic3")
  private String inspectionReportPic3;

  @Column(name = "inspectionreportpic3_ref")
  @UploadRef(ref = "inspectionReportPic3")
  private String inspectionReportPic3Ref;

  /**
   * 检验报告4
   */
  @Column(name = "inspectionreportpic4")
  private String inspectionReportPic4;

  @Column(name = "inspectionreportpic4_ref")
  @UploadRef(ref = "inspectionReportPic4")
  private String inspectionReportPic4Ref;
  //=======================================新增的属性End==========================================

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getMerchantId() {
    return merchantId;
  }

  public void setMerchantId(String merchantId) {
    this.merchantId = merchantId;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getNameEn() {
    return nameEn;
  }

  public void setNameEn(String nameEn) {
    this.nameEn = nameEn;
  }

  public Long getPrice() {
    return price;
  }

  public void setPrice(Long price) {
    this.price = price;
  }

  public Long getStatus() {
    return status;
  }

  public void setStatus(Long status) {
    this.status = status;
  }

  public String getStatusName() {
    return statusName;
  }

  public void setStatusName(String statusName) {
    this.statusName = statusName;
  }

  public String getCatagory() {
    return catagory;
  }

  public void setCatagory(String catagory) {
    this.catagory = catagory;
  }

  public String getCatagoryName() {
    return catagoryName;
  }

  public void setCatagoryName(String catagoryName) {
    this.catagoryName = catagoryName;
  }

  public String getGrapeType() {
    return grapeType;
  }

  public void setGrapeType(String grapeType) {
    this.grapeType = grapeType;
  }

  public String getYear() {
    return year;
  }

  public void setYear(String year) {
    this.year = year;
  }

  public String getDegree() {
    return degree;
  }

  public void setDegree(String degree) {
    this.degree = degree;
  }

  public String getMl() {
    return ml;
  }

  public void setMl(String ml) {
    this.ml = ml;
  }

  public String getTreeAge() {
    return treeAge;
  }

  public void setTreeAge(String treeAge) {
    this.treeAge = treeAge;
  }

  public String getWineMaker() {
    return wineMaker;
  }

  public void setWineMaker(String wineMaker) {
    this.wineMaker = wineMaker;
  }

  public String getProductArea() {
    return productArea;
  }

  public void setProductArea(String productArea) {
    this.productArea = productArea;
  }

  public String getSmallPic() {
    return smallPic;
  }

  public void setSmallPic(String smallPic) {
    this.smallPic = smallPic;
  }

  public String getBigPic1() {
    return bigPic1;
  }

  public void setBigPic1(String bigPic1) {
    this.bigPic1 = bigPic1;
  }

  public String getBigPic2() {
    return bigPic2;
  }

  public void setBigPic2(String bigPic2) {
    this.bigPic2 = bigPic2;
  }

  public String getBigPic3() {
    return bigPic3;
  }

  public void setBigPic3(String bigPic3) {
    this.bigPic3 = bigPic3;
  }

  public String getBigPic4() {
    return bigPic4;
  }

  public void setBigPic4(String bigPic4) {
    this.bigPic4 = bigPic4;
  }

  public String getReason() {
    return reason;
  }

  public void setReason(String reason) {
    this.reason = reason;
  }

  public String getStoryPic() {
    return storyPic;
  }

  public void setStoryPic(String storyPic) {
    this.storyPic = storyPic;
  }

  public String getSmallPicRef() {
    return smallPicRef;
  }

  public void setSmallPicRef(String smallPicRef) {
    this.smallPicRef = smallPicRef;
  }

  public String getBigPic1Ref() {
    return bigPic1Ref;
  }

  public void setBigPic1Ref(String bigPic1Ref) {
    this.bigPic1Ref = bigPic1Ref;
  }

  public String getBigPic2Ref() {
    return bigPic2Ref;
  }

  public void setBigPic2Ref(String bigPic2Ref) {
    this.bigPic2Ref = bigPic2Ref;
  }

  public String getBigPic3Ref() {
    return bigPic3Ref;
  }

  public void setBigPic3Ref(String bigPic3Ref) {
    this.bigPic3Ref = bigPic3Ref;
  }

  public String getBigPic4Ref() {
    return bigPic4Ref;
  }

  public void setBigPic4Ref(String bigPic4Ref) {
    this.bigPic4Ref = bigPic4Ref;
  }

  public String getStoryPicRef() {
    return storyPicRef;
  }

  public void setStoryPicRef(String storyPicRef) {
    this.storyPicRef = storyPicRef;
  }

  public String getTechnology() {
    return technology;
  }

  public void setTechnology(String technology) {
    this.technology = technology;
  }

  public String getBarrel() {
    return barrel;
  }

  public void setBarrel(String barrel) {
    this.barrel = barrel;
  }

  public String getFillingTime() {
    return fillingTime;
  }

  public void setFillingTime(String fillingTime) {
    this.fillingTime = fillingTime;
  }

  public String getExpiryDate() {
    return expiryDate;
  }

  public void setExpiryDate(String expiryDate) {
    this.expiryDate = expiryDate;
  }

  public String getDrinkTemperature() {
    return drinkTemperature;
  }

  public void setDrinkTemperature(String drinkTemperature) {
    this.drinkTemperature = drinkTemperature;
  }

  public String getSoberTime() {
    return soberTime;
  }

  public void setSoberTime(String soberTime) {
    this.soberTime = soberTime;
  }

  public String getCollocation() {
    return collocation;
  }

  public void setCollocation(String collocation) {
    this.collocation = collocation;
  }

  public String getYield() {
    return yield;
  }

  public void setYield(String yield) {
    this.yield = yield;
  }

  public String getInventory() {
    return inventory;
  }

  public void setInventory(String inventory) {
    this.inventory = inventory;
  }

  public String getPrizePic1() {
    return prizePic1;
  }

  public void setPrizePic1(String prizePic1) {
    this.prizePic1 = prizePic1;
  }

  public String getPrizePic1Ref() {
    return prizePic1Ref;
  }

  public void setPrizePic1Ref(String prizePic1Ref) {
    this.prizePic1Ref = prizePic1Ref;
  }

  public String getPrizePic2() {
    return prizePic2;
  }

  public void setPrizePic2(String prizePic2) {
    this.prizePic2 = prizePic2;
  }

  public String getPrizePic2Ref() {
    return prizePic2Ref;
  }

  public void setPrizePic2Ref(String prizePic2Ref) {
    this.prizePic2Ref = prizePic2Ref;
  }

  public String getPrizePic3() {
    return prizePic3;
  }

  public void setPrizePic3(String prizePic3) {
    this.prizePic3 = prizePic3;
  }

  public String getPrizePic3Ref() {
    return prizePic3Ref;
  }

  public void setPrizePic3Ref(String prizePic3Ref) {
    this.prizePic3Ref = prizePic3Ref;
  }

  public String getPrizePic4() {
    return prizePic4;
  }

  public void setPrizePic4(String prizePic4) {
    this.prizePic4 = prizePic4;
  }

  public String getPrizePic4Ref() {
    return prizePic4Ref;
  }

  public void setPrizePic4Ref(String prizePic4Ref) {
    this.prizePic4Ref = prizePic4Ref;
  }

  public String getInspectionReportPic1() {
    return inspectionReportPic1;
  }

  public void setInspectionReportPic1(String inspectionReportPic1) {
    this.inspectionReportPic1 = inspectionReportPic1;
  }

  public String getInspectionReportPic1Ref() {
    return inspectionReportPic1Ref;
  }

  public void setInspectionReportPic1Ref(String inspectionReportPic1Ref) {
    this.inspectionReportPic1Ref = inspectionReportPic1Ref;
  }

  public String getInspectionReportPic2() {
    return inspectionReportPic2;
  }

  public void setInspectionReportPic2(String inspectionReportPic2) {
    this.inspectionReportPic2 = inspectionReportPic2;
  }

  public String getInspectionReportPic2Ref() {
    return inspectionReportPic2Ref;
  }

  public void setInspectionReportPic2Ref(String inspectionReportPic2Ref) {
    this.inspectionReportPic2Ref = inspectionReportPic2Ref;
  }

  public String getInspectionReportPic3() {
    return inspectionReportPic3;
  }

  public void setInspectionReportPic3(String inspectionReportPic3) {
    this.inspectionReportPic3 = inspectionReportPic3;
  }

  public String getInspectionReportPic3Ref() {
    return inspectionReportPic3Ref;
  }

  public void setInspectionReportPic3Ref(String inspectionReportPic3Ref) {
    this.inspectionReportPic3Ref = inspectionReportPic3Ref;
  }

  public String getInspectionReportPic4() {
    return inspectionReportPic4;
  }

  public void setInspectionReportPic4(String inspectionReportPic4) {
    this.inspectionReportPic4 = inspectionReportPic4;
  }

  public String getInspectionReportPic4Ref() {
    return inspectionReportPic4Ref;
  }

  public void setInspectionReportPic4Ref(String inspectionReportPic4Ref) {
    this.inspectionReportPic4Ref = inspectionReportPic4Ref;
  }

  @Override
  public String toString() {
    return new Gson().toJson(this);
  }
}


text:
> [Introduced][ce-30469] in GitLab 9.3.

Conversational Development Index (ConvDev) gives you an overview of your entire
instance's feature usage, from idea to production. It looks at your usage in the
past 30 days, averaged over the number of active users in that time period. It also
provides a lead score per feature, which is calculated based on GitLab's analysis
of top performing instances, based on [usage ping data][ping] that GitLab has
collected. Your score is compared to the lead score, expressed as a percentage.
The overall index score is an average over all your feature scores.

![ConvDev index](img/convdev_index.png)

The page also provides helpful links to articles and GitLab docs, to help you
improve your scores.

Your GitLab instance's usage ping must be activated in order to use this feature.
Usage ping data is aggregated on GitLab's servers for analysis. Your usage
information is **not sent** to any other GitLab instances.

If you have just started using GitLab, it may take a few weeks for data to be
collected before this feature is available.

This feature is accessible only to a system admin, at
**Admin area > Monitoring > ConvDev Index**.

[ce-30469]: https://gitlab.com/gitlab-org/gitlab-ce/issues/30469
[ping]: ../settings/usage_statistics.md#usage-ping


text:
import { action, observable, makeObservable } from "mobx";
import _ from "lodash";
import { $try } from "./utils";
import ValidatorInterface, {
  DriversMap,
  ValidationPluginInterface,
  ValidationPlugins,
} from "./models/ValidatorInterface";
import FormInterface from "./models/FormInterface";
import { OptionsEnum } from "./models/OptionsModel";

export default class Validator implements ValidatorInterface {
  promises: Promise<any>[] = [];

  form: FormInterface = null;

  drivers: DriversMap = {};

  plugins: ValidationPlugins = {
    vjf: undefined,
    dvr: undefined,
    svk: undefined,
    yup: undefined,
  };

  error: string | null = null;

  constructor(obj: any = {}) {
    makeObservable(this, {
      error: observable,
      validate: action,
      validateField: action,
    });
    _.merge(this.plugins, obj.plugins);
    this.form = obj.form;

    this.initDrivers();
    this.checkSVKValidationPlugin();
  }

  initDrivers(): void {
    _.map(
      this.plugins,
      (driver, key) =>
        (this.drivers[key] =
          driver &&
          _.has(driver, "class") &&
          new driver.class({
            config: driver.config,
            state: this.form.state,
            promises: this.promises,
          }))
    );
  }

  validate(opt: any = {}, obj: any = {}): Promise<any> {
    const path = $try(opt.path, opt);
    const field = $try(opt.field, this.form.select(path, null, null));
    const related = $try(opt.related, obj.related, true);
    const showErrors = $try(opt.showErrors, obj.showErrors, false);
    const instance = field || this.form;
    instance.$validating = true;
    instance.$validated += 1;

    this.error = null;

    return new Promise((resolve) => {
      // validate instance (form or filed)
      if (instance.path || _.isString(path)) {
        this.validateField({
          field: instance,
          showErrors,
          related,
          path,
        });
      }

      // validate nested fields
      instance.each((field: any) =>
        this.validateField({
          path: field.path,
          field: field,
          showErrors,
          related,
        })
      );

      // wait all promises
      resolve(Promise.all(this.promises));
    })
      .then(
        action(() => {
          instance.$validating = false;
          instance.$clearing = false;
          instance.$resetting = false;
        })
      )
      .catch(
        action((err) => {
          instance.$validating = false;
          instance.$clearing = false;
          instance.$resetting = false;
          throw err;
        })
      )
      .then(() => instance);
  }

  validateField({
    showErrors = false,
    related = false,
    field = null,
    path,
  }: any): void {
    const instance = field || this.form.select(path);
    // check if the field is a valid instance
    if (!instance.path)
      throw new Error("Validation Error: Invalid Field Instance");
    // do not validate soft deleted fields
    if (
      instance.deleted &&
      !this.form.state.options.get(OptionsEnum.validateDeletedFields)
    )
      return;
    // do not validate disabled fields
    if (
      instance.disabled &&
      !this.form.state.options.get(OptionsEnum.validateDisabledFields)
    )
      return;
    // do not validate pristine fields
    if (
      instance.isPristine &&
      !this.form.state.options.get(OptionsEnum.validatePristineFields)
    )
      return;

    // reset field validation
    instance.resetValidation();

    // validate with all enabled drivers
    const stopOnError = instance.state.options.get(
      OptionsEnum.stopValidationOnError,
      instance
    );

    // get validation order
    const validationOrder = instance.state.options.get(
      OptionsEnum.validationOrder,
      instance
    );

    const drivers = validationOrder
      ? validationOrder.map((n: string) => this.drivers[n])
      : this.drivers;

    _.each(drivers, (driver: ValidationPluginInterface) => {
      driver && driver.validate(instance);
      if (stopOnError && instance.hasError) {
        return false;
      }
    });

    // send error to the view
    instance.showErrors(showErrors);

    // related validation
    if (related) this.validateRelatedFields(instance, showErrors);
  }

  /**
    Validate 'related' fields if specified
    and related validation allowed (recursive)
  */
  validateRelatedFields(field: any, showErrors: boolean): void {
    if (!field.related || !field.related.length) return;

    _.each(field.related, (path) =>
      this.validateField({
        related: false,
        showErrors,
        path,
      })
    );
  }

  checkSVKValidationPlugin(): void {
    if (_.isNil(this.drivers.svk) && _.get(this.plugins, "svk.config.schema")) {
      const form = (this as any).state.form.name
        ? `Form: ${(this as any).state.form.name}`
        : "";
      throw new Error(
        `The SVK validation schema is defined but no plugin provided (SVK). ${form}`
      );
    }
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: lephuong
 * Date: 9/26/16
 * Time: 10:24 PM
 */
namespace console\modules\backup\transports;

use yii\base\Object;

class Base extends Object {

	public $enable = false;
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="stylesheet" type="text/css" href="css/component.css" />

					<button>3D rotate in</button>


text:
package com.thoughtworks.go.agent;

import com.thoughtworks.go.agent.service.AgentUpgradeService;
import com.thoughtworks.go.agent.service.AgentWebsocketService;
import com.thoughtworks.go.agent.service.SslInfrastructureService;
import com.thoughtworks.go.buildsession.BuildSessionBasedTestCase;
import com.thoughtworks.go.config.AgentRegistry;
import com.thoughtworks.go.config.GuidService;
import com.thoughtworks.go.domain.AgentRuntimeStatus;
import com.thoughtworks.go.domain.BuildCommand;
import com.thoughtworks.go.domain.BuildSettings;
import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.JobState;
import com.thoughtworks.go.domain.Property;
import com.thoughtworks.go.plugin.access.packagematerial.PackageAsRepositoryExtension;
import com.thoughtworks.go.plugin.access.pluggabletask.TaskExtension;
import com.thoughtworks.go.plugin.access.scm.SCMExtension;
import com.thoughtworks.go.plugin.infra.PluginManager;
import com.thoughtworks.go.plugin.infra.PluginManagerReference;
import com.thoughtworks.go.publishers.GoArtifactsManipulator;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.BuildRepositoryRemote;
import com.thoughtworks.go.remote.work.Work;
import com.thoughtworks.go.server.service.AgentBuildingInfo;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.util.HttpService;
import com.thoughtworks.go.util.SubprocessLogger;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import com.thoughtworks.go.websocket.Action;
import com.thoughtworks.go.websocket.Message;
import com.thoughtworks.go.websocket.MessageCallback;
import com.thoughtworks.go.websocket.MessageEncoding;
import com.thoughtworks.go.websocket.Report;
import com.thoughtworks.go.work.SleepWork;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.thoughtworks.go.util.SystemUtil.getFirstLocalNonLoopbackIpAddress;
import static com.thoughtworks.go.util.SystemUtil.getLocalhostName;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class AgentControllerTest {
    private static final int MAX_WAIT_IN_TEST = 10000;

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();
    @Mock
    private BuildRepositoryRemote loopServer;
    @Mock
    private GoArtifactsManipulator artifactsManipulator;
    @Mock
    private SslInfrastructureService sslInfrastructureService;
    @Mock
    private Work work;
    @Mock
    private AgentRegistry agentRegistry;
    @Mock
    private SubprocessLogger subprocessLogger;
    @Mock
    private SystemEnvironment systemEnvironment;
    @Mock
    private AgentUpgradeService agentUpgradeService;
    @Mock
    private PluginManager pluginManager;
    @Mock
    private PackageAsRepositoryExtension packageAsRepositoryExtension;
    @Mock
    private SCMExtension scmExtension;
    @Mock
    private TaskExtension taskExtension;
    @Mock
    private AgentWebsocketService agentWebsocketService;
    @Mock
    private HttpService httpService;
    @Mock
    private HttpClient httpClient;
    private String agentUuid = "uuid";
    private AgentIdentifier agentIdentifier;
    private AgentController agentController;

    @Before
    public void setUp() throws Exception {
        agentIdentifier = new AgentIdentifier(getLocalhostName(), getFirstLocalNonLoopbackIpAddress(), agentUuid);
    }

    @After
    public void tearDown() {
        GuidService.deleteGuid();
    }

    @Test
    public void shouldSetPluginManagerReference() throws Exception {
        agentController = createAgentController();
        assertThat(PluginManagerReference.reference().getPluginManager(), is(pluginManager));
    }

    @Test
    public void shouldRetrieveWorkFromServerAndDoIt() throws Exception {
        when(loopServer.getWork(any(AgentRuntimeInfo.class))).thenReturn(work);
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        agentController = createAgentController();
        agentController.init();
        agentController.ping();
        agentController.retrieveWork();
        verify(work).doWork(eq(agentIdentifier), eq(loopServer), eq(artifactsManipulator), any(EnvironmentVariableContext.class), any(AgentRuntimeInfo.class), eq(packageAsRepositoryExtension), eq(scmExtension), eq(taskExtension));
        verify(sslInfrastructureService).createSslInfrastructure();
    }

    @Test
    public void shouldRetrieveCookieIfNotPresent() throws Exception {
        agentController = createAgentController();
        agentController.init();

        when(loopServer.getCookie(any(AgentIdentifier.class), eq(agentController.getAgentRuntimeInfo().getLocation()))).thenReturn("cookie");
        when(sslInfrastructureService.isRegistered()).thenReturn(true);
        when(loopServer.getWork(agentController.getAgentRuntimeInfo())).thenReturn(work);
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        agentController.loop();
        verify(work).doWork(eq(agentIdentifier), eq(loopServer), eq(artifactsManipulator), any(EnvironmentVariableContext.class), eq(agentController.getAgentRuntimeInfo()), eq(packageAsRepositoryExtension), eq(scmExtension), eq(taskExtension));
    }

    @Test
    public void shouldNotTellServerWorkIsCompletedWhenThereIsNoWork() throws Exception {
        when(loopServer.getWork(any(AgentRuntimeInfo.class))).thenReturn(work);
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        agentController = createAgentController();
        agentController.init();
        agentController.retrieveWork();
        verify(work).doWork(eq(agentIdentifier), eq(loopServer), eq(artifactsManipulator), any(EnvironmentVariableContext.class), any(AgentRuntimeInfo.class), eq(packageAsRepositoryExtension), eq(scmExtension), eq(taskExtension));
        verify(sslInfrastructureService).createSslInfrastructure();
    }

    @Test
    public void shouldReturnTrueIfCausedBySecurity() throws Exception {
        Exception exception = new Exception(new RuntimeException(new GeneralSecurityException()));
        when(agentRegistry.uuid()).thenReturn(agentUuid);

        agentController = createAgentController();
        agentController.init();
        assertTrue(agentController.isCausedBySecurity(exception));
        verify(sslInfrastructureService).createSslInfrastructure();
    }

    @Test
    public void shouldReturnFalseIfNotCausedBySecurity() throws Exception {
        Exception exception = new Exception(new IOException());
        when(agentRegistry.uuid()).thenReturn(agentUuid);

        agentController = createAgentController();
        agentController.init();
        assertFalse(agentController.isCausedBySecurity(exception));
        verify(sslInfrastructureService).createSslInfrastructure();
    }

    @Test
    public void shouldRegisterSubprocessLoggerAtExit() throws Exception {
        SslInfrastructureService sslInfrastructureService = mock(SslInfrastructureService.class);
        AgentRegistry agentRegistry = mock(AgentRegistry.class);
        agentController = new AgentController(loopServer, artifactsManipulator, sslInfrastructureService, agentRegistry, agentUpgradeService, subprocessLogger, systemEnvironment, pluginManager, packageAsRepositoryExtension, scmExtension, taskExtension, agentWebsocketService, mock(HttpService.class));
        agentController.init();
        verify(subprocessLogger).registerAsExitHook("Following processes were alive at shutdown: ");
    }

    @Test
    public void shouldNotPingIfNotRegisteredYet() throws Exception {
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        when(sslInfrastructureService.isRegistered()).thenReturn(false);

        agentController = createAgentController();
        agentController.init();
        agentController.ping();
        verify(sslInfrastructureService).createSslInfrastructure();
    }

    @Test
    public void shouldPingIfAfterRegistered() throws Exception {
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        when(sslInfrastructureService.isRegistered()).thenReturn(true);
        agentController = createAgentController();
        agentController.init();
        agentController.ping();
        verify(sslInfrastructureService).createSslInfrastructure();
        verify(loopServer).ping(any(AgentRuntimeInfo.class));
    }

    @Test
    public void shouldUpgradeAgentBeforeAgentRegistration() throws Exception {
        agentController = createAgentController();
        InOrder inOrder = inOrder(agentUpgradeService, sslInfrastructureService);
        agentController.loop();
        inOrder.verify(agentUpgradeService).checkForUpgrade();
        inOrder.verify(sslInfrastructureService).registerIfNecessary(agentController.getAgentAutoRegistrationProperties());
    }

    @Test
    public void websocketPing() throws Exception {
        when(systemEnvironment.isWebsocketEnabled()).thenReturn(true);
        when(agentWebsocketService.isRunning()).thenReturn(false);
        when(sslInfrastructureService.isRegistered()).thenReturn(true);

        agentController = createAgentController();
        agentController.init();

        agentController.loop();

        verify(agentUpgradeService).checkForUpgrade();
        verify(sslInfrastructureService).registerIfNecessary(agentController.getAgentAutoRegistrationProperties());
        verify(agentWebsocketService).start();
        verify(agentWebsocketService).sendAndWaitForAck(new Message(Action.ping, MessageEncoding.encodeData(agentController.getAgentRuntimeInfo())));
    }

    @Test
    public void shouldHandleSecurityErrorWhenOpenningWebsocketFailed() throws Exception {
        when(systemEnvironment.isWebsocketEnabled()).thenReturn(true);
        when(sslInfrastructureService.isRegistered()).thenReturn(true);

        when(agentWebsocketService.isRunning()).thenReturn(false);
        doThrow(new GeneralSecurityException()).when(agentWebsocketService).start();

        agentController = createAgentController();
        agentController.init();

        agentController.loop();

        verify(agentUpgradeService).checkForUpgrade();
        verify(sslInfrastructureService).registerIfNecessary(agentController.getAgentAutoRegistrationProperties());
        verify(sslInfrastructureService).invalidateAgentCertificate();
    }

    @Test
    public void processSetCookieAction() throws IOException, InterruptedException {
        agentController = createAgentController();
        agentController.init();

        agentController.process(new Message(Action.setCookie, MessageEncoding.encodeData("cookie")));

        assertThat(agentController.getAgentRuntimeInfo().getCookie(), is("cookie"));
    }

    @Test
    public void processAssignWorkAction() throws IOException, InterruptedException {
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        agentController = createAgentController();
        agentController.init();
        agentController.process(new Message(Action.assignWork, MessageEncoding.encodeWork(new SleepWork("work1", 0))));
        assertThat(agentController.getAgentRuntimeInfo().getRuntimeStatus(), is(AgentRuntimeStatus.Idle));
        verify(agentWebsocketService).sendAndWaitForAck(new Message(Action.ping, MessageEncoding.encodeData(agentController.getAgentRuntimeInfo())));
        verify(artifactsManipulator).setProperty(null, new Property("work1_result", "done"));
    }

    @Test
    public void processBuildCommand() throws Exception {
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        agentController = createAgentController();
        agentController.init();
        BuildSettings build = new BuildSettings();
        build.setBuildId("b001");
        build.setConsoleUrl("http://foo.bar/console");
        build.setArtifactUploadBaseUrl("http://foo.bar/artifacts");
        build.setPropertyBaseUrl("http://foo.bar/properties");
        build.setBuildLocator("build1");
        build.setBuildLocatorForDisplay("build1ForDisplay");
        build.setBuildCommand(BuildCommand.compose(
                BuildCommand.echo("building"),
                BuildCommand.reportCurrentStatus(JobState.Building)));
        agentController.process(new Message(Action.build, MessageEncoding.encodeData(build)));
        assertThat(agentController.getAgentRuntimeInfo().getRuntimeStatus(), is(AgentRuntimeStatus.Idle));

        AgentRuntimeInfo agentRuntimeInfo = cloneAgentRuntimeInfo(agentController.getAgentRuntimeInfo());
        agentRuntimeInfo.busy(new AgentBuildingInfo("build1ForDisplay", "build1"));
        verify(agentWebsocketService).sendAndWaitForAck(new Message(Action.reportCurrentStatus, MessageEncoding.encodeData(new Report(agentRuntimeInfo, "b001", JobState.Building, null))));
        verify(agentWebsocketService).sendAndWaitForAck(new Message(Action.reportCompleted, MessageEncoding.encodeData(new Report(agentRuntimeInfo, "b001", null, JobResult.Passed))));

        ArgumentCaptor<HttpPut> putMethodArg = ArgumentCaptor.forClass(HttpPut.class);
        verify(httpService).execute(putMethodArg.capture());
        assertThat(putMethodArg.getValue().getURI(), is(new URI("http://foo.bar/console")));
        assertThat(IO.toString(putMethodArg.getValue().getEntity().getContent()), containsString("building"));
    }

    private AgentRuntimeInfo cloneAgentRuntimeInfo(AgentRuntimeInfo agentRuntimeInfo) {
        return MessageEncoding.decodeData(MessageEncoding.encodeData(agentRuntimeInfo), AgentRuntimeInfo.class);
    }

    @Test
    public void processCancelBuildCommandBuild() throws IOException, InterruptedException {
        when(agentRegistry.uuid()).thenReturn(agentUuid);

        agentController = createAgentController();
        agentController.init();
        agentController.getAgentRuntimeInfo().setSupportsBuildCommandProtocol(true);
        final BuildSettings build = new BuildSettings();
        build.setBuildId("b001");
        build.setConsoleUrl("http://foo.bar/console");
        build.setArtifactUploadBaseUrl("http://foo.bar/artifacts");
        build.setPropertyBaseUrl("http://foo.bar/properties");
        build.setBuildLocator("build1");
        build.setBuildLocatorForDisplay("build1ForDisplay");
        build.setBuildCommand(BuildCommand.compose(
                BuildSessionBasedTestCase.execSleepScript(MAX_WAIT_IN_TEST / 1000),
                BuildCommand.reportCurrentStatus(JobState.Building)));

        Thread buildingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    agentController.process(new Message(Action.build, MessageEncoding.encodeData(build)));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        buildingThread.start();

        waitForAgentRuntimeState(agentController.getAgentRuntimeInfo(), AgentRuntimeStatus.Building);

        agentController.process(new Message(Action.cancelBuild));
        buildingThread.join(MAX_WAIT_IN_TEST);

        AgentRuntimeInfo agentRuntimeInfo = cloneAgentRuntimeInfo(agentController.getAgentRuntimeInfo());
        agentRuntimeInfo.busy(new AgentBuildingInfo("build1ForDisplay", "build1"));
        agentRuntimeInfo.cancel();

        verify(agentWebsocketService).sendAndWaitForAck(new Message(Action.reportCompleted, MessageEncoding.encodeData(new Report(agentRuntimeInfo, "b001", null, JobResult.Cancelled))));

        assertThat(agentController.getAgentRuntimeInfo().getRuntimeStatus(), is(AgentRuntimeStatus.Idle));
    }

    @Test
    public void processCancelJobAction() throws IOException, InterruptedException {
        agentController = createAgentController();
        agentController.init();
        final SleepWork sleep1secWork = new SleepWork("work1", MAX_WAIT_IN_TEST);

        Thread buildingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    agentController.process(new Message(Action.assignWork, MessageEncoding.encodeWork(sleep1secWork)));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        buildingThread.start();

        waitForAgentRuntimeState(agentController.getAgentRuntimeInfo(), AgentRuntimeStatus.Building);

        agentController.process(new Message(Action.cancelBuild));
        buildingThread.join(MAX_WAIT_IN_TEST);

        assertThat(agentController.getAgentRuntimeInfo().getRuntimeStatus(), is(AgentRuntimeStatus.Idle));
        verify(artifactsManipulator).setProperty(null, new Property("work1_result", "done_canceled"));
    }

    private void waitForAgentRuntimeState(AgentRuntimeInfo runtimeInfo, AgentRuntimeStatus status) throws InterruptedException {
        int elapsed = 0;
        int waitStep = 100;
        while (elapsed <= MAX_WAIT_IN_TEST) {
            if (runtimeInfo.getRuntimeStatus() == status) {
                return;
            }
            Thread.sleep(waitStep);
            elapsed += waitStep;
        }
        throw new RuntimeException("wait for agent status '" + status.name() + "' timeout, current status is '" + runtimeInfo.getRuntimeStatus().name() + "'");
    }

    @Test
    public void processReregisterAction() throws IOException, InterruptedException {
        when(agentRegistry.uuid()).thenReturn(agentUuid);
        agentController = createAgentController();
        agentController.init();
        agentController.process(new Message(Action.reregister));

        verify(sslInfrastructureService).invalidateAgentCertificate();
        verify(agentWebsocketService).stop();
    }

    @Test
    public void shouldCancelPreviousRunningJobIfANewAssignWorkMessageIsReceived() throws IOException, InterruptedException {
        agentController = createAgentController();
        agentController.init();
        final SleepWork work1 = new SleepWork("work1", MAX_WAIT_IN_TEST);
        Thread work1Thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    agentController.process(new Message(Action.assignWork, MessageEncoding.encodeWork(work1)));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        work1Thread.start();
        waitForAgentRuntimeState(agentController.getAgentRuntimeInfo(), AgentRuntimeStatus.Building);
        SleepWork work2 = new SleepWork("work2", 1);
        agentController.process(new Message(Action.assignWork, MessageEncoding.encodeWork(work2)));
        work1Thread.join(MAX_WAIT_IN_TEST);

        verify(artifactsManipulator).setProperty(null, new Property("work1_result", "done_canceled"));
        verify(artifactsManipulator).setProperty(null, new Property("work2_result", "done"));
    }

    @Test
    public void sendWithCallback() throws Exception {
        final AtomicBoolean callbackIsCalled = new AtomicBoolean(false);
        agentController = createAgentController();
        agentController.init();
        final Message message = new Message(Action.reportCurrentStatus);
        assertNull(message.getAckId());
        agentController.sendWithCallback(message, new MessageCallback() {
            @Override
            public void call() {
                callbackIsCalled.set(true);
            }
        });
        assertNotNull(message.getAckId());
        agentController.process(new Message(Action.ack, MessageEncoding.encodeData(message.getAckId())));
        assertTrue(callbackIsCalled.get());
    }

    private AgentController createAgentController() {
        return new AgentController(loopServer, artifactsManipulator, sslInfrastructureService, agentRegistry, agentUpgradeService, subprocessLogger, systemEnvironment, pluginManager, packageAsRepositoryExtension, scmExtension, taskExtension, agentWebsocketService, httpService);
    }
}


text:
package net.twasi.core.services.providers.config.catalog;

public class TwitchCatalog {
    public String hostname;
    public int port;
    public String defaultName;
    public String defaultToken;
    public String defaultUserId;
    public String clientId;
    public String clientSecret;
    public String redirectUri;
    public String scopes;
}


text:
function submitHClustJob(form){

	var independentVariableConceptCode = "";

	independentVariableConceptCode = readConceptVariables("divIndependentVariable");

	var variablesConceptCode = independentVariableConceptCode;

	//----------------------------------
	//Validation
	//----------------------------------
	//This is the independent variable.
	var independentVariableEle = Ext.get("divIndependentVariable");

	//Get the types of nodes from the input box.
	var independentNodeList = createNodeTypeArrayFromDiv(independentVariableEle,"setnodetype")

	//Validate to make sure a concept was dragged in.
	if(independentVariableConceptCode == '')
	{
		Ext.Msg.alert('Missing input', 'Please drag at least one concept into the Heatmap Variable box.');
		return;
	}

	if((independentNodeList[0] == 'valueicon' || independentNodeList[0] == 'hleaficon') && (independentVariableConceptCode.indexOf("|") != -1))
	{
		Ext.Msg.alert('Wrong input', 'For continuous and high dimensional data, you may only drag one node into the input boxes. The heatmap variable input box has multiple nodes.');
		return;
	}

	if(document.getElementById("txtMaxDrawNumber").value == '')
	{
		Ext.Msg.alert('Wrong input', 'Please enter the maximumm number of markers to display into the "Max rows to display" text box.');
		return;
	}

	if(!isNumber(document.getElementById("txtMaxDrawNumber").value))
	{
		Ext.Msg.alert('Wrong input', 'Please enter a valid integer into the "Max rows to display" text box.');
		return;
	}

	if(document.getElementById("txtMaxDrawNumber").value < 1)
	{
		Ext.Msg.alert('Wrong input', 'Please enter a valid integer greater than 0 into the "Max rows to display" text box.');
		return;
	}

	//----------------------------------

	var formParams = {
			independentVariable:		independentVariableConceptCode,
			variablesConceptPaths:		variablesConceptCode,
			jobType:			'RHClust',
			txtMaxDrawNumber:		document.getElementById("txtMaxDrawNumber").value
	};

	//Use a common function to load the High Dimensional Data params.
	loadCommonHighDimFormObjects(formParams,"divIndependentVariable")
	loadCommonHeatmapImageAttributes(formParams);

	if(!validateCommonHeatmapImageAttributes(formParams))
	{
		return false;
	}

	//------------------------------------
	//More Validation
	//------------------------------------
	if(independentNodeList[0] == 'hleaficon' && formParams["divIndependentVariableType"] == "CLINICAL")
	{
		Ext.Msg.alert('Wrong input', 'You dragged a High Dimensional Data node into the heatmap variable box but did not select any filters. Please click the "High Dimensional Data" button and select filters. Apply the filters by clicking "Apply Selections".');
		return;
	}

	//For the time being if the user is trying to run anything but GEX, stop them.
	if(formParams["divIndependentVariableType"] != "MRNA")
	{
		Ext.Msg.alert("Invalid selection", "The heatmap only supports GEX data at this time. Please drag a Gene Expression node into the Heatmap variable and click the 'High Dimensional Data' button.")
		return false;
	}
	//------------------------------------

	submitJob(formParams);
}

/**
 * Register drag and drop.
 * Clear out all gobal variables and reset them to blank.
 */
function loadHclustView(){
	registerHClustDragAndDrop();
	clearHighDimDataSelections('divIndependentVariable');
}

/**
 * Clear the variable selection box
 * Clear all selection stored in global variables
 * Clear the selection display
 * @param divName
 */
function clearGroupHeatmap(divName)
{
	//Clear the drag and drop div.
	var qc = Ext.get(divName);

	for(var i=qc.dom.childNodes.length-1;i>=0;i--)
	{
		var child=qc.dom.childNodes[i];
		qc.dom.removeChild(child);
	}
	clearHighDimDataSelections(divName);
	clearSummaryDisplay(divName);
}

function registerHClustDragAndDrop()
{
	//Set up drag and drop for Dependent and Independent variables on the data association tab.
	//Get the Independent DIV
	var independentDiv = Ext.get("divIndependentVariable");

	dtgI = new Ext.dd.DropTarget(independentDiv,{ddGroup : 'makeQuery'});
	dtgI.notifyDrop =  dropOntoCategorySelection;

}


text:
class Path{
  private:
    Twnode depot;
//    double w1,w2,w3;
    int rid;
    double D;      // duration
    int TWV;    // TW violations
    int CV;     // capacity violations
    bool twv_depot;
    bool cv_depot;
    std::deque<pathNode> path;      // node ids along the path and more

  public:

    Path (const pathNode &d){
         depot = d;
         twv_depot=false;
         cv_depot=false;
	 D= TWV=CV=0;
//         w1=w2=w3=1;
         pathNode dep(d);
         path.push_back(dep);
     };

    ~Path() {};

    int size() {return path.size();};
    double getx(const int i) const { return path[i].getx(); };
    double gety(const int i) const { return path[i].gety(); };
    int getnid(int i) const { return path[i].getnid(); };
 //   int  getoid(int i) const { return path[i].getoid(); };
    int getdpos(const int oid) const;
    int getppos(const int oid) const;
    void remove(int at);
    void removeOrder(int orderid);
    void removePickup(int orderid);
    void removeDelivery(int orderid);
    void swapnodes(int i,int j);
    void swap(int i,int j);
    void move(int fromi,int toj);
    void push_back(pathNode pathstop);
    void insert(pathNode pathstop,int at);
    void setvalues(int at);
    void setDepotValues();
    void dump() ;
    void smalldump();
    bool ispickup(int i) {return path[i].ispickup();}
    bool isdelivery(int i) {return path[i].isdelivery();}
    bool isdepot(int i) {return path[i].isdepot();}
//    bool sameorder(int i,int j){return path[i].sameorder(path[j]);}
    bool feasable() { return TWV == 0 and CV == 0;}
    bool hascv()const { return CV != 0;}
    bool hastwv()const { return TWV != 0;}
    double getcost(double w1,double w2,double w3);// { return   w1*D + w2*TWV + w3*CV; }

};
#endif


text:
package voldemort.store.readonly.fetcher;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;

public class HdfsFile implements Comparable<HdfsFile> {

    public enum FileType {
        METADATA,
        OTHER,
        DATA,
        INDEX
    }

    private final FileStatus fs;
    private final FileType type;

    private FileType getFileType(String fileName) {
        if(fileName.contains(HdfsFetcher.METADATA_FILE_EXTENSION)) {
            return FileType.METADATA;
        } else if(fileName.contains(HdfsFetcher.DATA_FILE_EXTENSION)) {
            return FileType.DATA;
        } else if(fileName.contains(HdfsFetcher.INDEX_FILE_EXTENSION)) {
            return FileType.INDEX;
        } else {
            return FileType.OTHER;
        }
    }

    public HdfsFile(FileStatus fs) {
        this.fs = fs;
        this.type = getFileType(fs.getPath().getName());
    }

    public Path getPath() {
        return fs.getPath();
    }

    public FileType getFileType() {
        return type;
    }

    public long getSize() {
        if(fs.isDir())
            return -1;
        return fs.getLen();
    }

    @Override
    public boolean equals(Object other) {
        if(this == other) {
            return true;
        }
        if(other instanceof HdfsFile) {
            return ((HdfsFile) other).fs.equals(this.fs);
        }
        return false;
    }
    @Override
    public int hashCode() {
        return fs.hashCode();
    }

    @Override
    public int compareTo(HdfsFile other) {
        FileStatus fs1 = this.fs;
        FileStatus fs2 = other.fs;

        // This is probably dead code, no directories should be present.
        // directories before files
        if(fs1.isDir())
            return fs2.isDir() ? 0 : -1;
        if(fs2.isDir())
            return fs1.isDir() ? 0 : 1;

        // if both are of same type, sort lexicographically
        if(this.type == other.type) {
            String f1 = fs1.getPath().getName(), f2 = fs2.getPath().getName();
            return f1.compareToIgnoreCase(f2);
        }

        // Move the index files to the end, this is a heuristic as they might be
        // available in the page cache
        if(this.type == FileType.INDEX) {
            return 1;
        } else {
            return -1;
        }
    }

    public String getDiskFileName() {
        String fileName = getPath().getName();
        // DiskFile is uncompressed
        if(fileName.endsWith(HdfsFetcher.GZIP_FILE_EXTENSION)) {
            fileName = fileName.substring(0,
                                      fileName.length() - HdfsFetcher.GZIP_FILE_EXTENSION.length());
        }
        return fileName;
    }

    public boolean isCompressed() {
        return getPath().getName().endsWith(HdfsFetcher.GZIP_FILE_EXTENSION);
    }

    @Override
    public String toString() {
        return getPath().toString();
    }

}


text:
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkAvailability = exports.getSnippet = void 0;
const axios_1 = require("axios");
const config_1 = require("@bldr/config");
function getSnippet(youtubeId) {
    return __awaiter(this, void 0, void 0, function* () {
        const snippet = yield axios_1.default.get('https://www.googleapis.com/youtube/v3/videos', {
            params: {
                part: 'snippet',
                id: youtubeId,
                key: config_1.default.youtube.apiKey
            }
        });
        if (snippet.data.items.length > 0) {
            return snippet.data.items[0].snippet;
        }
    });
}
exports.getSnippet = getSnippet;
function checkAvailability(youtubeId) {
    return __awaiter(this, void 0, void 0, function* () {
        const snippet = yield getSnippet(youtubeId);
        if (snippet != null)
            return true;
        return false;
    });
}
exports.checkAvailability = checkAvailability;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="emailTxt">e-mail</string>
    <string name="showPasswordTxt">Show password</string>
    <string name="registerTxt">Register</string>
</resources>


text:
package com.google.api.tools.framework.aspects;

import com.google.api.tools.framework.model.DiagReporter;
import com.google.api.tools.framework.model.DiagReporter.LocationContext;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * Manages a collection of {@link Feature} objects that together define the feature handling for a
 * particular service config element.
 */
public class Features {
  private static final String FEATURE_DISABLE_CHARACTER_PREFIX = "~";
  private final Map<String, Feature> featuresByName;

  public Features(Feature... features) {
    ImmutableMap.Builder<String, Feature> featuresByNameBuilder = ImmutableMap.builder();
    for (Feature feature : features) {
      feature.addSelfAndChildren(featuresByNameBuilder);
    }
    featuresByName = featuresByNameBuilder.build();
  }

  public static String getFeatureNameStringToDisable(String featureName) {
    return FEATURE_DISABLE_CHARACTER_PREFIX + featureName;
  }

  /**
   * Evaluates a collection of feature strings provided by the service owner, taking into account
   * the feature definitions and the current config version, and returns the canonicalized set of
   * enabled features. Any issues are reported to the given DiagCollector.
   *
   * @param input a collection of strings that are either feature names (indicating that the named
   *     feature should be enabled), or a '~' followed by a feature name (indicating that the named
   *     feature should be disabled).
   */
  public Set<String> evaluate(
      Collection<String> input,
      int configVersion,
      DiagReporter diagReporter,
      LocationContext location) {
    Set<String> enabled = new TreeSet<>();

    // Accumulate features that are enabled by default.
    for (Feature feature : featuresByName.values()) {
      if (feature.isDefaultIn(configVersion)) {
        feature.accumulate(enabled, false /* remove */, configVersion, diagReporter, location);
      }
    }

    // Accumulate features that are explicitly specified.
    for (String featureString : input) {
      boolean remove = featureString.startsWith("~");
      String featureName = remove ? featureString.substring(1) : featureString;
      Feature feature = featuresByName.get(featureName);
      if (feature == null) {
        diagReporter.reportError(
            location,
            "No such feature %s supported for this element. "
                + "Supported features for this config version are: [%s].",
            featureName,
            Joiner.on(", ").join(getSupportedFeatureNames(configVersion)));
      } else {
        feature.accumulate(enabled, remove, configVersion, diagReporter, location);
      }
    }
    return enabled;
  }

  private Set<String> getSupportedFeatureNames(int configVersion) {
    Set<String> supportedFeatures = new TreeSet<>();
    for (Feature feature : featuresByName.values()) {
      if (feature.isSupportedIn(configVersion)) {
        supportedFeatures.add(feature.getName());
      }
    }
    return supportedFeatures;
  }
}


text:
package net.q3aiml.config.scheduler;

import javax.annotation.Nonnull;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * Polling on a fixed schedule.
 */
public class FixedDelayPollingScheduler implements PollingScheduler {
    protected final long delay;
    protected final TimeUnit units;
    protected final ScheduledExecutorService executor = createExecutor();

    /**
     * @param delay how long to wait between polls in {@code delayUnits}
     */
    public FixedDelayPollingScheduler(long delay, TimeUnit delayUnits) {
        this.delay = delay;
        this.units = delayUnits;
    }

    protected ScheduledExecutorService createExecutor() {
        return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(@Nonnull Runnable r) {
                Thread thread = new Thread(r, "configuration poller with fixed delay");
                thread.setDaemon(true);
                return thread;
            }
        });
    }

    @Override
    public void start(Runnable doPolling) {
        // not using separate initial delay as PollingDynamicConfig already does the first polling during creation
        executor.scheduleWithFixedDelay(doPolling, delay, delay, units);
    }

    public void stop() {
        executor.shutdown();
    }

    public boolean isRunning() {
        return !executor.isShutdown();
    }

    @Override
    public String toString() {
        return "FixedPollingScheduler{" +
                "delay=" + delay +
                ", units=" + units +
                '}';
    }
}