text:
function select_image(element){
	element = $(element);
    element.closest('ul').children('li:first').removeClass("selected");
    element.closest('li').addClass('selected');
}

function select_thumb(element) {
	element = $(element);
  console.log(element.attr('href'));
  size = element.attr('href').split('_')[1];
  element.closest('li').removeClass("selected")
  img = element.closest('li').find("img");
	src = img.attr("src").replace('thumb', size);
	curbly_insert_image(src, img.attr('alt') );
}

function upload_image_callback(url, alt_text, photo_id){
  $("#image_uploaded_data").val("");
  jQuery(function($){
     $.get('/tinymce_assets');
  });
}

function curbly_insert_image(url, alt_text){
	var formObj = formElement();
	formObj.src.value = url;
	formObj.alt.value = alt_text;
	mcTabs.displayTab('general_tab','general_panel');
	ImageDialog.showPreviewImage(url);
	}
function formElement() {
	return document.forms[1];
	}
function ts_onload(){
	$('#dynamic_images_list').replaceWith("
Uploading...

");
    mcTabs.displayTab('dynamic_select_tab','dynamic_select_panel');

	var iframe1=ts_ce('iframe','html_editor_image_upload_frame');
	iframe1.setAttribute('src','about:blank');
	iframe1.style.border="0px none";
	iframe1.style.position="absolute";
	iframe1.style.width="1px";
	iframe1.style.height="1px";
	iframe1.style.visibility="hidden";
	iframe1.setAttribute('id','html_editor_image_upload_frame');
	$('#image-upload').append(iframe1);
	$("#image_upload_form").attr("action", ts_upload_image_path());
}

function ts_upload_image_path() {
  return '/tinymce_assets/create';
}
function ts_ce(tag,name){
  if (name && window.ActiveXObject){
    element = document.createElement('<'+tag+' name="'+name+'">');
  }else{
    element = document.createElement(tag);
    element.setAttribute('name',name);
  }
  return element;
	}

	var ImageDialog = {
		preInit : function() {
			var url;

			tinyMCEPopup.requireLangPack();

			if (url = tinyMCEPopup.getParam("external_image_list_url"))
				document.write('');
		},

		init : function(ed) {
			var f = formElement(), nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode();

			tinyMCEPopup.resizeToInnerSize();
			this.fillClassList('class_list');
			this.fillFileList('src_list', 'tinyMCEImageList');
			this.fillFileList('over_list', 'tinyMCEImageList');
			this.fillFileList('out_list', 'tinyMCEImageList');

			if (n.nodeName == 'IMG') {
				nl.src.value = dom.getAttrib(n, 'src');
				nl.width.value = dom.getAttrib(n, 'width');
				nl.height.value = dom.getAttrib(n, 'height');
				nl.alt.value = dom.getAttrib(n, 'alt');
				nl.title.value = dom.getAttrib(n, 'title');
				nl.vspace.value = this.getAttrib(n, 'vspace');
				nl.hspace.value = this.getAttrib(n, 'hspace');
				nl.border.value = this.getAttrib(n, 'border');
				selectByValue(f, 'align', this.getAttrib(n, 'align'));
				selectByValue(f, 'class_list', dom.getAttrib(n, 'class'));
				nl.style.value = dom.getAttrib(n, 'style');
				nl.id.value = dom.getAttrib(n, 'id');
				nl.dir.value = dom.getAttrib(n, 'dir');
				nl.lang.value = dom.getAttrib(n, 'lang');
				nl.usemap.value = dom.getAttrib(n, 'usemap');
				nl.longdesc.value = dom.getAttrib(n, 'longdesc');
				nl.insert.value = ed.getLang('update');

				if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover')))
					nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1');

				if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout')))
					nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1');

				if (ed.settings.inline_styles) {
					// Move attribs to styles
					if (dom.getAttrib(n, 'align'))
						this.updateStyle('align');

					if (dom.getAttrib(n, 'hspace'))
						this.updateStyle('hspace');

					if (dom.getAttrib(n, 'border'))
						this.updateStyle('border');

					if (dom.getAttrib(n, 'vspace'))
						this.updateStyle('vspace');
				}
			}

			// Setup browse button
			document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image');
			if (isVisible('srcbrowser'))
				document.getElementById('src').style.width = '260px';

			// Setup browse button
			// document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image');
			// if (isVisible('overbrowser'))
			// 	document.getElementById('onmouseoversrc').style.width = '260px';
			//
			// // Setup browse button
			// document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image');
			// if (isVisible('outbrowser'))
			// 	document.getElementById('onmouseoutsrc').style.width = '260px';

			// If option enabled default contrain proportions to checked
			if (ed.getParam("advimage_constrain_proportions", true))
				f.constrain.checked = true;

			// Check swap image if valid data
			// if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value)
			// 	this.setSwapImage(true);
			// else
			// 	this.setSwapImage(false);

			this.changeAppearance();
			this.showPreviewImage(nl.src.value, 1);
		},

		insert : function(file, title) {
			var ed = tinyMCEPopup.editor, t = this, f = formElement();

			if (f.src.value === '') {
				if (ed.selection.getNode().nodeName == 'IMG') {
					ed.dom.remove(ed.selection.getNode());
					ed.execCommand('mceRepaint');
				}

				tinyMCEPopup.close();
				return;
			}

			if (tinyMCEPopup.getParam("accessibility_warnings", 1)) {
				if (!f.alt.value) {
					tinyMCEPopup.editor.windowManager.confirm(tinyMCEPopup.getLang('advimage_dlg.missing_alt'), function(s) {
						if (s)
							t.insertAndClose();
					});

					return;
				}
			}

			t.insertAndClose();
		},

		insertAndClose : function() {
			var ed = tinyMCEPopup.editor, f = formElement(), nl = f.elements, v, args = {}, el;

			// Fixes crash in Safari
			if (tinymce.isWebKit)
				ed.getWin().focus();

			if (!ed.settings.inline_styles) {
				args = {
					vspace : nl.vspace.value,
					hspace : nl.hspace.value,
					border : nl.border.value,
					align : getSelectValue(f, 'align')
				};
			} else {
				// Remove deprecated values
				args = {
					vspace : '',
					hspace : '',
					border : '',
					align : ''
				};
			}

			tinymce.extend(args, {
				src : nl.src.value,
				width : nl.width.value,
				height : nl.height.value,
				alt : nl.alt.value,
				title : nl.title.value,
				'class' : getSelectValue(f, 'class_list'),
				style : nl.style.value
				// id : nl.id.value,
				// dir : nl.dir.value,
				// lang : nl.lang.value,
				// usemap : nl.usemap.value,
				// longdesc : nl.longdesc.value
			});

			// args.onmouseover = args.onmouseout = '';

			// if (f.onmousemovecheck.checked) {
			// 	if (nl.onmouseoversrc.value)
			// 		args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';";
			//
			// 	if (nl.onmouseoutsrc.value)
			// 		args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';";
			// }

			el = ed.selection.getNode();

			if (el && el.nodeName == 'IMG') {
				ed.dom.setAttribs(el, args);
			} else {
				ed.execCommand('mceInsertContent', false, '', {skip_undo : 1});
				ed.dom.setAttribs('__mce_tmp', args);
				ed.dom.setAttrib('__mce_tmp', 'id', '');
				ed.undoManager.add();
			}

			tinyMCEPopup.close();
		},

		getAttrib : function(e, at) {
			var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;

			if (ed.settings.inline_styles) {
				switch (at) {
					case 'align':
						if (v = dom.getStyle(e, 'float'))
							return v;

						if (v = dom.getStyle(e, 'vertical-align'))
							return v;

						break;

					case 'hspace':
						v = dom.getStyle(e, 'margin-left')
						v2 = dom.getStyle(e, 'margin-right');

						if (v && v == v2)
							return parseInt(v.replace(/[^0-9]/g, ''));

						break;

					case 'vspace':
						v = dom.getStyle(e, 'margin-top')
						v2 = dom.getStyle(e, 'margin-bottom');
						if (v && v == v2)
							return parseInt(v.replace(/[^0-9]/g, ''));

						break;

					case 'border':
						v = 0;

						tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
							sv = dom.getStyle(e, 'border-' + sv + '-width');

							// False or not the same as prev
							if (!sv || (sv != v && v !== 0)) {
								v = 0;
								return false;
							}

							if (sv)
								v = sv;
						});

						if (v)
							return parseInt(v.replace(/[^0-9]/g, ''));

						break;
				}
			}

			if (v = dom.getAttrib(e, at))
				return v;

			return '';
		},

		setSwapImage : function(st) {
			var f = formElement();

			f.onmousemovecheck.checked = st;
			setBrowserDisabled('overbrowser', !st);
			setBrowserDisabled('outbrowser', !st);

			if (f.over_list)
				f.over_list.disabled = !st;

			if (f.out_list)
				f.out_list.disabled = !st;

			f.onmouseoversrc.disabled = !st;
			f.onmouseoutsrc.disabled  = !st;
		},

		fillClassList : function(id) {
			var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;

			if (v = tinyMCEPopup.getParam('theme_advanced_styles')) {
				cl = [];

				tinymce.each(v.split(';'), function(v) {
					var p = v.split('=');

					cl.push({'title' : p[0], 'class' : p[1]});
				});
			} else
				cl = tinyMCEPopup.editor.dom.getClasses();

			if (cl.length > 0) {
				lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), '');

				tinymce.each(cl, function(o) {
					lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']);
				});
			} else
				dom.remove(dom.getParent(id, 'tr'));
		},

		fillFileList : function(id, l) {
			var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;

			l = window[l];

			if (l && l.length > 0) {
				lst.options[lst.options.length] = new Option('', '');

				tinymce.each(l, function(o) {
					lst.options[lst.options.length] = new Option(o[0], o[1]);
				});
			} else
				dom.remove(dom.getParent(id, 'tr'));
		},

		resetImageData : function() {
			var f = formElement();

			f.elements.width.value = f.elements.height.value = '';
		},

		updateImageData : function(img, st) {
			var f = formElement();

			if (!st) {
				f.elements.width.value = img.width;
				f.elements.height.value = img.height;
			}

			this.preloadImg = img;
		},

		changeAppearance : function() {
			var ed = tinyMCEPopup.editor, f = formElement(), img = document.getElementById('alignSampleImg');

			if (img) {
				if (ed.getParam('inline_styles')) {
					ed.dom.setAttrib(img, 'style', f.style.value);
				} else {
					img.align = f.align.value;
					img.border = f.border.value;
					img.hspace = f.hspace.value;
					img.vspace = f.vspace.value;
				}
			}
		},

		changeHeight : function() {
			var f = formElement(), tp, t = this;

			if (!f.constrain.checked || !t.preloadImg) {
				return;
			}

			if (f.width.value == "" || f.height.value == "")
				return;

			tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height;
			f.height.value = tp.toFixed(0);
		},

		changeWidth : function() {
			var f = formElement(), tp, t = this;

			if (!f.constrain.checked || !t.preloadImg) {
				return;
			}

			if (f.width.value == "" || f.height.value == "")
				return;

			tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width;
			f.width.value = tp.toFixed(0);
		},

		updateStyle : function(ty) {
			var dom = tinyMCEPopup.dom, st, v, f = formElement(), img = dom.create('img', {style : dom.get('style').value});

			if (tinyMCEPopup.editor.settings.inline_styles) {
				// Handle align
				if (ty == 'align') {
					dom.setStyle(img, 'float', '');
					dom.setStyle(img, 'vertical-align', '');

					v = getSelectValue(f, 'align');
					if (v) {
						if (v == 'left' || v == 'right')
							dom.setStyle(img, 'float', v);
						else
							img.style.verticalAlign = v;
					}
				}

				// Handle border
				if (ty == 'border') {
					dom.setStyle(img, 'border', '');

					v = f.border.value;
					if (v || v == '0') {
						if (v == '0')
							img.style.border = '';
						else
							img.style.border = v + 'px solid black';
					}
				}

				// Handle hspace
				if (ty == 'hspace') {
					dom.setStyle(img, 'marginLeft', '');
					dom.setStyle(img, 'marginRight', '');

					v = f.hspace.value;
					if (v) {
						img.style.marginLeft = v + 'px';
						img.style.marginRight = v + 'px';
					}
				}

				// Handle vspace
				if (ty == 'vspace') {
					dom.setStyle(img, 'marginTop', '');
					dom.setStyle(img, 'marginBottom', '');

					v = f.vspace.value;
					if (v) {
						img.style.marginTop = v + 'px';
						img.style.marginBottom = v + 'px';
					}
				}

				// Merge
				dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText));
			}
		},

		changeMouseMove : function() {
		},

		showPreviewImage : function(u, st) {
			if (!u) {
				tinyMCEPopup.dom.setHTML('prev', '');
				return;
			}

			if (!st && tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true))
				this.resetImageData();

			u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u);

			if (!st)
				tinyMCEPopup.dom.setHTML('prev', '');
			else
				tinyMCEPopup.dom.setHTML('prev', '');
		}
	};

	ImageDialog.preInit();
	tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);


text:
{% extends "base.html" %}
{% load custom_filters %}

{% block title %}Study List{% endblock title%}

{% block scripts %}
{% include "sortable_table_script.html" %}

{% endblock scripts %}

{% block header %}Study List{% endblock header %}

{% block content %}

  Description
  Strain
  Start Date

 <tdata>
{% for study in study_list %}

  {{study.description}}
  {% for strain in study.strain.all %}<a href="{{ strain.get_absolute_url }}"{% endfor %}
  {{study.start_date}}

{% endfor %}
 </tdata>

To add a new study click here.

{% endblock content %}

redpajama_set_name: RedPajamaGithub


text:
import { autoinject } from 'aurelia-framework';
import { UserRestService } from './../../services/rest/user.service';
import { UserModel } from './../../models/user.model';

@autoinject
export class UsersViewModel {
  public heading: string = 'Github Users';
  public users: UserModel[] = [];

  constructor(
    private userRestService: UserRestService
  ) { }

  public async activate(): Promise<void> {
    this.users = await this.userRestService.getUsers();
  }
}


text:
package net.oneandone.troilus.userdefinieddatatypes;

import net.oneandone.troilus.Schema;

public interface ClassifierType  {

    public static final String TYPE = "type";

    public static final String CREATE_STMT = Schema.load("com/unitedinternet/troilus/example/classifier.ddl");
}


text:
package org.unitime.timetable.gwt.client.instructor;

import org.unitime.timetable.gwt.client.page.UniTimeNotifications;
import org.unitime.timetable.gwt.client.rooms.RoomSharingWidget;
import org.unitime.timetable.gwt.command.client.GwtRpcRequest;
import org.unitime.timetable.gwt.command.client.GwtRpcService;
import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync;
import org.unitime.timetable.gwt.shared.RoomInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingModel;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingOption;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * @author Tomas Muller
 */
public class InstructorAvailabilityWidget extends RoomSharingWidget {
	private static GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class);
	private Hidden iPattern = null;

	public InstructorAvailabilityWidget() {
		super(false);
	}

	public void insert(final RootPanel panel) {
		RPC.execute(InstructorAvailabilityRequest.load(null), new AsyncCallback<InstructorAvailabilityModel>() {
			@Override
			public void onFailure(Throwable caught) {
				UniTimeNotifications.error(caught);
			}

			@Override
			public void onSuccess(final InstructorAvailabilityModel model) {
				if (panel.getElement().getFirstChildElement() != null) {
					iPattern = Hidden.wrap(panel.getElement().getFirstChildElement());
					model.setPattern(iPattern.getValue());

					addValueChangeHandler(new ValueChangeHandler<RoomInterface.RoomSharingModel>() {
						@Override
						public void onValueChange(ValueChangeEvent<RoomSharingModel> event) {
							iPattern.setValue(event.getValue().toString());
						}
					});
					iEditable = true;
				} else {
					String pattern = panel.getElement().getInnerText().trim();
					panel.getElement().setInnerText(null);
					model.setPattern(pattern);
					iEditable = false;
				}

				setModel(model);

				panel.add(InstructorAvailabilityWidget.this);
				panel.setVisible(true);
			}
		});
	}

	public static class InstructorAvailabilityRequest implements GwtRpcRequest<InstructorAvailabilityModel> {
		private String iInstructorId;

		public InstructorAvailabilityRequest() {}

		public String getInstructorId() { return iInstructorId; }
		public void setInstructorId(String instructorId) { iInstructorId = instructorId; }

		public static InstructorAvailabilityRequest load(String instructorId) {
			InstructorAvailabilityRequest request = new InstructorAvailabilityRequest();
			request.setInstructorId(instructorId);
			return request;
		}

		@Override
		public String toString() {
			return iInstructorId == null ? "NULL" : iInstructorId;
		}
	};

	public static class InstructorAvailabilityModel extends RoomInterface.RoomSharingModel {
		public char id2char(Long id) {
			if (id == null) return '2';
			switch (id.intValue()) {
			case -1: return 'R';
			case -2: return '0';
			case -3: return '1';
			case -4: return '2';
			case -5: return '3';
			case -6: return '4';
			case -7: return 'P';
			case -8: return 'N';
			default: return '2';
			}
		}

		public Long char2id(char ch) {
			switch (ch) {
			case 'R': return -1l;
			case '0': return -2l;
			case '1': return -3l;
			case '2': return -4l;
			case '3': return -5l;
			case '4': return -6l;
			case 'P': return -7l;
			case 'N': return -8l;
			default: return -4l;
			}
		}

		public String getPattern() {
			String pattern = "";
			for (int d = 0; d < 7; d++)
				for (int s = 0; s < 288; s++) {
					RoomSharingOption option = getOption(d, s);
					pattern += id2char(option == null ? null : option.getId());
				}
			return pattern;
		}
		public void setPattern(String pattern) {
			if (pattern.length() <= 336) {
				boolean req = pattern.indexOf('R') >= 0;
				for (int d = 0; d < 7; d++)
					for (int s = 0; s < 288; s++) {
						char ch = '2';
						try {
							ch = pattern.charAt(48 * d + s / 6);
						} catch (IndexOutOfBoundsException e) {}
						setOption(d, s, char2id(req ? ch == 'R' ? '2' : 'P' : ch));
					}
			} else {
				for (int d = 0; d < 7; d++)
					for (int s = 0; s < 288; s++) {
						char ch = '2';
						try {
							ch = pattern.charAt(288 * d + s);
						} catch (IndexOutOfBoundsException e) {}
						setOption(d, s, char2id(ch));
					}
			}
		}

		@Override
		public String toString() {
			return getPattern();
		}
	}
}


text:
"use strict";

var subscriptionSchema = module.exports = {
    "id": { type: String, required: true },
    "userToken": { type: String },
    "collection": { type: String, required: true, default: 'timeline' },     // locations, timeline
    "callbackUrl": { type: String }
};


text:
package obligatorioalgoritmos;

public interface ILista {
    public boolean esVacia();
    public void agregarInicio(Object h);
    public void borrarInicio();
    public void agregarFinal(Object h);
    public void borrarFin();
    public void vaciar();
    public void mostrar();
    public void borrarObjeto(Object h);

    public void agregarOrd(Object h);
    public Object buscarObjeto(String string);
}


text:
package org.ec.jap.backend.pago;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import org.ec.jap.backend.pagina.Bean;
import org.ec.jap.backend.utilitario.Mensaje;
import org.ec.jap.bo.saap.DestinoBO;
import org.ec.jap.entiti.saap.Destino;
import org.ec.jap.enumerations.ValorSiNo;

@ManagedBean
@ViewScoped
public class ReporteCajaDetalleBean extends Bean {

	/**
	 *
	 */

	@EJB
	DestinoBO destinoBO;

	private Destino destino;

	public ReporteCajaDetalleBean() {
		super();
	}
	@PostConstruct
	@Override
	public void init() {
		try {
			super.init();
			search(null);
		} catch (Exception e) {
			e.printStackTrace();
			displayMessage(e.getMessage(), Mensaje.SEVERITY_ERROR);
		}

	}

	@Override
	public void search(ActionEvent event) {
		try {

			if ("INS".equals(getAccion())) {
				destino = new Destino();
			} else {
				destino = destinoBO.findByPk(getParam1Integer());
			}
		} catch (Exception e) {
			e.printStackTrace();
			displayMessage(e.getMessage(), Mensaje.SEVERITY_ERROR);
		}
	}

	@Override
	public String guardar() {
		try {
			if ("INS".equals(getAccion())) {
				destinoBO.save(getUsuarioCurrent(), destino);
				setParam1(destino.getIdDestino());
				setAccion("UPD");
			} else {
				destinoBO.update(getUsuarioCurrent(), destino);
			}
			displayMessage(Mensaje.saveMessaje, Mensaje.SEVERITY_INFO);
			return getPage().getOutcome();
		} catch (Exception e) {
			e.printStackTrace();
			displayMessage(e.getMessage(), Mensaje.SEVERITY_ERROR);
			return getPage().getOutcome();
		}
	}

	@Override
	public String delete() {
		try {
			destinoBO.delete(getUsuarioCurrent(), destino);
			displayMessage(Mensaje.deleteMessaje, Mensaje.SEVERITY_INFO);
			return getLastPage().getOutcome() + "?faces-redirect=true";
		} catch (Exception e) {
			displayMessage(Mensaje.errorMessaje, Mensaje.SEVERITY_FATAL);
			return getPage().getOutcome();
		}
	}

	public Destino getDestino() {
		return destino;
	}
	public void setDestino(Destino destino) {
		this.destino = destino;
	}
	public List<SelectItem> getActivos() {
		try {
			return getSelectItems(ValorSiNo.values());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}


text:
Whendle.Timezone_Locator = Class.create({

	initialize: function(ajax, tzloader) {
		this.ajax = ajax || new Whendle.AjaxService();
		this.loader = tzloader || new Whendle.TzLoader(this.ajax);
	},

	lookup: function(latitude, longitude, on_complete, on_error) {
		on_complete = on_complete || Prototype.emptyFunction;
		on_error = on_error || Prototype.emptyFunction;

		this.ajax.load(
			this._make_lookup_url(latitude, longitude),
			this._on_lookup_result.bind(this, on_complete, on_error),
			this._on_lookup_error.bind(this, on_error)
		);
	},

	_make_lookup_url: function(latitude, longitude) {
		return GeoNames.timezone_url(latitude, longitude);
	},

	_on_lookup_result: function(on_complete, on_error, response) {
		if (this.is_service_error(response)) {
			this.on_service_error(response, on_error);
		}
		else {
			this.load(response.timezoneId, on_complete, on_error);
		}
	},

	is_service_error: function(response) {
		return Object.isUndefined(response.timezoneId);
	},

	on_service_error: function(response, on_error) {
		var status = response.status;
		var error = { code: 0 };
		if (Object.isUndefined(status)) {
			error.message = 'Unknown service error';
		}
		else {
			error.code = status.value;
			error.message = status.message;
		}

		on_error(error);
	},

	_on_lookup_error: function(on_error, error) {
		on_error(error);
	},

	load: function(name, on_complete, on_error) {
		on_complete = on_complete || Prototype.emptyFunction;
		on_error = on_error || Prototype.emptyFunction;

		this.load_from_disk(name, on_complete, on_error);
	},

	load_from_disk: function(name, on_complete, on_error) {
		this.loader.load(
			name,
			this.on_load_result.bind(this, name, on_complete, on_error),
			this.on_load_error.bind(this, name, on_error)
		);
	},

	on_load_result: function(name, on_complete, on_error, text) {
		var zone_reader = this.new_reader(text);
		var rules = [];
		var zones = [];

		var zone = zone_reader.zone(name);
		if (zone == null) {
			var link = zone_reader.link(name);
			if (link != null) {
				zone = zone_reader.zone(link.ZONE);
			}
		}

		while (zone != null) {
			zones.push(zone);

			var rule_reader = this.new_reader(text);
			var rule = rule_reader.next_rule(zone.RULES);

			while (rule != null) {
				var contains = rules.any(function(r) {
					return r.toString() == rule.toString();
				});

				if (!contains) {
					rules.push(rule);
				}

				rule = rule_reader.next_rule(zone.RULES);
			}

			zone = zone_reader.next_zone(zone.NAME);
		}

		on_complete(new Whendle.Timezone(name, zones, rules));
	},

	new_reader: function(text) {
		return new Whendle.TzReader(text);
	},

	on_load_error: function(name, on_error, error) {
		on_error(error);
	}
});


text:
username: `admin`

password: `changeme`


text:
package org.zstack.header.storage.snapshot.group;

import org.zstack.header.storage.snapshot.SnapshotBackendOperation;

/**
 * Created by MaJin on 2019/7/9.
 */
public interface VolumeSnapshotGroupMessage {
    String getGroupUuid();
    SnapshotBackendOperation getBackendOperation();
}


text:
#ifndef _CSTR_H_
#define _CSTR_H_

/* A general-purpose string "class" for C */

#if     !defined(P)
#ifdef  __STDC__
#define P(x)    x
#else
#define P(x)    ()
#endif
#endif

#define _CDECL
#define _TYPE(a) a _CDECL

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* Arguments to allocator methods ordered this way for compatibility */
typedef struct cstr_alloc_st {
  void * (_CDECL * alloc)(int n, void * heap);
  void (_CDECL * free)(void * p, void * heap);
  void * heap;
} cstr_allocator;

typedef struct cstr_st {
  char * data;	/* Okay to access data and length fields directly */
  int length;
  int cap;
  int ref;	/* Simple reference counter */
  cstr_allocator * allocator;
} cstr;

_TYPE( void ) cstr_set_allocator P((cstr_allocator * alloc));

_TYPE( cstr * ) cstr_new P((void));
_TYPE( cstr * ) cstr_new_alloc P((cstr_allocator * alloc));
_TYPE( cstr * ) cstr_dup P((const cstr * str));
_TYPE( cstr * ) cstr_dup_alloc P((const cstr * str, cstr_allocator * alloc));
_TYPE( cstr * ) cstr_create P((const char * s));
_TYPE( cstr * ) cstr_createn P((const char * s, int len));

_TYPE( void ) cstr_free P((cstr * str));
_TYPE( void ) cstr_clear_free P((cstr * str));
_TYPE( void ) cstr_use P((cstr * str));
_TYPE( void ) cstr_empty P((cstr * str));
_TYPE( int ) cstr_copy P((cstr * dst, const cstr * src));
_TYPE( int ) cstr_set P((cstr * str, const char * s));
_TYPE( int ) cstr_setn P((cstr * str, const char * s, int len));
_TYPE( int ) cstr_set_length P((cstr * str, int len));
_TYPE( int ) cstr_append P((cstr * str, const char * s));
_TYPE( int ) cstr_appendn P((cstr * str, const char * s, int len));
_TYPE( int ) cstr_append_str P((cstr * dst, const cstr * src));

#ifdef __cplusplus
}
#endif // __cplusplus

#endif // _CSTR_H_


text:
<!DOCTYPE html>

    <title>
      Competitions
    </title>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css?family=Raleway:400,900" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="../css/component.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

        arrow_back

Competitions

        

              Home

              About

              Competitions

              Technocruise

              TOSC

              Sponsors

              Contact Us

              Home

              About

              Competitions

              Technocruise

              TOSC

              Sponsors

              Contact Us

                Technical

                WHERE SKILLS
AMPLIFY

                Social

                WHERE CREATIVITY
EMERGES

                Entrepreneurial

                WHERE IDEAS
FLOURISH

                International

                WHERE NATIONS
UNITE


text:
function createCell () {
    return {
        state: 'unknown'
    };
}

function createArray () {
    return [];
}

function Hanjie (data) {
    var rowCount = data.rows.length;
    var colCount = data.cols.length;
    var celCount = rowCount * colCount;

    var cels = _.times(celCount, createCell);
    var rows = _.times(rowCount, createArray);
    var cols = _.times(colCount, createArray);

    _.each(cels, function (cell, index) {

        var rowIndex = index % colCount;
        var colIndex = index % rowCount;

        rows[rowIndex].push(cell);
        cols[colIndex].push(cell);

    });

    this.rowsData = data.rows;
    this.columnsData = data.cols;

    this.rows = rows;
    this.columns = cols;
    this.cells = cels;
}

module.exports = Hanjie;


text:
module Issues
  module Github
    class Connection
      include Singleton

      def connection
        @conn ||= Faraday.new(:url => "https://api.github.com")
        @conn.basic_auth(Github.username, Github.password) unless Github.password.nil?
        @conn
      end
    end
  end
end


text:
using BDDoc.Core;
using System;
using System.Diagnostics.CodeAnalysis;

namespace BDDoc.IntegrationTest
{
    [ExcludeFromCodeCoverage]
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class CustomScenarioAttribute : BDDocAttribute, IScenarioAttrib
    {
        //Constructors

        public CustomScenarioAttribute(string text)
            : base(text, 1) { }
    }
}


text:
#import <iCalendar/ICSByDayValue.h>

@interface ICSByDayValue (ICSWriter)
- (long long)compare:(id)arg1;
- (void)_ICSStringWithOptions:(unsigned long long)arg1 appendingToString:(id)arg2;
@end


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Best City Guide</title>
	<link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="css/base.css">
	<link rel="stylesheet" href="css/flexbox.css">

Best City Guide

ice cream

donuts

tea

coffee

The Best City

		The best drinks and eats in the best city ever.

Welcome!

Everything in this city is worth waiting in line for. Cupcake ipsum dolor sit. Amet chocolate cake gummies jelly beans.

			Learn More

Great food

Croissant macaroon pie brownie. Cookie marshmallow liquorice gingerbread caramels toffee I love chocolate.

Wafer lollipop dessert. Bonbon jelly beans pudding dessert sugar plum.

			Learn More

How to get here

Plane: Tiramisu caramels gummies chupa chups lollipop muffin. Jujubes chocolate caramels cheesecake brownie lollipop dragée cheesecake.

Car: Pie apple pie pudding I love wafer toffee liquorice sesame snaps lemon drops. Lollipop gummi bears dessert muffin I love fruitcake toffee pie.

Car: Jelly cotton candy bonbon jelly-o jelly-o I love. I love sugar plum chocolate cake pie I love pastry liquorice.

			Learn More

		©2015 Residents of The Best City Ever.


text:
Namespace SqlClauses
    Public Class SqlJoinClause
        Private _joinTypeText As String
        Private _tableAlias As String
        Private _targetTable As String
        Private _targetColumn As String
        Private _srcTable As String
        Private _srcColumn As String

        Private _joinWhereConjunctionText As String
        Private _joinWhere As SqlWhereClause

        Public Property JoinWhereConjunctionText() As String
            Get
                Return _joinWhereConjunctionText
            End Get
            Set(ByVal value As String)
                _joinWhereConjunctionText = value
            End Set
        End Property

        Public Property JoinWhere() As SqlWhereClause
            Get
                Return _joinWhere
            End Get
            Set(ByVal value As SqlWhereClause)
                _joinWhere = value
            End Set
        End Property

        Public Property JoinTypeText() As String
            Get
                Return _joinTypeText
            End Get
            Set(ByVal value As String)
                _joinTypeText = value
            End Set
        End Property
        Public Property TableAlias() As String
            Get
                Return _tableAlias
            End Get
            Set(ByVal value As String)
                _tableAlias = value
            End Set
        End Property

        Public Property TargetTable() As String
            Get
                Return _targetTable
            End Get
            Set(ByVal value As String)
                _targetTable = value
            End Set
        End Property

        Public Property TargetColumn() As String
            Get
                Return _targetColumn
            End Get
            Set(ByVal value As String)
                _targetColumn = value
            End Set
        End Property

        Public Property SourceTable() As String
            Get
                Return _srcTable
            End Get
            Set(ByVal value As String)
                _srcTable = value
            End Set
        End Property

        Public Property SourceColumn() As String
            Get
                Return _srcColumn
            End Get
            Set(ByVal value As String)
                _srcColumn = value
            End Set
        End Property

        Public Overrides Function ToString() As String
            Dim tableName As String = TargetTable
            Dim strQry As String = String.Format("{0}[{1}]", _joinTypeText, _targetTable.Replace(".", "].["))

            If _tableAlias <> "" Then
                strQry &= " As [" & _tableAlias & "]"
                tableName = _tableAlias
            End If

            strQry &= String.Format(" ON [{0}].[{1}]=[{2}].[{3}]", _srcTable, _srcColumn, tableName, _targetColumn)

            If _joinWhere IsNot Nothing AndAlso _joinWhere.RecursiveClauseList.Count > 0 Then
                strQry += " " + _joinWhereConjunctionText + " (" + _joinWhere.ToString() + ")"
            End If

            Return strQry
        End Function
    End Class
End Namespace


text:
package com.swfarm.biz.ebay.job;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.swfarm.biz.chain.bo.Semaphore;
import com.swfarm.biz.chain.srv.ChainQueryService;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.chain.web.ChainFrontHelper;
import com.swfarm.biz.ebay.bo.DefaultCustomLabelParser;
import com.swfarm.biz.ebay.bo.EbayAccount;
import com.swfarm.biz.ebay.bo.EbayItem;
import com.swfarm.biz.ebay.bo.EbayItemSummary;
import com.swfarm.biz.ebay.bo.EbayItemSummaryGroup;
import com.swfarm.biz.ebay.dto.ItemVariation;
import com.swfarm.biz.ebay.dto.ItemVariations;
import com.swfarm.biz.ebay.dto.SearchEbayItemSummaryGroupsCriteria;
import com.swfarm.biz.ebay.srv.EbayService;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.oa.srv.UserService;
import com.swfarm.biz.product.bo.StockKeepingUnit;
import com.swfarm.biz.product.bo.StockKeepingUnitGroup;
import com.swfarm.biz.product.dto.SearchStockKeepingUnitGroupsCriteria;
import com.swfarm.biz.product.srv.ProductService;
import com.swfarm.biz.warehouse.srv.WarehouseQueryService;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.AppContext;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.SpringUtils;

public class AutoRecoverEbayItemSummarysTask extends QuartzJobBean {
	Logger logger = Logger.getLogger(AutoRecoverEbayItemSummarysTask.class);
	private UserService userService;
	private EbayService ebayService;
	private ProductService productService;
	private ChainService chainService;
	private ChainQueryService chainQueryService;
	private WarehouseService warehouseService;
	private WarehouseQueryService warehouseQueryService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setEbayService(EbayService ebayService) {
		this.ebayService = ebayService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	public void setChainQueryService(ChainQueryService chainQueryService) {
		this.chainQueryService = chainQueryService;
	}

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setWarehouseQueryService(
			WarehouseQueryService warehouseQueryService) {
		this.warehouseQueryService = warehouseQueryService;
	}

	public void recoverOosEbayItemSummarys() {
		this.logger.warn("*********start to recover EbayItemSummarys**********");
		SearchStockKeepingUnitGroupsCriteria searchStockKeepingUnitGroupsCriteria = new SearchStockKeepingUnitGroupsCriteria();
		String groupName = "oossku(0)";
		searchStockKeepingUnitGroupsCriteria.setName(groupName);
		List hiddenStockkeepingunitGroups = this.productService.searchStockKeepingUnitGroups(searchStockKeepingUnitGroupsCriteria);
		List oosArticleNumbers = new ArrayList();
		if (CollectionUtils.isNotEmpty(hiddenStockkeepingunitGroups)) {
			StockKeepingUnitGroup group = (StockKeepingUnitGroup) hiddenStockkeepingunitGroups.iterator().next();
			List<StockKeepingUnit> keepingUnits = group.getStockKeepingUnitList();
			if (CollectionUtils.isNotEmpty(keepingUnits)) {
				for (StockKeepingUnit sku : keepingUnits) {
					oosArticleNumbers.add(sku.getArticleNumber());
				}
			}
		}
		logger.warn("oosArticleNumbers.size [" + oosArticleNumbers.size() + "]");
		SearchEbayItemSummaryGroupsCriteria criteria = new SearchEbayItemSummaryGroupsCriteria();
		int n = 0;
		String hideOosName = "hideOosRecords(0)";
		criteria.setName(hideOosName);
		List hiddenEbayItemSummaryGroups = this.ebayService
				.searchEbayItemSummaryGroups(criteria);
		Map skuStockQuantities = this.warehouseQueryService
				.getArticleNumberStockQuantities();
		Map toBeDeliveredStatistics = this.chainQueryService
				.getToBeDeliveredStatistics();
		if (CollectionUtils.isNotEmpty(hiddenEbayItemSummaryGroups)) {
			EbayItemSummaryGroup ebayItemSummaryGroup = (EbayItemSummaryGroup) hiddenEbayItemSummaryGroups
					.iterator().next();
			this.logger.warn("ebayItemSummaryGroup.getEbayItemSummaryList() >> ["
							+ ebayItemSummaryGroup.getEbayItemSummaryList()
									.size() + "]");
			for (Iterator iter = ebayItemSummaryGroup.getEbayItemSummaryList()
					.iterator(); iter.hasNext();) {
				EbayItemSummary ebayItemSummary = (EbayItemSummary) iter.next();
				String accountNumber = ebayItemSummary.getAccountNumber();
				EbayAccount ebayAccount = this.ebayService
						.findEbayAccountByName(accountNumber);
				String itemId = ebayItemSummary.getItemId();
				EbayItem ebayItemInfo = this.ebayService.findEbayItemByItemId(itemId);
				if (ebayItemInfo == null) {
					this.ebayService.syncItemFromEbay(ebayItemSummary.getAccountNumber(), itemId);
					ebayItemInfo = this.ebayService.findEbayItemByItemId(itemId);
				}
				String variationProperties = ebayItemInfo.getVariationProperties();
				boolean toBeRevised = false;
				if (StringUtils.isNotEmpty(variationProperties)) {
					boolean flag = false;
					ItemVariations itemVariations = new ItemVariations();
					itemVariations.populateFromJsString(variationProperties);
					List itemVariationList = itemVariations.getItemVariations();
					for (Iterator itemIter = itemVariationList.iterator(); itemIter.hasNext();) {
						ItemVariation itemVariation = (ItemVariation) itemIter.next();
						String varArticleNumber = itemVariation.getArticleNumber();
						DefaultCustomLabelParser parser = new DefaultCustomLabelParser(varArticleNumber);
						String articleNumber = parser.getArticleNumber();
						if (!oosArticleNumbers.contains(articleNumber)) continue;
						Integer stockQuantity = (Integer) skuStockQuantities.get(articleNumber);
						stockQuantity = Integer.valueOf(stockQuantity == null ? 0
								: stockQuantity.intValue());
						Double toBeDeliveredQuantity = (Double) toBeDeliveredStatistics
								.get(articleNumber);
						toBeDeliveredQuantity = Double
								.valueOf(toBeDeliveredQuantity == null ? 0.0D
										: toBeDeliveredQuantity.doubleValue());
						Double allocatableQuantity = stockQuantity - toBeDeliveredQuantity;
						this.logger.warn("货号为:" + articleNumber + " 的可发货库存为:" + allocatableQuantity);
						if (allocatableQuantity > n) {
							try {
								toBeRevised = this.ebayService.reviseInventoryStatus(ebayAccount, itemId,
										articleNumber, Integer.valueOf(allocatableQuantity.intValue()));
								if (toBeRevised) {
									ChainFrontHelper.removeSkuFromGroup(articleNumber, groupName);
									logger.warn("货号:[" + articleNumber + "]恢复成功");
								} else {
									flag = true;
								}
							} catch (Exception e) {
								this.logger.warn(e);
							}
						} else {
							flag = true;
						}
					}
					if (!flag) ChainFrontHelper.removeItemFromGroup(itemId, hideOosName);
				} else {
					String articleNumber = ebayItemInfo.getArticleNumber();
					Integer stockQuantity = (Integer) skuStockQuantities.get(articleNumber);
					stockQuantity = Integer.valueOf(stockQuantity == null ? 0
							: stockQuantity.intValue());
					Double toBeDeliveredQuantity = (Double) toBeDeliveredStatistics
							.get(articleNumber);
					toBeDeliveredQuantity = Double
							.valueOf(toBeDeliveredQuantity == null ? 0.0D
									: toBeDeliveredQuantity.doubleValue());
					Double allocatableQuantity = stockQuantity - toBeDeliveredQuantity;
					this.logger.warn("货号为:" + articleNumber + " 的可发货库存为:" + allocatableQuantity);
					if (allocatableQuantity > n) {
						try {
							toBeRevised = this.ebayService.reviseInventoryStatus(ebayAccount, itemId, articleNumber,
									Integer.valueOf(allocatableQuantity.intValue()));
							if (toBeRevised) {
								ChainFrontHelper.removeItemFromGroup(itemId, hideOosName);
								ChainFrontHelper.removeSkuFromGroup(articleNumber, groupName);
								logger.warn("货号:[" + articleNumber + "]恢复成功");
							}
						} catch (Exception e) {
							this.logger.warn(e);
						}
					}
				}
			}
		}
		this.logger
				.warn("*********finish recover EbayItemSummarys************");
	}

	protected void executeInternal(JobExecutionContext jobExecutionContext)
			throws JobExecutionException {
		this.userService = ((UserService) SpringUtils.getBean("userService"));
		this.ebayService = ((EbayService) SpringUtils.getBean("ebayService"));
		this.productService = ((ProductService) SpringUtils
				.getBean("productService"));
		this.chainQueryService = ((ChainQueryService) SpringUtils
				.getBean("chainQueryService"));
		this.warehouseService = ((WarehouseService) SpringUtils
				.getBean("warehouseService"));
		this.warehouseQueryService = ((WarehouseQueryService) SpringUtils
				.getBean("warehouseQueryService"));
		User systemUser = this.userService.findUserByUsername("system");
		AppContext.getContextData().setCurrentUser(systemUser);
		this.chainService = ((ChainService) SpringUtils.getBean("chainService"));
		String jobDetailName = jobExecutionContext.getJobDetail().getName();
		this.logger.warn("jobDetailName >> " + jobDetailName);
		Semaphore semaphore = this.chainService
				.findSemaphoreByJobServerPrefixAndJobDetailName(
						Env.JOB_SERVER_PREFIX, jobDetailName);
		if (semaphore == null)
			recoverOosEbayItemSummarys();
	}
}


text:
package org.wso2.carbon.streaming.integrator.common.utils.config;

import org.wso2.carbon.config.annotation.Configuration;
import org.wso2.carbon.config.annotation.Element;

/**
 * A third level configuration bean class for siddhi extension config.
 */
@Configuration(description = "Extension configuration")
public class Extension {

    @Element(description = "A string field")
    private ExtensionChildConfiguration extension = new ExtensionChildConfiguration();

    public ExtensionChildConfiguration getExtension() {
        return extension;
    }
}


text:
/*************************************************************************/
/*  remote_transform_2d.cpp                                              */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "remote_transform_2d.h"
#include "scene/scene_string_names.h"

void RemoteTransform2D::_update_cache() {

	cache = 0;
	if (has_node(remote_node)) {
		Node *node = get_node(remote_node);
		if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
			return;
		}

		cache = node->get_instance_id();
	}
}

void RemoteTransform2D::_update_remote() {

	if (!is_inside_tree())
		return;

	if (!cache)
		return;

	Node2D *n = Object::cast_to<Node2D>(ObjectDB::get_instance(cache));
	if (!n)
		return;

	if (!n->is_inside_tree())
		return;

	//todo make faster
	if (use_global_coordinates) {

		if (update_remote_position && update_remote_rotation && update_remote_scale) {
			n->set_global_transform(get_global_transform());
		} else {
			Transform2D n_trans = n->get_global_transform();
			Transform2D our_trans = get_global_transform();
			Vector2 n_scale = n->get_scale();

			if (!update_remote_position)
				our_trans.set_origin(n_trans.get_origin());
			if (!update_remote_rotation)
				our_trans.set_rotation(n_trans.get_rotation());

			n->set_global_transform(our_trans);

			if (update_remote_scale)
				n->set_scale(get_global_scale());
			else
				n->set_scale(n_scale);
		}

	} else {

		if (update_remote_position && update_remote_rotation && update_remote_scale) {
			n->set_transform(get_transform());
		} else {
			Transform2D n_trans = n->get_transform();
			Transform2D our_trans = get_transform();
			Vector2 n_scale = n->get_scale();

			if (!update_remote_position)
				our_trans.set_origin(n_trans.get_origin());
			if (!update_remote_rotation)
				our_trans.set_rotation(n_trans.get_rotation());

			n->set_transform(our_trans);

			if (update_remote_scale)
				n->set_scale(get_scale());
			else
				n->set_scale(n_scale);
		}
	}
}

void RemoteTransform2D::_notification(int p_what) {

	switch (p_what) {

		case NOTIFICATION_READY: {

			_update_cache();

		} break;
		case NOTIFICATION_TRANSFORM_CHANGED: {
			if (!is_inside_tree())
				break;

			if (cache) {

				_update_remote();
			}

		} break;
	}
}

void RemoteTransform2D::set_remote_node(const NodePath &p_remote_node) {

	remote_node = p_remote_node;
	if (is_inside_tree()) {
		_update_cache();
		_update_remote();
	}

	update_configuration_warning();
}

NodePath RemoteTransform2D::get_remote_node() const {

	return remote_node;
}

void RemoteTransform2D::set_use_global_coordinates(const bool p_enable) {
	use_global_coordinates = p_enable;
	_update_remote();
}

bool RemoteTransform2D::get_use_global_coordinates() const {
	return use_global_coordinates;
}

void RemoteTransform2D::set_update_position(const bool p_update) {
	update_remote_position = p_update;
	_update_remote();
}

bool RemoteTransform2D::get_update_position() const {
	return update_remote_position;
}

void RemoteTransform2D::set_update_rotation(const bool p_update) {
	update_remote_rotation = p_update;
	_update_remote();
}

bool RemoteTransform2D::get_update_rotation() const {
	return update_remote_rotation;
}

void RemoteTransform2D::set_update_scale(const bool p_update) {
	update_remote_scale = p_update;
	_update_remote();
}

bool RemoteTransform2D::get_update_scale() const {
	return update_remote_scale;
}

String RemoteTransform2D::get_configuration_warning() const {

	if (!has_node(remote_node) || !Object::cast_to<Node2D>(get_node(remote_node))) {
		return TTR("Path property must point to a valid Node2D node to work.");
	}

	return String();
}

void RemoteTransform2D::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform2D::set_remote_node);
	ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform2D::get_remote_node);

	ClassDB::bind_method(D_METHOD("set_use_global_coordinates", "use_global_coordinates"), &RemoteTransform2D::set_use_global_coordinates);
	ClassDB::bind_method(D_METHOD("get_use_global_coordinates"), &RemoteTransform2D::get_use_global_coordinates);

	ClassDB::bind_method(D_METHOD("set_update_position", "update_remote_position"), &RemoteTransform2D::set_update_position);
	ClassDB::bind_method(D_METHOD("get_update_position"), &RemoteTransform2D::get_update_position);
	ClassDB::bind_method(D_METHOD("set_update_rotation", "update_remote_rotation"), &RemoteTransform2D::set_update_rotation);
	ClassDB::bind_method(D_METHOD("get_update_rotation"), &RemoteTransform2D::get_update_rotation);
	ClassDB::bind_method(D_METHOD("set_update_scale", "update_remote_scale"), &RemoteTransform2D::set_update_scale);
	ClassDB::bind_method(D_METHOD("get_update_scale"), &RemoteTransform2D::get_update_scale);

	ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node2D"), "set_remote_node", "get_remote_node");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_global_coordinates"), "set_use_global_coordinates", "get_use_global_coordinates");

	ADD_GROUP("Update", "update_");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_position"), "set_update_position", "get_update_position");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_rotation"), "set_update_rotation", "get_update_rotation");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_scale"), "set_update_scale", "get_update_scale");
}

RemoteTransform2D::RemoteTransform2D() {

	use_global_coordinates = true;
	update_remote_position = true;
	update_remote_rotation = true;
	update_remote_scale = true;

	cache = 0;
	set_notify_transform(true);
}


text:
package org.apache.flink.test.example.java;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.test.testdata.WordCountData;
import org.apache.flink.test.util.JavaProgramTestBase;
import org.apache.flink.util.Collector;

import java.io.Serializable;

import static org.apache.flink.test.util.TestBaseUtils.compareResultsByLinesInMemory;

/** WordCount with simple POJO example. */
public class WordCountSimplePOJOITCase extends JavaProgramTestBase implements Serializable {
    private static final long serialVersionUID = 1L;
    protected String textPath;
    protected String resultPath;

    @Override
    protected void preSubmit() throws Exception {
        textPath = createTempFile("text.txt", WordCountData.TEXT);
        resultPath = getTempDirPath("result");
    }

    @Override
    protected void postSubmit() throws Exception {
        compareResultsByLinesInMemory(WordCountData.COUNTS, resultPath);
    }

    @Override
    protected void testProgram() throws Exception {
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        DataSet<String> text = env.readTextFile(textPath);

        DataSet<WC> counts =
                text.flatMap(new Tokenizer())
                        .groupBy("word")
                        .reduce(
                                new ReduceFunction<WC>() {
                                    private static final long serialVersionUID = 1L;

                                    public WC reduce(WC value1, WC value2) {
                                        return new WC(value1.word, value1.count + value2.count);
                                    }
                                });

        counts.writeAsText(resultPath);

        env.execute("WordCount with custom data types example");
    }

    private static final class Tokenizer implements FlatMapFunction<String, WC> {
        private static final long serialVersionUID = 1L;

        @Override
        public void flatMap(String value, Collector<WC> out) {
            // normalize and split the line
            String[] tokens = value.toLowerCase().split("\\W+");

            // emit the pairs
            for (String token : tokens) {
                if (token.length() > 0) {
                    out.collect(new WC(token, 1));
                }
            }
        }
    }

    /** POJO with word and count. */
    public static class WC {
        public WC() {}

        public WC(String w, int c) {
            word = w;
            count = c;
        }

        public String word;
        public int count;

        @Override
        public String toString() {
            return word + " " + count;
        }
    }
}


text:
package org.jenkinsci.plugins.spokehubintegration.command;

import org.jenkinsci.plugins.spokehubintegration.SlackData;
import org.jenkinsci.plugins.spokehubintegration.SlackMessage;

/**
 * Class that requires the execution of a command.
 *
 * @author Tommaso Montingelli
 *
 */
public class JenkinsInvoker {

	private Command command;

	/**
	 * Instantiates the requested command.
	 *
	 * @param command requested command
	 */
	public JenkinsInvoker(Command command) {
		this.command = command;
	}

	/**
	 * Starts a build for any type of job.
	 *
	 * @param data data sent by Slack
	 * @return response to the requested command
	 */
	public SlackMessage build(SlackData data) {
		return this.command.execute(data);
	}

	/**
	 * Performs tests for a maven job.
	 *
	 * @param data data sent by Slack
	 * @return response to the requested command
	 */
	public SlackMessage test(SlackData data) {
		return this.command.execute(data);
	}

	/**
	 * Lists all jobs.
	 *
	 * @param data data sent by Slack
	 * @return response to the requested command
	 */
	public SlackMessage listJobs(SlackData data) {
		return this.command.execute(data);
	}

	/**
	 * Lists all the available commands or a detailed description of single command.
	 *
	 * @param data data sent by Slack
	 * @return response to the requested command
	 */
	public SlackMessage help(SlackData data) {
		return this.command.execute(data);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NSubstitute;
using NUnit.Framework;
using Wyam.Common.Documents;
using Wyam.Common.Meta;
using Wyam.Common.Execution;
using Wyam.Testing;

namespace Wyam.Modules.Json.Tests
{
    [TestFixture]
    [Parallelizable(ParallelScope.Self | ParallelScope.Children)]
    public class GenerateJsonTests : BaseFixture
    {
        private class Account
        {
            public string Email { get; set; }
            public bool Active { get; set; }
            public DateTime CreatedDate { get; set; }
            public IList<string> Roles { get; set; }
        }

        private static Account JsonObject = new Account
        {
            Email = "james@example.com",
            Active = true,
            CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
            Roles = new List<string>
            {
                "User",
                "Admin"
            }
        };

        private static string JsonContent = @"{
  ""Email"": ""james@example.com"",
  ""Active"": true,
  ""CreatedDate"": ""2013-01-20T00:00:00Z"",
  ""Roles"": [
    ""User"",
    ""Admin""
  ]
}";

        public class ExecuteMethodTests : GenerateJsonTests
        {
            [Test]
            public void GetsObjectFromMetadata()
            {
                // Given
                IExecutionContext context = Substitute.For<IExecutionContext>();
                IDocument document = Substitute.For<IDocument>();
                document.Get("JsonObject").Returns(JsonObject);
                GenerateJson generateJson = new GenerateJson("JsonObject");

                // When
                generateJson.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, Arg.Is(JsonContent));
            }

            [Test]
            public void GetsObjectFromContextDelegate()
            {
                // Given
                IExecutionContext context = Substitute.For<IExecutionContext>();
                IDocument document = Substitute.For<IDocument>();
                GenerateJson generateJson = new GenerateJson(ctx => JsonObject);

                // When
                generateJson.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, Arg.Is(JsonContent));
            }

            [Test]
            public void GetsObjectFromDocumentDelegate()
            {
                // Given
                IExecutionContext context = Substitute.For<IExecutionContext>();
                IDocument document = Substitute.For<IDocument>();
                document.Get("JsonObject").Returns(JsonObject);
                GenerateJson generateJson = new GenerateJson((doc, ctx) => doc.Get("JsonObject"));

                // When
                generateJson.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, Arg.Is(JsonContent));
            }

            [Test]
            public void SetsMetadataKey()
            {
                // Given
                IExecutionContext context = Substitute.For<IExecutionContext>();
                IDocument document = Substitute.For<IDocument>();
                document.Get("JsonObject").Returns(JsonObject);
                GenerateJson generateJson = new GenerateJson("JsonObject", "OutputKey");

                // When
                generateJson.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>());
                context.Received().GetDocument(document, Arg.Is<IEnumerable<KeyValuePair<string, object>>>(
                    x => x.First().Key == "OutputKey" && (string)x.First().Value == JsonContent));
            }

            [Test]
            public void DoesNotIndent()
            {
                // Given
                IExecutionContext context = Substitute.For<IExecutionContext>();
                IDocument document = Substitute.For<IDocument>();
                document.Get("JsonObject").Returns(JsonObject);
                GenerateJson generateJson = new GenerateJson("JsonObject").WithIndenting(false);
                string nonIndentedJsonContent = JsonContent.Replace(" ", "").Replace("\r\n", "");

                // When
                generateJson.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, Arg.Is(nonIndentedJsonContent));
            }
        }
    }
}


text:
/**
 * Action object contains
 * @param options.which Array of key codes
 * @param options.shift Whether shift key is required
 * @param options.commandKey Whether command key is required
 * @param options.name Shortcut name
 * @param options.cb Function callback
 * @param options.accept Additional function to test whether to accept shortcut
 * @param options.icon Optional icon to display
 */
morpheus.ActionManager = function () {
  this.actionNameToAction = new morpheus.Map();
  this.actions = [];
  // TODO copy all row/column metadata
  // pin/unpin tab,
  // header stuff-display, delete.
  this.add({
    ellipsis: true,
    name: 'Sort/Group',
    cb: function (options) {
      new morpheus.SortDialog(options.heatMap.getProject());
    },
    icon: 'fa fa-sort-alpha-asc'
  });

  var $filterModal = null;
  var windowOpen = function (url) {
    if (morpheus.Util.isNode()) {
      var remote = require('electron').remote;
      var BrowserWindow = remote.BrowserWindow;
      var newWindow = new BrowserWindow({
        fullscreenable: false
      });
      newWindow.loadURL(url);
      newWindow.on('closed', function () {
        newWindow = null;
      });
    } else {
      window.open(url);
    }
  };
  this.add({
    name: 'Filter',
    ellipsis: true,
    cb: function (options) {
      if ($filterModal == null) {
        var filterModal = [];
        var filterLabelId = _.uniqueId('morpheus');
        filterModal
          .push('
');
        filterModal.push('
');
        filterModal.push('
');
        filterModal.push('
');
        filterModal
          .push('<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>');
        filterModal.push('
Filter
');
        filterModal.push('
');
        filterModal.push('

');
        filterModal.push('
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
');
        filterModal.push('
');
        filterModal.push('
');
        filterModal.push('
');
        $filterModal = $(filterModal.join(''));
        $filterModal.on('mousewheel', function (e) {
          e.stopPropagation();
        });
        var $filter = $('

');
        $filter.appendTo($filterModal.find('.modal-body'));
        var filterHtml = [];
        filterHtml
          .push('
<input type="radio" name="rowsOrColumns" value="rows" checked>Rows
 ');
        filterHtml
          .push('
<input type="radio" name="rowsOrColumns" value="columns">Columns
');

        var $filterChooser = $(filterHtml.join(''));
        $filterChooser.appendTo($filter);
        var columnFilterUI = new morpheus.FilterUI(options.heatMap.getProject(), true);
        var rowFilterUI = new morpheus.FilterUI(options.heatMap.getProject(), false);
        // options.heatMap.getProject().getRowFilter().on('focus', function (e) {
        //   $filterChooser.find('[value=rows]').prop('checked', true);
        //   columnFilterUI.$div.hide();
        //   rowFilterUI.$div.show();
        //   $filterModal.modal('show');
        //   morpheus.Util.trackEvent({
        //     eventCategory: '',
        //     eventAction: 'rowFilter'
        //   });
        //
        // });
        // options.heatMap.getProject().getColumnFilter().on('focus', function (e) {
        //   $filterChooser.find('[value=columns]').prop('checked', true);
        //   columnFilterUI.$div.show();
        //   rowFilterUI.$div.hide();
        //   $filterModal.modal('show');
        //   morpheus.Util.trackEvent({
        //     eventCategory: '',
        //     eventAction: 'columnFilter'
        //   });
        // });
        rowFilterUI.$div.appendTo($filter);
        columnFilterUI.$div.appendTo($filter);
        columnFilterUI.$div.css('display', 'none');
        var $filterRadio = $filterChooser.find('[name=rowsOrColumns]');
        $filterRadio.on('change', function (e) {
          var val = $filterRadio.filter(':checked').val();
          if (val === 'columns') {
            columnFilterUI.$div.show();
            rowFilterUI.$div.hide();
          } else {
            columnFilterUI.$div.hide();
            rowFilterUI.$div.show();
          }
          e.preventDefault();
        });
        $filterModal.appendTo(options.heatMap.$content);
        $filterModal.on('hidden.bs.modal', function () {
          options.heatMap.focus();
        });
      }
      $filterModal.modal('show');
    },
    icon: 'fa fa-filter'
  });

  this.add({
    name: 'Options',
    ellipsis: true,
    cb: function (options) {
      options.heatMap.showOptions();
    },
    icon: 'fa fa-cog'
  });

  this.add({
    which: [191], // slash
    commandKey: true,
    global: true,
    name: 'Toggle Search',
    cb: function (options) {
      options.heatMap.getToolbar().toggleSearch();
    }
  });

  //
  this.add({
    name: 'Copy Image',
    icon: 'fa fa-clipboard',
    cb: function (options) {
      var bounds = options.heatMap.getTotalSize();
      var height = bounds.height;
      var width = bounds.width;
      var canvas = $('<canvas></canvas>')[0];
      var backingScale = morpheus.CanvasUtil.BACKING_SCALE;
      canvas.height = backingScale * height;
      canvas.style.height = height + 'px';
      canvas.width = backingScale * width;
      canvas.style.width = width + 'px';
      var context = canvas.getContext('2d');
      morpheus.CanvasUtil.resetTransform(context);
      options.heatMap.snapshot(context);
      var url = canvas.toDataURL();
      // canvas.toBlob(function (blob) {
      // 	url = URL.createObjectURL(blob);
      // 	event.clipboardData
      // 	.setData(
      // 		'text/html',
      // 		'');
      // });

      morpheus.Util.setClipboardData([
        {
          format: 'text/html',
          data: ''
        }], true);
    }
  });

  //
  this.add({
    name: 'Close Tab',
    cb: function (options) {
      options.heatMap.getTabManager().remove(options.heatMap.tabId);
    }
  });
  this.add({
    name: 'Rename Tab',
    ellipsis: true,
    cb: function (options) {
      options.heatMap.getTabManager().rename(options.heatMap.tabId);
    }
  });

  this.add({
    which: [88], // x
    commandKey: true,
    name: 'New Heat Map',
    accept: function (options) {
      return (!options.isInputField || window.getSelection().toString() === '');
    },

    cb: function (options) {
      morpheus.HeatMap.showTool(new morpheus.NewHeatMapTool(),
        options.heatMap);
    }
  });

  this.add({
    which: [67], // C
    commandKey: true,
    name: 'Copy'
  });

  this.add({
    which: [86], // V
    commandKey: true,
    name: 'Paste Dataset'
  });

  this.add({
    global: true,
    name: 'Open',
    ellipsis: true,
    cb: function (options) {
      morpheus.HeatMap.showTool(new morpheus.OpenFileTool(), options.heatMap);
    },
    which: [79],
    commandKey: true,
    icon: 'fa fa-folder-open-o'
  });

  this.add({
    ellipsis: true,
    name: 'Save Image',
    gui: function () {
      return new morpheus.SaveImageTool();
    },
    cb: function (options) {
      morpheus.HeatMap.showTool(this.gui(),
        options.heatMap);
    },
    which: [83],
    commandKey: true,
    global: true,
    icon: 'fa fa-file-image-o'
  });

  this.add({
    ellipsis: true,
    name: 'Save Dataset',
    gui: function () {
      return new morpheus.SaveDatasetTool();
    },
    cb: function (options) {
      morpheus.HeatMap.showTool(this.gui(),
        options.heatMap);
    },
    // shiftKey: true,
    // which: [83],
    // commandKey: true,
    // global: true,
    icon: 'fa fa-floppy-o'
  });

  this.add({
    ellipsis: true,
    name: 'Save Session',
    gui: function () {
      return new morpheus.SaveSessionTool();
    },
    cb: function (options) {
      morpheus.HeatMap.showTool(this.gui(), options.heatMap);
    },
    icon: 'fa fa-anchor'
  });

  if (typeof echarts !== 'undefined') {
    this.add({
      name: 'Chart',
      cb: function (options) {
        new morpheus.ChartTool({
          project: options.heatMap.getProject(),
          heatmap: options.heatMap,
          getVisibleTrackNames: _.bind(
            options.heatMap.getVisibleTrackNames, options.heatMap)
        });
      },
      icon: 'fa fa-line-chart'
    });
  }

  this.add({
    name: 'Zoom In',
    cb: function (options) {
      options.heatMap.zoom(true);
    },
    which: [107, 61, 187]
  });
  this.add({
    name: 'Zoom Out',
    cb: function (options) {
      options.heatMap.zoom(false);
    },
    which: [173, 189, 109]
  });

  this.add({
    name: 'Fit To Window',
    cb: function (options) {
      options.heatMap.fitToWindow({fitRows: true, fitColumns: true, repaint: true});
    },
    which: [48], // zero
    commandKey: true,
    icon: 'fa fa-compress'
  });
  this.add({
    name: 'Fit Columns To Window',
    cb: function (options) {
      options.heatMap.fitToWindow({fitRows: false, fitColumns: true, repaint: true});
    }
  });
  this.add({
    name: 'Fit Rows To Window',
    cb: function (options) {
      options.heatMap.fitToWindow({fitRows: true, fitColumns: false, repaint: true});
    }
  });
  this.add({
    name: '100%',
    cb: function (options) {
      options.heatMap.resetZoom();
    },
    button: '100%',
    which: [48], // zero
    commandKey: true,
    shiftKey: true
  });

  this.add({
    which: [35],
    name: 'Go To End',
    cb: function (options) {
      options.heatMap.scrollLeft(options.heatMap.heatmap.getPreferredSize().width);
      options.heatMap.scrollTop(options.heatMap.heatmap.getPreferredSize().height);
    }
  });
  this.add({
    which: [36], // home key
    name: 'Go To Start',
    cb: function (options) {
      options.heatMap.scrollLeft(0);
      options.heatMap.scrollTop(0);
    }
  });
  this.add({
    which: [34], // page down
    commandKey: true,
    name: 'Go To Bottom',
    cb: function (options) {
      options.heatMap
        .scrollTop(options.heatMap.heatmap.getPreferredSize().height);
    }
  });
  this.add({
    which: [34], // page down
    commandKey: false,
    name: 'Scroll Page Down',
    cb: function (options) {
      var pos = options.heatMap.scrollTop();
      options.heatMap.scrollTop(pos + options.heatMap.heatmap.getUnscaledHeight()
        - 2);
    }
  });

  this.add({
    which: [33], // page up
    commandKey: true,
    name: 'Go To Top',
    cb: function (options) {
      options.heatMap
        .scrollTop(0);
    }
  });
  this.add({
    which: [33], // page up
    commandKey: false,
    name: 'Scroll Page Up',
    cb: function (options) {
      var pos = options.heatMap.scrollTop();
      options.heatMap.scrollTop(pos - options.heatMap.heatmap.getUnscaledHeight()
        + 2);
    }
  });

  this.add({
    which: [38], // up arrow
    commandKey: true,
    name: 'Zoom Out Rows',
    cb: function (options) {
      options.heatMap.zoom(false, {
        columns: false,
        rows: true
      });
    }
  });
  this.add({
    which: [38], // up arrow
    commandKey: false,
    name: 'Scroll Up',
    cb: function (options) {
      options.heatMap.scrollTop(options.heatMap.scrollTop() - 8);
    }
  });

  this.add({
    which: [40], // down arrow
    commandKey: true,
    name: 'Zoom In Rows',
    cb: function (options) {
      options.heatMap.zoom(true, {
        columns: false,
        rows: true
      });
    }
  });
  this.add({
    which: [40], // down arrow
    commandKey: false,
    name: 'Scroll Down',
    cb: function (options) {
      options.heatMap.scrollTop(options.heatMap.scrollTop() + 8);
    }
  });

  this.add({
    which: [37], // left arrow
    commandKey: true,
    name: 'Zoom Out Columns',
    cb: function (options) {
      options.heatMap.zoom(false, {
        columns: true,
        rows: false
      });
    }
  });
  this.add({
    which: [37], // left arrow
    commandKey: false,
    name: 'Scroll Left',
    cb: function (options) {
      options.heatMap.scrollLeft(options.heatMap.scrollLeft() - 8);
    }
  });

  this.add({
    which: [39], // right arrow
    commandKey: true,
    name: 'Zoom In Columns',
    cb: function (options) {
      options.heatMap.zoom(true, {
        columns: true,
        rows: false
      });
    }
  });
  this.add({
    which: [39], // right arrow
    commandKey: false,
    name: 'Scroll Right',
    cb: function (options) {
      options.heatMap.scrollLeft(options.heatMap.scrollLeft() + 8);
    }
  });
  this.add({
    name: 'Tutorial',
    cb: function () {
      windowOpen('https://software.broadinstitute.org/morpheus/tutorial.html');
    }
  });

  this.add({
    icon: 'fa fa-code',
    name: 'Source Code',
    cb: function () {
      windowOpen('https://github.com/cmap/morpheus.js');
    }
  });
  var $findModal;
  var $search;

  this.add({
    which: [65],
    ellipsis: true,
    shiftKey: true,
    commandKey: true,
    name: 'Find Action',
    cb: function (options) {
      if ($findModal == null) {
        var findModal = [];
        var id = _.uniqueId('morpheus');
        findModal
          .push('
');
        findModal.push('
');
        findModal.push('
');
        findModal.push('
');
        findModal
          .push('<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>');
        findModal.push('
Enter action
');
        findModal.push('
');
        findModal.push('
<input class="form-control input-sm">
');
        findModal.push('
');
        findModal.push('
');
        findModal.push('
');
        $findModal = $(findModal.join(''));
        $findModal.appendTo(options.heatMap.$content);
        var allActions = options.heatMap.getActionManager().getActions();
        $search = $findModal.find('input');
        $search.on('keyup', function (e) {
          if (e.which === 13) {
            var text = $search.val().trim();
            if (text !== '') {
              var action = _this.getAction(text);
              if (action) {
                $findModal.modal('hide');
                _this.execute(text, {event: e});
              }
            }
          }
        });
        morpheus.Util.autosuggest({
          $el: $search,
          multi: false,
          suggestWhenEmpty: false,
          //  history: options.history,
          filter: function (tokens, response) {
            var token = tokens[0].trim();
            var matches = [];
            var replaceRegex = new RegExp('(' + morpheus.Util.escapeRegex(token) + ')', 'i');
            for (var i = 0; i < allActions.length; i++) {
              if (allActions[i].cb) {
                var name = allActions[i].name;
                if (replaceRegex.test(name)) {
                  matches.push({
                    clear: true,
                    value: name,
                    label: ''
                    + name.replace(replaceRegex, '$1') + ''
                  });
                }
              }
            }
            response(matches);

          },
          select: function () {
            setTimeout(function () {
              var text = $search.val().trim();
              if (text !== '') {
                var action = _this.getAction(text);
                if (action) {
                  $findModal.modal('hide');
                  _this.execute(text);
                }
              }
            }, 20);

          }
        });
        $findModal.on('hidden.bs.modal', function () {
          options.heatMap.focus();
        });
      }
      $findModal.modal('show');
      $search.focus();
    }
  });
  this.add({
    name: 'Keyboard Shortcuts',
    cb: function (options) {
      new morpheus.HeatMapKeyListener(options.heatMap).showKeyMapReference();
    }
  });

  this.add({
    name: 'Configuration',
    cb: function () {
      windowOpen('https://software.broadinstitute.org/morpheus/configuration.html');
    }
  });
  this.add({
    name: 'Contact',
    icon: 'fa fa-envelope-o',
    cb: function (options) {
      morpheus.FormBuilder.showInModal({
        title: 'Contact',
        html: 'Please email us at morpheus@broadinstitute.org',
        focus: options.heatMap.getFocusEl()
      });
    }
  });

  this.add({
    which: [65], // a
    commandKey: true,
    name: 'Select All',
    accept: function (options) {
      var active = options.heatMap.getActiveComponent();
      return (active === 'rowTrack' || active === 'columnTrack');
    },
    cb: function (options) {
      var active = options.heatMap.getActiveComponent();
      var selectionModel = active === 'rowTrack' ? options.heatMap.getProject()
        .getRowSelectionModel() : options.heatMap.getProject()
        .getColumnSelectionModel();
      var count = active === 'rowTrack' ? options.heatMap.getProject()
        .getSortedFilteredDataset().getRowCount() : options.heatMap
        .getProject().getSortedFilteredDataset()
        .getColumnCount();
      var indices = new morpheus.Set();
      for (var i = 0; i < count; i++) {
        indices.add(i);
      }
      selectionModel.setViewIndices(indices, true);
    }
  });

  var invertAction = function (options, isColumns) {
    var model = isColumns ? options.heatMap.getProject().getColumnSelectionModel() : options.heatMap.getProject().getRowSelectionModel();
    var viewIndices = model.getViewIndices();
    var inverse = new morpheus.Set();
    var n = n = isColumns ? options.heatMap.getProject().getSortedFilteredDataset().getColumnCount() : options.heatMap.getProject().getSortedFilteredDataset().getRowCount();
    for (var i = 0; i < n; i++) {
      if (!viewIndices.has(i)) {
        inverse.add(i);
      }
    }
    model.setViewIndices(inverse, true);
  };
  this.add({
    name: 'Invert Selected Rows',
    cb: function (options) {
      invertAction(options, false);
    }
  });
  this.add({
    name: 'Invert Selected Columns',
    cb: function (options) {
      invertAction(options, true);
    }
  });
  var clearAction = function (options, isColumns) {
    var model = isColumns ? options.heatMap.getProject()
      .getColumnSelectionModel() : options.heatMap.getProject()
      .getRowSelectionModel();
    model.setViewIndices(new morpheus.Set(), true);
  };
  this.add({
    name: 'Clear Selected Rows',
    cb: function (options) {
      clearAction(options, false);
    }
  });
  this.add({
    name: 'Clear Selected Columns',
    cb: function (options) {
      clearAction(options, true);
    }
  });

  var moveToTop = function (options, isColumns) {
    var project = options.heatMap.getProject();
    var selectionModel = !isColumns ? project.getRowSelectionModel()
      : project
        .getColumnSelectionModel();
    var viewIndices = selectionModel.getViewIndices().values();
    if (viewIndices.length === 0) {
      return;
    }
    viewIndices.sort(function (a, b) {
      return (a === b ? 0 : (a < b ? -1 : 1));
    });
    var converter = isColumns ? project.convertViewColumnIndexToModel
      : project.convertViewRowIndexToModel;
    converter = _.bind(converter, project);
    var modelIndices = [];
    for (var i = 0, n = viewIndices.length; i < n; i++) {
      modelIndices.push(converter(viewIndices[i]));
    }
    var sortKey = new morpheus.MatchesOnTopSortKey(project, modelIndices, 'selection on top', isColumns);
    sortKey.setLockOrder(1);
    sortKey.setUnlockable(false);
    if (isColumns) {
      project
        .setColumnSortKeys(
          morpheus.SortKey
            .keepExistingSortKeys(
              [sortKey],
              project
                .getColumnSortKeys().filter(function (key) {
                return !(key instanceof morpheus.MatchesOnTopSortKey && key.toString() === sortKey.toString());
              })),
          true);
    } else {
      project
        .setRowSortKeys(
          morpheus.SortKey
            .keepExistingSortKeys(
              [sortKey],
              project
                .getRowSortKeys().filter(function (key) {
                return !(key instanceof morpheus.MatchesOnTopSortKey && key.toString() === sortKey.toString());
              })),
          true);
    }
  };
  this.add({
    name: 'Move Selected Rows To Top',
    cb: function (options) {
      moveToTop(options, false);
    }
  });
  this.add({
    name: 'Move Selected Columns To Top',
    cb: function (options) {
      moveToTop(options, true);
    }
  });
  var selectAll = function (options, isColumns) {
    var project = options.heatMap.getProject();
    var selectionModel = !isColumns ? project.getRowSelectionModel()
      : project
        .getColumnSelectionModel();
    var count = !isColumns ? project
      .getSortedFilteredDataset()
      .getRowCount() : project
      .getSortedFilteredDataset()
      .getColumnCount();
    var indices = new morpheus.Set();
    for (var i = 0; i < count; i++) {
      indices.add(i);
    }
    selectionModel.setViewIndices(indices, true);
  };
  this.add({
    name: 'Select All Rows',
    cb: function (options) {
      selectAll(options, false);
    }
  });
  this.add({
    name: 'Select All Columns',
    cb: function (options) {
      selectAll(options, true);
    }
  });
  var copySelection = function (options, isColumns) {
    var project = options.heatMap.getProject();
    var dataset = project
      .getSortedFilteredDataset();
    var activeTrackName = options.heatMap.getSelectedTrackName(isColumns);
    var v;
    if (activeTrackName == null) {
      v = isColumns ? dataset.getColumnMetadata()
        .get(0) : dataset
        .getRowMetadata().get(0);
    } else {
      v = isColumns ? dataset.getColumnMetadata()
        .getByName(activeTrackName) : dataset
        .getRowMetadata().getByName(activeTrackName);
    }

    var selectionModel = isColumns ? project
      .getColumnSelectionModel() : project
      .getRowSelectionModel();
    var text = [];
    var toStringFunction = morpheus.VectorTrack.vectorToString(v);
    selectionModel.getViewIndices().forEach(
      function (index) {
        text.push(toStringFunction(v
          .getValue(index)));
      });
    morpheus.Util.setClipboardData([
      {
        format: 'text/plain',
        data: text.join('\n')
      }]);
  };
  this.add({
    name: 'Copy Selected Rows',
    cb: function (options) {
      copySelection(options, false);
    }
  });
  this.add({
    name: 'Copy Selected Columns',
    cb: function (options) {
      copySelection(options, true);
    }
  });

  var annotateSelection = function (options, isColumns) {

    var project = options.heatMap.getProject();
    var selectionModel = isColumns ? project
        .getColumnSelectionModel()
      : project
        .getRowSelectionModel();
    if (selectionModel.count() === 0) {
      morpheus.FormBuilder
        .showMessageModal({
          title: 'Annotate Selection',
          html: 'No ' + (isColumns ? 'columns' : 'rows') + ' selected.',
          focus: options.heatMap.getFocusEl()
        });
      return;
    }
    var formBuilder = new morpheus.FormBuilder();
    formBuilder.append({
      name: 'annotation_name',
      type: 'text',
      required: true
    });
    formBuilder.append({
      name: 'annotation_value',
      type: 'text',
      required: true
    });
    morpheus.FormBuilder
      .showOkCancel({
        title: 'Annotate',
        content: formBuilder.$form,
        focus: options.heatMap.getFocusEl(),
        okCallback: function () {
          var value = formBuilder
            .getValue('annotation_value');
          var annotationName = formBuilder
            .getValue('annotation_name');
          var dataset = project
            .getSortedFilteredDataset();
          var fullDataset = project
            .getFullDataset();
          if (isColumns) {
            dataset = morpheus.DatasetUtil
              .transposedView(dataset);
            fullDataset = morpheus.DatasetUtil
              .transposedView(fullDataset);
          }

          var existingVector = fullDataset
            .getRowMetadata()
            .getByName(
              annotationName);
          var v = dataset
            .getRowMetadata().add(
              annotationName);

          selectionModel
            .getViewIndices()
            .forEach(
              function (index) {
                v
                  .setValue(
                    index,
                    value);
              });
          morpheus.VectorUtil
            .maybeConvertStringToNumber(v);
          project
            .trigger(
              'trackChanged',
              {
                vectors: [v],
                display: existingVector != null ? []
                  : [morpheus.VectorTrack.RENDER.TEXT],
                columns: isColumns
              });
        }
      });
  };
  this.add({
    ellipsis: true,
    name: 'Annotate Selected Rows',
    cb: function (options) {
      annotateSelection(options, false);
    }
  });
  this.add({
    ellipsis: true,
    name: 'Annotate Selected Columns',
    cb: function (options) {
      annotateSelection(options, true);
    }
  });
  this.add({
    name: 'Copy Selected Dataset',
    cb: function (options) {
      var project = options.heatMap.getProject();
      var dataset = project.getSelectedDataset({
        emptyToAll: false
      });
      var columnMetadata = dataset
        .getColumnMetadata();
      var rowMetadata = dataset.getRowMetadata();
      // only copy visible tracks
      var visibleColumnFields = options.heatMap
        .getVisibleTrackNames(true);
      var columnFieldIndices = [];
      _.each(visibleColumnFields, function (name) {
        var index = morpheus.MetadataUtil.indexOf(
          columnMetadata, name);
        if (index !== -1) {
          columnFieldIndices.push(index);
        }
      });
      columnMetadata = new morpheus.MetadataModelColumnView(
        columnMetadata, columnFieldIndices);
      var rowMetadata = dataset.getRowMetadata();
      // only copy visible tracks
      var visibleRowFields = options.heatMap
        .getVisibleTrackNames(false);
      var rowFieldIndices = [];
      _.each(visibleRowFields, function (name) {
        var index = morpheus.MetadataUtil.indexOf(
          rowMetadata, name);
        if (index !== -1) {
          rowFieldIndices.push(index);
        }
      });
      rowMetadata = new morpheus.MetadataModelColumnView(
        rowMetadata, rowFieldIndices);

      var text = new morpheus.GctWriter()
        .write(dataset);
      morpheus.Util.setClipboardData([
        {
          format: 'text/plain',
          data: text
        }]);

    }
  });
  var _this = this;
  [
    new morpheus.HClusterTool(), new morpheus.KMeansTool(), new morpheus.MarkerSelection(), new morpheus.NearestNeighbors(), new morpheus.AdjustDataTool(),
    new morpheus.CollapseDatasetTool(), new morpheus.CreateAnnotation(), new morpheus.SimilarityMatrixTool(), new morpheus.TransposeTool(), new morpheus.TsneTool(),
    new morpheus.DevAPI()].forEach(function (tool) {
    _this.add({
      ellipsis: true,
      name: tool.toString(),
      gui: function () {
        return tool;
      },
      cb: function (options) {
        morpheus.HeatMap.showTool(tool, options.heatMap);
      }
    });
  });
  this.add({
    name: 'Edit Fonts',
    ellipse: true,
    cb: function (options) {
      var trackInfo = options.heatMap.getLastSelectedTrackInfo();
      var project = options.heatMap.getProject();
      var model = trackInfo.isColumns ? project
        .getColumnFontModel() : project
        .getRowFontModel();
      var chooser = new morpheus.FontChooser({
        fontModel: model,
        track: options.heatMap.getTrack(trackInfo.name, trackInfo.isColumns),
        heatMap: options.heatMap
      });
      morpheus.FormBuilder.showInModal({
        title: 'Edit Fonts',
        html: chooser.$div,
        close: 'Close',
        focus: options.heatMap.getFocusEl()
      });
    }
  });

};
morpheus.ActionManager.prototype = {
  getActions: function () {
    return this.actions;
  },
  getAction: function (name) {
    return this.actionNameToAction.get(name);
  },
  execute: function (name, args) {
    var action = this.getAction(name);
    if (args == null) {
      args = {};
    }

    args.heatMap = this.heatMap;
    action.cb(args);

    morpheus.Util.trackEvent({
      eventCategory: 'Tool',
      eventAction: name
    });
  },
  add: function (action) {
    this.actions.push(action);
    this.actionNameToAction.set(action.name, action);
  }
};