text:
/* $Id$ */

package org.apache.fop.render;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.xmlgraphics.util.Service;

/**
 * This class holds references to various XML handlers used by FOP. It also
 * supports automatic discovery of additional XML handlers available through
 * the class path.
 */
public class XMLHandlerRegistry {

    /** the logger */
    private static Log log = LogFactory.getLog(XMLHandlerRegistry.class);

    /** Map containing XML handlers for various document types */
    private Map<String, List<XMLHandler>> handlers
    = new java.util.HashMap<String, List<XMLHandler>>();

    /**
     * Default constructor.
     */
    public XMLHandlerRegistry() {
        discoverXMLHandlers();
    }

    /**
     * Add a default XML handler which is able to handle any namespace.
     * @param handler XMLHandler to use
     */
    private void setDefaultXMLHandler(XMLHandler handler) {
        addXMLHandler(XMLHandler.HANDLE_ALL, handler);
    }

    /**
     * Add an XML handler. The handler itself is inspected to find out what it supports.
     * @param classname the fully qualified class name
     */
    public void addXMLHandler(String classname) {
        try {
            XMLHandler handlerInstance = (XMLHandler)Class.forName(classname).getDeclaredConstructor().newInstance();
            addXMLHandler(handlerInstance);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Could not find "
                                               + classname);
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("Could not instantiate "
                                               + classname);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("Could not access "
                                               + classname);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(classname
                                               + " is not an "
                                               + XMLHandler.class.getName());
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Add an XML handler. The handler itself is inspected to find out what it supports.
     * @param handler the XMLHandler instance
     */
    public void addXMLHandler(XMLHandler handler) {
        String ns = handler.getNamespace();
        if (ns == null) {
            setDefaultXMLHandler(handler);
        } else {
            addXMLHandler(ns, handler);
        }
    }

    /**
     * Add an XML handler for the given MIME type and XML namespace.
     * @param ns Namespace URI
     * @param handler XMLHandler to use
     */
    private void addXMLHandler(String ns, XMLHandler handler) {
        List<XMLHandler> lst = handlers.get(ns);
        if (lst == null) {
            lst = new java.util.ArrayList<XMLHandler>();
            handlers.put(ns, lst);
        }
        lst.add(handler);
    }

    /**
     * Returns an XMLHandler which handles an XML dialect of the given namespace and for
     * a specified output format defined by its MIME type.
     * @param renderer the Renderer for which to retrieve a Renderer
     * @param ns the XML namespace associated with the XML to be rendered
     * @return the XMLHandler responsible for handling the XML or null if none is available
     */
    public XMLHandler getXMLHandler(Renderer renderer, String ns) {
        XMLHandler handler;

        List<XMLHandler> lst = handlers.get(ns);
        handler = getXMLHandler(renderer, lst);
        if (handler == null) {
            lst = handlers.get(XMLHandler.HANDLE_ALL);
            handler = getXMLHandler(renderer, lst);
        }
        return handler;
    }

    private XMLHandler getXMLHandler(Renderer renderer, List<XMLHandler> lst) {
        XMLHandler handler;
        if (lst != null) {
            for (XMLHandler aLst : lst) {
                //TODO Maybe add priorities later
                handler = aLst;
                if (handler.supportsRenderer(renderer)) {
                    return handler;
                }
            }
        }
        return null; //No handler found
    }

    /**
     * Discovers XMLHandler implementations through the classpath and dynamically
     * registers them.
     */
    private void discoverXMLHandlers() {
        // add mappings from available services
        Iterator<Object> providers = Service.providers(XMLHandler.class);
        if (providers != null) {
            while (providers.hasNext()) {
                XMLHandler handler = (XMLHandler)providers.next();
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Dynamically adding XMLHandler: " + handler.getClass().getName());
                    }
                    addXMLHandler(handler);
                } catch (IllegalArgumentException e) {
                    log.error("Error while adding XMLHandler", e);
                }

            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.nitorcreations.willow.auth;

import java.util.Locale;
import java.util.TreeSet;

import javax.inject.Singleton;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class PublicKeyAuthenticationFilter extends BasicHttpAuthenticationFilter {
  private static final Logger log = LoggerFactory.getLogger(PublicKeyAuthenticationFilter.class);
  private final TreeSet<Long> timeStamps = new TreeSet<>();
  private static final String scheme = "PUBLICKEY";
  public PublicKeyAuthenticationFilter() {
    this.setAuthcScheme(scheme);
    this.setAuthzScheme(scheme);
  }
  @Override
  protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
    String authorizationHeader = getAuthzHeader(request);
    if (authorizationHeader == null || authorizationHeader.length() == 0) {
      return createToken("", null, null, request);
    }

    if (log.isDebugEnabled()) {
      log.debug("Attempting to execute login with headers [" + authorizationHeader + "]");
    }

    String[] header = authorizationHeader.split("\\s+");
    if (header.length < 3 || !scheme.equals(header[0].toUpperCase(Locale.ENGLISH))) {
      return createToken("", null, null, request);
    }
    String[] unameNow = Base64.decodeToString(header[1]).split(":");
    String username = unameNow[0];
    long timestamp = Long.parseLong(unameNow[1]);
    long currentTime = System.currentTimeMillis();
    long wStart = currentTime - 15000;
    long wEnd = currentTime + 15000;
    if (!(timestamp > wStart && timestamp < wEnd) || timeStamps.contains(timestamp)) {
      return createToken("", null, null, request);
    }
    timeStamps.add(timestamp);
    while (timeStamps.first() < wStart) {
      timeStamps.pollFirst();
    }
    PublicKeyAuthenticationToken token = createToken(username, Base64.decode(header[1]), Base64.decode(header[2]), request);
    for (int i=3; i<header.length;i++) {
      token.addSignature(Base64.decode(header[i]));
    }
    return token;
  }
  protected PublicKeyAuthenticationToken createToken(String username, byte[] sign, byte[] signature, ServletRequest request) {
    return new PublicKeyAuthenticationToken(username, sign, signature, getHost(request));
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using KeyPay.DomainModels.V2;
using KeyPay.DomainModels.V2.Business;
using KeyPay.DomainModels.V2.Employee;
using KeyPay.DomainModels.V2.Manager;
using RestSharp;

namespace KeyPay.ApiFunctions.V2
{
    public class ManagerLeaveRequestsFunction : BaseFunction
    {
        public ManagerLeaveRequestsFunction(ApiRequestExecutor api) : base(api)
        {
        }

        public List<ManagerLeaveRequestModel> List(int businessId, ManagerLeaveRequestFilterModel filter)
        {
            var queryString = new StringBuilder("?");
            if (filter.Status.HasValue) queryString.Append($"Status={filter.Status.ToString()}&");
            if (filter.FromDate.HasValue) queryString.Append($"FromDate={filter.FromDate.Value.ToString("yyyy-MM-dd")}&");
            if (filter.ToDate.HasValue) queryString.Append($"ToDate={filter.ToDate.Value.ToString("yyyy-MM-dd")}&");
            if (filter.LeaveCategoryId.HasValue) queryString.Append($"LeaveCategoryId={filter.LeaveCategoryId}&");
            if (filter.LocationId.HasValue) queryString.Append($"LocationId={filter.LocationId}&");
            if (filter.EmployeeId.HasValue) queryString.Append($"EmployeeId={filter.EmployeeId}&");

            return ApiRequest<List<ManagerLeaveRequestModel>>($"/business/{businessId}/manager/leaverequest{queryString}");
        }

        public List<ManagerLeaveRequestModel> Overlapping(int businessId, DateTime fromDate, DateTime toDate)
        {
            return ApiRequest<List<ManagerLeaveRequestModel>>($"/business/{businessId}/manager/leaverequest/overlapping?fromDate={fromDate.ToString("yyyy-MM-dd")}&toDate={toDate.ToString("yyyy-MM-dd")}");
        }

        public List<ManagerLeaveRequestModel> Overlapping(int businessId, int employeeId, int leaveRequestId)
        {
            return ApiRequest<List<ManagerLeaveRequestModel>>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}/overlapping");
        }

        public ManagerLeaveRequestModel Get(int businessId, int employeeId, int leaveRequestId)
        {
            return ApiRequest<ManagerLeaveRequestModel>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}");
        }

        public ManagerLeaveRequestModel Create(int businessId, int employeeId, ManagerLeaveApplicationModel leaveApplicationModel)
        {
            return ApiRequest<ManagerLeaveRequestModel, ManagerLeaveApplicationModel>($"/business/{businessId}/manager/{employeeId}/leaverequest", leaveApplicationModel, Method.Post);
        }

        public ManagerLeaveRequestModel Update(int businessId, int employeeId, int leaveRequestId, ManagerLeaveApplicationModel leaveApplicationModel)
        {
            return ApiRequest<ManagerLeaveRequestModel, ManagerLeaveApplicationModel>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}", leaveApplicationModel, Method.Post);
        }

        public ManagerLeaveRequestModel Approve(int businessId, int employeeId, int leaveRequestId)
        {
            return ApiRequest<ManagerLeaveRequestModel>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}/approve", Method.Post);
        }

        public ManagerLeaveRequestModel Decline(int businessId, int employeeId, int leaveRequestId, string reason)
        {
            return ApiRequest<ManagerLeaveRequestModel, DeclineReason>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}/decline", new DeclineReason { Reason = reason }, Method.Post);
        }

        public ManagerLeaveRequestModel Cancel(int businessId, int employeeId, int leaveRequestId)
        {
            return ApiRequest<ManagerLeaveRequestModel>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}", Method.Delete);
        }

        public DocumentFile Attachment(int businessId, int employeeId, int leaveRequestId)
        {
            return ApiRequest<DocumentFile>($"/business/{businessId}/manager/{employeeId}/leaverequest/{leaveRequestId}/attachment");
        }

        public List<LeaveBalanceModel> Balances(int businessId, int employeeId, DateTime? asAtDate)
        {
            var queryString = asAtDate.HasValue
                ? $"?asAtDate={asAtDate.Value.ToString("yyyy-MM-dd")}"
                : "";
            return ApiRequest<List<LeaveBalanceModel>>($"/business/{businessId}/manager/{employeeId}/leaverequest/balances{queryString}");
        }

        public ManagerLeaveEstimateModel Estimate(int businessId, int employeeId, DateTime fromDate, DateTime toDate, int leaveCategoryId)
        {
            return ApiRequest<ManagerLeaveEstimateModel>($"/business/{businessId}/manager/{employeeId}/leaverequest/estimate?fromDate={fromDate.ToString("yyyy-MM-dd")}&toDate={toDate.ToString("yyyy-MM-dd")}&leaveCategoryId={leaveCategoryId}");
        }

        public List<ManagerLeaveCategoryModel> Categories(int businessId)
        {
            return ApiRequest<List<ManagerLeaveCategoryModel>>($"/business/{businessId}/manager/leaverequest/categories");
        }

        public List<ManagerLeaveEmployeeModel> Employees(int businessId)
        {
            return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/leaverequest/employees");
        }

        public List<LocationModel> Locations(int businessId)
        {
            return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/leaverequest/locations");
        }

        public List<ManagerLeaveCategoryModel> Categories(int businessId, int employeeId)
        {
            return ApiRequest<List<ManagerLeaveCategoryModel>>($"/business/{businessId}/manager/{employeeId}/leaverequest/categories");
        }

    }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Model_Discussion extends ORM {

    protected $_belongs_to = array('image' => array('model' => 'Image', 'foreign_key' => 'image_id'));
    protected $_has_many = array('comments' => array('model' => 'Comment', 'foreign_key' => 'discussion_id'));

    function create_new(){
        $discussion = Model::factory('Discussion');
        $discussion->save();
        return $discussion->id;
    }
}


text:
from rest_framework import serializers

from huxley.api import validators
from huxley.core.models import CommitteeFeedback

class CommitteeFeedbackSerializer(serializers.ModelSerializer):
    class Meta:
        model = CommitteeFeedback
        fields = ('id',
                  'committee',
                  'comment',
                  'rating',
                  'chair_1_name',
                  'chair_2_name',
                  'chair_3_name',
                  'chair_4_name',
                  'chair_5_name',
                  'chair_6_name',
                  'chair_7_name',
                  'chair_8_name',
                  'chair_9_name',
                  'chair_10_name',
                  'chair_1_comment',
                  'chair_2_comment',
                  'chair_3_comment',
                  'chair_4_comment',
                  'chair_5_comment',
                  'chair_6_comment',
                  'chair_7_comment',
                  'chair_8_comment',
                  'chair_9_comment',
                  'chair_10_comment',
                  'chair_1_rating',
                  'chair_2_rating',
                  'chair_3_rating',
                  'chair_4_rating',
                  'chair_5_rating',
                  'chair_6_rating',
                  'chair_7_rating',
                  'chair_8_rating',
                  'chair_9_rating',
                  'chair_10_rating',
                  'berkeley_perception',
                  'money_spent')


text:
$LOAD_PATH.unshift('./lib/')

require 'collins_auth'
require 'optparse'
require 'yaml'
require 'consolr/version'

module Consolr
  class Console

    attr_reader :ipmitool_exec, :dangerous_assets, :dangerous_status, :dangerous_actions, :options, :opt_parser

    def initialize
      config_file = [ENV['CONSOLR_CONFIG'],
                      '~/.consolr.yml', '~/.consolr.yaml',
                      '/etc/consolr.yml', '/etc/consolr.yaml',
                      '/var/db/consolr.yml', '/var/db/consolr.yaml'].compact.find do |conf|
        File.readable?(File.expand_path(conf, __FILE__)) and File.size(File.expand_path(conf, __FILE__)) > 0
      end

      config_params = begin
        YAML.load(File.open(File.expand_path(config_file, __FILE__)))
      rescue TypeError => e
        puts "-------"
        puts "Failed to load Configuration File ... "
        puts "Looks like a configuration file doesn't exist."
        puts "Please look at README.md on creating a configuration file"
        puts "-------"
        exit 1
      rescue ArgumentError => e
        puts "------"
        puts "Failed to load Configuration File ... "
        puts "Looks like the configuration file is not correctly formatted"
        puts "Please check if your file conforms to YAML spec"
        puts "------"
        exit 1
      end

      begin
        @ipmitool_exec = config_params['ipmitool'] # ipmitool absolute path
      rescue Exception => e
        puts e
        puts "-------"
        puts "Ensure that the ipmitool's path (#{@ipmitool_exec}) is given in the consolr.yml file and is correct"
        puts "-------"
        exit 1
      end

      # Will be ignored for dangerous actions, no matter what, even with --force
      begin
        @dangerous_assets = config_params['dangerous_assets']
      rescue Exception => e
        puts e
        puts "-------"
        puts "Dangerous Assets -- #{dangrous}"
        puts "Please make sure dangerous_assets exists and is valid."
        puts "Supply them in a comma separated list."
        puts "-------"
        exit 1
      end

      # Dangerous actions wont be run in these status, override with --force
      begin
        @dangerous_status = config_params['dangerous_status']
      rescue Exception => e
        puts e
        puts "-------"
        puts "Dangerous Status -- #{@dangeous_status}"
        puts "Please specify the statuses which are dangerorous, during which dangerous shouldn't be run."
        puts "-------"
        exit 1
      end

      @dangerous_actions = [:off, :reboot] # Must match the symbol in options{}

      @options = {}
      @opt_parser = OptionParser.new do |opt|
        opt.banner = 'Usage: consolr [OPTIONS]'
        opt.separator  ''
        opt.separator  'Options'

        opt.on('-c', '--console', 'console into node via SOL') { options[:console] = true }
        opt.on('-d', '--dangerous', 'list dangerous stuff') { options[:dangerous] = true }
        opt.on('-f', '--force', 'force run dangerous actions') { options[:force] = true }
        opt.on('-H', '--hostname ASSET', 'asset hostname') { |hostname| options[:hostname] = hostname }
        opt.on('-i', '--identify', 'turn on chassis UID') { options[:identify] = true }
        opt.on('-k', '--kick', 'kick if someone is hogging the console') { options[:kick] = true }
        opt.on('-l', '--log LOG', 'System Event Log (SEL) [list|clear]') { |log| options[:log] = log }
        opt.on('-o', '--on', 'turn on node') { options[:on] = true }
        opt.on('-r', '--reboot', 'restart node') { options[:reboot] = true }
        opt.on('-s', '--sdr', 'Sensor Data Repository (SDR)') { options[:sdr] = true }
        opt.on('-t', '--tag ASSET', 'asset tag') { |tag| options[:tag] = tag }
        opt.on('-x', '--off', 'turn off node') { options[:off] = true }
        opt.on_tail('-h', '--help', 'help') { puts opt; exit 0 }
        opt.on_tail('-v', '--version', 'version') { puts Consolr::VERSION; exit 0 }
      end
    end

    def ipmitool_cmd action
      system("#{@ipmitool_exec} -I lanplus -H #{@node.ipmi.address} -U #{@node.ipmi.username} -P #{@node.ipmi.password} #{action}")
      return $?.exitstatus == 0 ? "SUCCESS" : "FAILED"
    end

    def start
      @opt_parser.parse! # extract from ARGV[]
      abort("Please pass either the asset tag or hostname") if options[:tag].nil? and options[:hostname].nil?

      abort("Cannot find #{@ipmitool_exec}") unless File.exist?(@ipmitool_exec)

      dangerous_body = "Dangerous actions: #{dangerous_actions.join(', ')}\n"\
        "Dangerous status: #{dangerous_status.join(', ')} (override with --force)\n"\
        "Dangerous assets: #{dangerous_assets.join(', ')} (ignored no matter what, even with --force)"

      if options[:dangerous]
        puts dangerous_body
        exit 1
      end

      begin
        collins = Collins::Authenticator.setup_client
      rescue Exception => e
        puts e
        puts "-------"
        puts "There was a problem setting up a connection with Collins."
        puts "-------"
        exit 1
      end

      if options[:tag] and options[:hostname]
        abort("Please pass either the hostname OR the tag but not both.")
      end

      # match assets like vm-67f5eh, zt-*, etc.
      nodes = options[:tag] ? (collins.find :tag => options[:tag]) : (collins.find :hostname => options[:hostname])
      @node = nodes.length == 1 ? nodes.first : abort("Found #{nodes.length} assets, aborting.")

      %x(/bin/ping -c 1 #{@node.ipmi.address})
      abort("Cannot ping IP #{@node.ipmi.address} (#{@node.tag})") unless $?.exitstatus == 0

      if dangerous_assets.include?(@node.tag) and dangerous_actions.any?
        puts "Asset #{@node.tag} is a crucial asset. Can't execute dangerous actions on this asset."
      end

      if options[:force].nil? and dangerous_actions.any? and dangerous_status.include?(@node.status)
        puts "Cannot run dangerous commands on #{@node.hostname} (#{@node.tag} - #{@node.status})"
        abort dangerous_body
      end

      case
      when options[:console]
        puts '--> Opening SOL session (type ~~. to quit)'
        puts ipmitool_cmd('sol activate')
      when options[:kick]
        puts ipmitool_cmd('sol deactivate')
      when options[:identify]
        puts ipmitool_cmd('chassis identify')
      when options[:sdr]
        puts ipmitool_cmd('sdr elist all')
      when options[:log] == 'list'
        puts ipmitool_cmd('sel list')
      when options[:log] == 'clear'
        puts ipmitool_cmd('sel clear')
      when options[:on]
        puts ipmitool_cmd('power on')
      when options[:off]
        puts ipmitool_cmd('power off')
      when options[:reboot]
        puts ipmitool_cmd('power cycle')
      else
        begin
          raise OptionParser::MissingArgument, "specify an action"
        rescue OptionParser::MissingArgument => e
          puts e
          puts @opt_parser
          exit 0
        end
      end
    end

  end

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
		"http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>doh.robot Editor FontChoice Plugin Test</title>

		<style>
			@import "../../../../util/doh/robot/robot.css";
		</style>

		<!-- required: dojo.js -->
		<script type="text/javascript" src="../../../../dojo/dojo.js"
			djConfig="isDebug: true, parseOnLoad: true"></script>

		<!-- functions to help test -->
		<script type="text/javascript" src="../../helpers.js"></script>

		<script type="text/javascript">
			dojo.require("dojo.DeferredList");
			dojo.require("dojo.window");
			dojo.require("dijit.robotx");

			dojo.addOnLoad(function(){
				doh.robot.initRobot('../test_FontChoice.html');

				var editor;		// points to one of the editors (editor0, editor1, etc.)
				var fcPlugin;	// formatBlock, fontSize, or fontName plugin
				var value;		// HTML value of editor

				function getPlugin(/*String*/ command){
					var editor = dijit.byId("editor0");
					var edPlugins = editor._plugins, i;
					for(i = 0; i < edPlugins.length; i++){
						var p = edPlugins[i];
						if (p.declaredClass === "dijit._editor.plugins.FontChoice" && p.command == command) {
							return p;
						}
					}
					doh.f(true, "didn't find plugin " + command);
				}

				doh.register("init", {
					name: "wait for editors to load",
					timeout: 5000,
					runTest: function(){
					    return new dojo.DeferredList(
					        dijit.registry.filter(function(w){ return w.onLoadDeferred; }).map(function(w){ return w.onLoadDeferred; })
					    );
					}
				});

				// Verify that the formatBlock, fontSize, and fontName
				// plugins correctly display the format / font-size / font-name of the selected text.

				doh.register("FontChoice: verify current format/font-size/font-name",
					dojo.map(
						[
							{id: "para0", format: "p"},
							{id: "pre0", format: "pre"},
							{id: "h10", format: "h1"},
							{id: "h20", format: "h2"},
							{id: "h30", format: "h3"},
							{id: "sizedText1", size: "1"},
							{id: "sizedText4", size: "4"},
							{id: "sizedText7", size: "7"},
							{id: "comicText", name: "Comic Sans MS"}
						],
						function(params){
							return {
								name: [
										"Verify",
										params.format ? "format " + params.format.toUpperCase() : "",
										params.size ? "font size " + params.size : "",
										params.name ? "font name " + params.name : "",
										"Identified"
									].join(" ").replace(/ +/g, " "),
								timeout: 20000,
								setUp: function(){
									editor = dijit.byId("editor0");
									value = editor.get("value");
								},
								runTest: function(){
									var d = new doh.Deferred();

									// Focus on the editor window
									dojo.window.scrollIntoView(editor.domNode);
									editor.focus();
									doh.robot.mouseMoveAt(editor.iframe, 1000);
									doh.robot.mouseClick({left:true}, 1000);

									doh.robot.sequence(d.getTestErrback(function() {
										// Find node w/specified id
										var node = dojo.withGlobal(editor.window, function() { return dojo.byId(params.id); });
										doh.is(params.id, node && node.id, "found " + params.id);

										// Select the text, collapse to the start of it
										// Using "dojo.global.dojo" to access the inner dojo, in test_FontChoice.html
										// (not the one in this file), since that's the one that dijit is referencing.
										dojo.global.dojo.withGlobal(editor.window, function() {
											dijit._editor.selection.selectElementChildren(node);
											dijit._editor.selection.collapse(true);
										});
									}),1000);
					                doh.robot.sequence(d.getTestErrback(function(){
										// Make sure states update.
										editor.onDisplayChanged();
									}), 1000);
									doh.robot.sequence(d.getTestCallback(function(){
										if(params.format){
											doh.is(params.format, getPlugin("formatBlock").button.get("value"), "format " + params.format + " identified.");
										}
										if(params.size){
											doh.is(params.size, getPlugin("fontSize").button.get("value"), "font size " + params.size + " identified.");
										}
										if(params.name){
											doh.is(params.name, getPlugin("fontName").button.get("value"), "font name" + params.name + " identified.");
										}
									}), 2000);

									return d;
								},
								tearDown: function(){
									if(editor){editor.set("value", value);}
								}
							};	// end of return { ...
						}	// end of function()
					)	// end of dojo.map()
				);	// end of dojo.register()

				// Test changing format/font-size/font-name (ex: changing an <h1> to an <h2>)
				doh.register("FontChoice: change format/font-size/font",
					dojo.map(
						[
							{id: "text", type: "formatBlock", from: "p", to: "pre"},
							{id: "text", type: "formatBlock", from: "pre", to: "h1"},
							{id: "text", type: "formatBlock", from: "h1", to: "h2"},
							{id: "text", type: "formatBlock", from: "h2", to: "h3"},
							{id: "sizedText7", type: "fontSize", from: "7", to: "3"},
							{id: "comicText", type: "fontName", from: "Comic Sans MS", to: "Times New Roman"}
						],
						function(params){
							return {
								name: "formatBlock: Verify can change " + params.type + " " +
									params.from.toUpperCase() + " to " + params.to.toUpperCase(),
								timeout: 20000,
								setUp: function(){
									fcPlugin = getPlugin(params.type);
									value = editor.get("value");
								},
								runTest: function(){
									var d = new doh.Deferred();

									// Focus on the editor window
									dojo.window.scrollIntoView(editor.domNode);
									editor.focus();
									doh.robot.mouseMoveAt(editor.iframe, 1000);
									doh.robot.mouseClick({left:true}, 1000);

									doh.robot.sequence(d.getTestErrback(function(){
										// Find node
										var p = dojo.withGlobal(editor.window, function() { return dojo.byId(params.id); });
										doh.is(params.id, p && p.id, "found node");

										dojo.global.dojo.withGlobal(editor.window, function() {
											// Select the text, collapse to the start of it
											dijit._editor.selection.selectElementChildren(p);
											// Disable collapse.  Webkit changed behavior so it now requires
											// a selection.
											if(!dojo.isWebKit){ dijit._editor.selection.collapse(true) };

											// Set the format / font-size / font-name plugin to the new value
											// TODO: use mouse/keyboard to set the value
											fcPlugin.button.set("value", params.to);
										});
									}),1000);
					                doh.robot.sequence(d.getTestErrback(function(){
										// Make sure states update.
										editor.onDisplayChanged();
									}), 1000);
									doh.robot.sequence(d.getTestCallback(function(){
										doh.is(params.to, fcPlugin.button.get("value"), "verify converted");

										// TODO: check that it actually changed the format / font-size / font-name (in the editor contents)
									}), 2000);

									return d;
								},
								tearDown: function(){
									if(editor){editor.set("value", value);}
								}
							};	// end of return { ...
						}	// end of function()
					)	// end of dojo.map()
				);	// end of dojo.register()

				doh.register("formatBlock: multiple changes",
					{
						name: "formatBlock: Verify changing multiple nodes to h3",
						timeout: 20000,
						setUp: function(){
							editor = dijit.byId("editor0");
							fcPlugin = getPlugin("formatBlock");
							value = editor.get("value");
						},
						runTest: function(){
							var d = new doh.Deferred();

							// Focus on the editor window
							dojo.window.scrollIntoView(editor.domNode);
							editor.focus();
							doh.robot.mouseMoveAt(editor.iframe, 1000);
							doh.robot.mouseClick({left:true}, 1000);

							// Verify the formatBlock plugin was found
							doh.t(fcPlugin !== null, "formatBlock was found");

							doh.robot.sequence(d.getTestErrback(function(){
								var p = dojo.withGlobal(editor.window, function() { return dojo.byId("text"); });
								doh.is("text", p && p.id, "found text");

								dojo.global.dojo.withGlobal(editor.window, function() {
									// Select the text, collapse to the start of it
									dijit._editor.selection.selectElementChildren(p);
									dijit._editor.selection.collapse(true);

									// Set the format / font-size / font-name plugin to the new value
									// TODO: use mouse/keyboard to set the value
									fcPlugin.button.set("value", "h3");
								});
							}),1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Make sure states update.
								editor.onDisplayChanged();
							}), 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								doh.is("h3", fcPlugin.button.get("value"), "Verify first P converted to H3.");
								// TODO: check that it actually changed the format (in the editor contents)
							}), 2000);

							// Move to the next block and try to change it to h3 too.
							doh.robot.sequence(d.getTestErrback(function(){
								var p = dojo.withGlobal(editor.window, function() { return dojo.byId("text1"); });
								doh.is("text1", p && p.id, "found text1");

								dojo.global.dojo.withGlobal(editor.window, function() {
									// Select the text, collapse to the start of it
									dijit._editor.selection.selectElementChildren(p);
									dijit._editor.selection.collapse(true);

									// Set the format / font-size / font-name plugin to the new value
									// TODO: use mouse/keyboard to set the value
									fcPlugin.button.set("value", "h3");
								});
							}),1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Make sure states update.
								editor.onDisplayChanged();
							}), 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// state should have updated, so, now set value.
								// TODO: use mouse/keyboard to set the value
								fcPlugin.button.set("value", "h3");
							}),1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Make sure states update.
								editor.onDisplayChanged();
							}), 1000);
							doh.robot.sequence(d.getTestCallback(function(){
								doh.is("h3", fcPlugin.button.get("value"), "Verify second P converted to H3.");
								// TODO: check that it actually changed the format (in the editor contents)
							}), 2000);

							return d;
						},
						tearDown: function(){
							if(editor){editor.set("value", value);}
						}
					}
				);

				doh.register("FontChoice: Format Removal Tests", [
					{
						name: "formatBlock: Verify single level format is removed (inside format block).",
						timeout: 20000,
						setUp: function(){
							editor = dijit.byId("editor0");
							fcPlugin = getPlugin("formatBlock");
							value = editor.get("value");
						},
						runTest: function(){
							var d = new doh.Deferred();

							// Focus on the editor window
							dojo.window.scrollIntoView(editor.domNode);
							editor.focus();
							doh.robot.mouseMoveAt(editor.iframe, 1000);
							doh.robot.mouseClick({left:true}, 1000);

							// Verify the formatBlock plugin was found
							doh.t(fcPlugin !== null, "formatBlock was found");

							doh.robot.sequence(d.getTestErrback(function(){
								var p = dojo.withGlobal(editor.window, function() { return dojo.byId("text"); });
								doh.is("text", p && p.id, "found text");
								dojo.global.dojo.withGlobal(editor.window, function() {
									// Select the text, collapse to the start of it
									dijit._editor.selection.selectElementChildren(p);
									dijit._editor.selection.collapse(true);
								});
							}),1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Make sure states update.
								editor.onDisplayChanged();
							}), 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								fcPlugin.button.set("value", "noFormat");
							}), 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Make sure states update.
								// If change occurred, then the value should
								// still be noFormat.
								editor.onDisplayChanged();
							}), 1000);
							doh.robot.sequence(d.getTestCallback(function(){
                                doh.is("noFormat", fcPlugin.button.get("value"),
									"Validating current cursor point format is noFormat");
							}), 1000);

							return d;
						},
						tearDown: function(){
							if(editor){editor.set("value", value);}
						}
					},
					{
						name: "formatBlock: Verify multiple format removal via selection",
						timeout: 20000,
						setUp: function(){
							editor = dijit.byId("editor0");
							fcPlugin = getPlugin("formatBlock");
							value = editor.get("value");
						},
						runTest: function(){
							var d = new doh.Deferred();

							// Focus on the editor window
							dojo.window.scrollIntoView(editor.domNode);
							editor.focus();
							doh.robot.mouseMoveAt(editor.iframe, 1000);
							doh.robot.mouseClick({left:true}, 1000);

							// Verify the formatBlock plugin was found
							doh.t(fcPlugin !== null, "formatBlock was found");

							doh.robot.sequence(d.getTestErrback(function(){
								var p = dojo.withGlobal(editor.window, function() { return dojo.byId("text"); });
								doh.is("text", p && p.id, "found text");
								dojo.global.dojo.withGlobal(editor.window, function() {
									// Select the text, collapse to the start of it
									dijit._editor.selection.selectElementChildren(p);
									dijit._editor.selection.collapse(true);
								});
							}),1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Make sure states update.
								editor.onDisplayChanged();
							}), 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								// Select the children of the block and try to flatten the formatting.

								var selection = dojo.withDoc(editor.document, function() { return dojo.byId("selectionContainer"); });
								dojo.global.dojo.withGlobal(editor.window, function() {
									dojo.window.scrollIntoView(selection);
									dijit._editor.selection.selectElementChildren(selection);
								});
								fcPlugin.button.set("value", "noFormat");
							}), 1000);
							doh.robot.sequence(d.getTestCallback(function(){
								// Now check that the elements are all gone.
								var selection = dojo.withDoc(editor.document, function() { return dojo.byId("selectionContainer"); });
								doh.t(selection.childNodes.length > 0, "Checking that there are still child nodes.");

								var i;
								var nodes = selection.childNodes;
								for(i = 0; i < nodes.length; i++){
									var n = nodes[i];
									if(n.nodeType == 1){
										var tag = n.nodeName? n.nodeName.toLowerCase() : "";
										doh.t(tag != "p");
										doh.t(tag != "h3");
										doh.t(tag != "pre");
									}
								}
							}), 1000);

							return d;
						},
						tearDown: function(){
							if(editor){editor.set("value", value);}
						}
					}
				]);

				doh.register("FontChoice: miscellaneous tests", [
					{
						name: "FontChoice: Plain Text labels",
						timeout: 20000,
						setUp: function(){
							editor = dijit.byId("editor1");
							fcPlugin = [];
							var edPlugins = editor._plugins, i;
							for(i = 0; i < edPlugins.length; i++){
								var p = edPlugins[i];
								if(p.declaredClass === "dijit._editor.plugins.FontChoice"){
									fcPlugin.push(p);
								}
							}
							value = editor.get("value");
						},
						runTest: function(){
							// summary:
							//		This test goes through all the registered FontChoice plugins
							//		and verifies that they're all using plain text labels in the dropdown.
							var d = new doh.Deferred();

							// Focus on the editor window
							dojo.window.scrollIntoView(editor.domNode);
							editor.focus();
							doh.robot.mouseMoveAt(editor.iframe, 1000);
							doh.robot.mouseClick({left:true}, 1000);
							doh.robot.sequence(function(){
								var i, passed = true, processed = 0;
								for(i = 0; i < fcPlugin.length; i++){
									var p = fcPlugin[i];
									var store = p.button.select.store;
									var onComplete = function(items){
										try{
											var j;
											processed++;
											for(j = 0; j < items.length; j++){
												var item = items[j];
												if(store.getValue(item, "name").indexOf("<") === 0){
													console.log("failed on: " + store.getValue(item, "name"));
													passed = false;
												}
											}
											if(processed === fcPlugin.length){
												if(passed){
													d.callback(true);
												}else{
													d.errback(new Error("Non-plain text label!"));
												}
											}
										}catch(e){
											d.errback(e);
										}
									};
									var onError = function(err){
										d.errback(err);
									}
									store.fetch({query: {name: "*"}, onComplete: onComplete, onError: onError});
								}
							}, 1000);

							return d;
						},
						tearDown: function(){
							if(editor){editor.set("value", value);}
						}
					},
					{
						name: "FontChoice: Validate usage of generic names",
						timeout: 20000,
						setUp: function(){
							editor = dijit.byId("generic");
							fcPlugin = null;
							var edPlugins = editor._plugins, i;
							for(i = 0; i < edPlugins.length; i++){
								var p = edPlugins[i];
								if(p.declaredClass === "dijit._editor.plugins.FontChoice" && p.command === "fontName" && p.generic){
									fcPlugin = p;
								}
							}
							value = editor.get("value");
						},
						runTest: function(){
							// summary:
							//		This test goes through the font choice plugin registered as generic font names and validates
							//		the font names in the values are the generic map.
							var d = new doh.Deferred();

							// Focus on the editor window
							dojo.window.scrollIntoView(editor.domNode);
							editor.focus();
							doh.robot.mouseMoveAt(editor.iframe, 1000);
							doh.robot.mouseClick({left:true}, 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								var i, passed = true;
								var map = {
									"sans-serif": false,
									"serif": false,
									"cursive": false,
									"monospace": false,
									"fantasy": false
								}
								var store = fcPlugin.button.select.store;
								var onComplete = function(items){
									try{
										var j;
										for(j = 0; j < items.length; j++){
											var item = items[j];
											map[store.getValue(item, "value")] = true;
										}
										for(j in map){
											if(!map[j]){
												passed = false;
												break;
											}
										}
										if(passed){
											d.callback(true);
										}else{
											d.errback(new Error("Did not find all the generic names in the store."));
										}
									}catch(e){
										d.errback(e);
									}
								};
								var onError = function(err){
									d.errback(err);
								}
								store.fetch({query: {value: "*"}, onComplete: onComplete, onError: onError});
							}), 1000);

							return d;
						},
						tearDown: function(){
							if(editor){editor.set("value", value);}
						}
					},
					{
						name: "FontChoice: Validate custom font names",
						timeout: 20000,
						setUp: function(){
							editor = dijit.byId("custom");
							fcPlugin = null;
							var edPlugins = editor._plugins, i;
							for(i = 0; i < edPlugins.length; i++){
								var p = edPlugins[i];
								if(p.declaredClass === "dijit._editor.plugins.FontChoice" && p.command === "fontName" && p.custom){
									fcPlugin = p;
								}
							}
							value = editor.get("value");
						},
						runTest: function(){
							// summary:
							//		This test goes through the font choice plugin registered as custom font names and validates
							//		the font names in the values are the provided names.
							var d = new doh.Deferred();

							// Focus on the editor window
							dojo.window.scrollIntoView(editor.domNode);
							editor.focus();
							doh.robot.mouseMoveAt(editor.iframe, 1000);
							doh.robot.mouseClick({left:true}, 1000);
							doh.robot.sequence(d.getTestErrback(function(){
								var i, passed = true;
								var map = {
									"Verdana": false,
									"Myriad": false,
									"Garamond": false
								}
								var store = fcPlugin.button.select.store;
								var onComplete = function(items){
									try{
										var j;
										for(j = 0; j < items.length; j++){
											var item = items[j];
											map[store.getValue(item, "value")] = true;
										}
										for(j in map){
											if(!map[j]){
												passed = false;
												break;
											}
										}
										if(passed){
											d.callback(true);
										}else{
											d.errback(new Error("Did not find all the generic names in the store."));
										}
									}catch(e){
										d.errback(e);
									}
								};
								var onError = function(err){
									d.errback(err);
								}
								store.fetch({query: {value: "*"}, onComplete: onComplete, onError: onError});
							}), 1000);

							return d;
						},
						tearDown: function(){
							if(editor){editor.set("value", value);}
						}
					}
				]);
				doh.run();
			});
		</script>
	</head>
</html>


text:
<?php

namespace LosBaseTest\Controller;

use LosBaseTest\Assets\Controller\CrudController;
use Zend\Http\PhpEnvironment\Response;
use LosBaseTest\Assets\Entity\TestEntity;
use LosBaseTest\TestCase;
use LosBaseTest\ServiceManagerTestCase;

class AbstractCrudControllerTest extends TestCase
{
    private $controller;

    private $pluginManager;

    private $pluginManagerPlugins = [];

    protected function setUp()
    {
        parent::setUp();
        $this->controller = new CrudController();

        $sm = new ServiceManagerTestCase();
        $this->controller->setServiceLocator($sm->getServiceManager());

        $pluginManager = $this->getMock('Zend\Mvc\Controller\PluginManager', array(
            'get',
        ));

        $pluginManager->expects($this->any())
            ->method('get')
            ->will($this->returnCallback(array(
            $this,
            'helperMockCallbackPluginManagerGet',
        )));

        $this->pluginManager = $pluginManager;
        $this->controller->setPluginManager($pluginManager);
    }

    protected function tearDown()
    {
        $this->controller = null;

        parent::tearDown();
    }

    /**
     * Tests AbstractCrudController->getEntityService().
     */
    public function testGetEntityService()
    {
        $this->assertInstanceOf('LosBaseTest\Assets\Service\TestService', $this->controller->getEntityService());
    }

    /**
     * Tests AbstractCrudController->getRouteName().
     */
    public function testGetRouteName()
    {
        $this->assertSame('losbasetest', $this->controller->getRouteName());
    }

    /**
     * Tests AbstractCrudController->getEntityClass().
     */
    public function testGetEntityClass()
    {
        $this->assertSame('LosBaseTest\Assets\Entity\TestEntity', $this->controller->getEntityClass());
    }

    /**
     * Tests AbstractCrudController->getEntityServiceClass().
     */
    public function testGetEntityServiceClass()
    {
        $this->assertSame('LosBaseTest\Assets\Service\TestService', $this->controller->getEntityServiceClass());
    }

    /**
     * Tests AbstractCrudController->getForm().
     */
    public function testGetForm()
    {
        $this->helperAddUrlPlugin();

        $form = $this->controller->getForm();
        $this->assertSame('formTest', $form->getName());
        $this->assertTrue($form->has('name'));
        $this->assertTrue($form->has('csrf'));
        $this->assertTrue($form->has('submit'));
        $this->assertTrue($form->has('cancelar'));
    }

    /**
     * Tests AbstractCrudController->handleSearch().
     */
    public function testHandleSearch()
    {
        $qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();
        $this->controller->handleSearch($qb);
    }

    /**
     * Tests AbstractCrudController->listAction().
     */
    public function testListAction()
    {
        $this->helperAddUrlPlugin();
        $this->helperAddParamsPlugin();
        $this->addEntityManager();

        $ret = $this->controller->listAction();
    }

    /**
     * Tests AbstractCrudController->getActionRoute().
     */
    public function testGetActionRoute()
    {
        $this->assertSame('losbasetest/list', $this->controller->getActionRoute('list'));
    }

    /**
     * Tests AbstractCrudController->addAction().
     */
    public function testAddAction()
    {
        $this->helperAddUrlPlugin();
        $this->helperAddParamsPlugin();

        $event = $this->getMockBuilder('Zend\Mvc\MvcEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $event->expects($this->any())
            ->method('getRouteMatch')
            ->will($this->returnValue($event));
        $event->expects($this->any())
            ->method('getParam')
            ->will($this->returnValue('add'));
        $this->controller->setEvent($event);

        $ret = $this->controller->addAction();
        $this->assertArrayHasKey('entity', $ret);
        $this->assertArrayHasKey('entityForm', $ret);
        $this->assertInstanceOf('LosBaseTest\Assets\Entity\TestEntity', $ret['entity']);
        $this->assertInstanceOf('LosBase\Form\AbstractForm', $ret['entityForm']);
        $this->assertSame('name', $ret['entityForm']->get('name')
            ->getName());
    }

    /**
     * Tests AbstractCrudController->editAction().
     */
    public function testEditAction()
    {
        $this->helperAddUrlPlugin();
        $this->helperAddParamsPlugin();
        $this->addEntityManager();

        $event = $this->getMockBuilder('Zend\Mvc\MvcEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $event->expects($this->any())
            ->method('getRouteMatch')
            ->will($this->returnValue($event));
        $event->expects($this->any())
            ->method('getParam')
            ->will($this->returnValue('add'));
        $this->controller->setEvent($event);

        $ret = $this->controller->editAction();
        $this->assertArrayHasKey('entity', $ret);
        $this->assertArrayHasKey('entityForm', $ret);
        $this->assertInstanceOf('LosBaseTest\Assets\Entity\TestEntity', $ret['entity']);
        $this->assertInstanceOf('LosBase\Form\AbstractForm', $ret['entityForm']);
        $this->assertSame('name', $ret['entityForm']->get('name')
            ->getName());
    }

    /**
     * Tests AbstractCrudController->deleteAction().
     */
    public function testDeleteAction()
    {
        $this->helperAddUrlPlugin();
        $this->helperAddParamsPlugin();
        $this->helperAddFlashMessengerPlugin();
        $this->addEntityManager();

        $event = $this->getMockBuilder('Zend\Mvc\MvcEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $event->expects($this->any())
            ->method('getRouteMatch')
            ->will($this->returnValue($event));
        $event->expects($this->any())
            ->method('getParam')
            ->will($this->returnValue('add'));
        $this->controller->setEvent($event);

        $translator = $this->getMockBuilder('Zend\I18n\Translator\Translator')
            ->disableOriginalConstructor()
            ->getMock();
        $translator->expects($this->any())
            ->method('translate')
            ->will($this->returnValue(true));
        $this->controller->getServiceLocator()->setService('translator', $translator);

        $ret = $this->controller->deleteAction();
        $this->assertArrayHasKey('entity', $ret);
        $this->assertInstanceOf('LosBaseTest\Assets\Entity\TestEntity', $ret['entity']);
    }

    /**
     * Tests AbstractCrudController->indexAction().
     */
    public function testIndexAction()
    {
        $this->assertEmpty($this->controller->indexAction());
    }

    public function helperMockCallbackPluginManagerGet($key)
    {
        return (array_key_exists($key, $this->pluginManagerPlugins)) ? $this->pluginManagerPlugins[$key] : null;
    }

    public function helperAddUrlPlugin($return = '')
    {
        $response = new Response();
        $url = $this->getMock('Zend\Mvc\Controller\Plugin\Url', array(
            'fromRoute',
        ));
        $url->expects($this->any())
            ->method('fromRoute')
            ->will($this->returnValue($return));

        $this->pluginManagerPlugins['url'] = $url;
    }

    public function helperAddParamsPlugin($post = [], $query = [])
    {
        $params = $this->getMock('Zend\Mvc\Controller\Plugin\Params');
        $params->expects($this->any())
            ->method('__invoke')
            ->will($this->returnSelf());
        $params->expects($this->any())
            ->method('fromPost')
            ->will($this->returnCallback(function ($key, $default) use ($post) {
            return $post ?: $default;
        }));
        $params->expects($this->any())
            ->method('fromQuery')
            ->will($this->returnCallback(function ($key, $default) use ($query) {
            return $query ?: $default;
        }));
        $this->pluginManagerPlugins['params'] = $params;
    }

    public function helperAddFlashMessengerPlugin()
    {
        $flash = $this->getMockBuilder('Zend\Mvc\Controller\Plugin\FlashMessenger')
            ->disableOriginalConstructor()
            ->getMock();
        $flash->expects($this->any())
            ->method('addErrorMessage')
            ->will($this->returnValue($flash));

        $this->pluginManagerPlugins['flashMessenger'] = $flash;
    }

    public function addEntityManager()
    {
        $entity = new TestEntity();
        $rep = $this->getMockBuilder('Doctrine\ORM\EntityRepository')
            ->disableOriginalConstructor()
            ->getMock();
        $rep->expects($this->any())
            ->method('find')
            ->will($this->returnValue($entity));

        $emConf = $this->getMockBuilder('Doctrine\ORM\Configuration')
            ->disableOriginalConstructor()->getMock();
        $emConf->expects($this->any())
            ->method('getDefaultQueryHints')
            ->will($this->returnValue([]));

        $em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();
        $em->expects($this->any())
            ->method('getRepository')
            ->will($this->returnValue($rep));
        $em->expects($this->any())
            ->method('getConfiguration')
            ->will($this->returnValue($emConf));
        $em->expects($this->any())
            ->method('createQuery')
            ->will($this->returnValue(new \Doctrine\ORM\Query($em)));

        $qb = $this->getMock('Doctrine\ORM\QueryBuilder', ['add', 'orderBy', 'select', 'setFirstResult', 'setMaxResults'], [$em]);
        $qb->expects($this->any())
        ->method('add')
        ->will($this->returnValue($qb));
        $qb->expects($this->any())
        ->method('orderBy')
        ->will($this->returnValue($qb));
        $qb->expects($this->any())
        ->method('select')
        ->will($this->returnValue($qb));
        $qb->expects($this->any())
        ->method('setFirstResult')
        ->will($this->returnValue($qb));
        $qb->expects($this->any())
        ->method('setMaxResults')
        ->will($this->returnValue($qb));

        $em->expects($this->any())
        ->method('createQueryBuilder')
        ->will($this->returnValue($qb));

        $this->controller->setEntityManager($em);
    }
}


text:
package org.eclipse.php.internal.debug.core.debugger;

import java.util.Map;

/**
 * Common interface for implementors of debugger owner settings.
 *
 * @author Bartlomiej Laczkowski
 */
public interface IDebuggerSettings {

	/**
	 * Returns corresponding debugger ID.
	 *
	 * @return corresponding debugger ID
	 */
	String getDebuggerId();

	/**
	 * Returns debugger settings owner (e.g. PHP executable or server).
	 *
	 * @return debugger settings owner
	 */
	String getOwnerId();

	/**
	 * Returns settings kind (see {@link DebuggerSettingsKind} enum)
	 *
	 * @return settings kind
	 */
	DebuggerSettingsKind getKind();

	/**
	 * Returns settings attribute value for given key.
	 *
	 * @param key
	 * @return attribute value for given key
	 */
	String getAttribute(String key);

	/**
	 * Returns all attributes map.
	 *
	 * @return all attributes map
	 */
	Map<String, String> getAttributes();

}


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

namespace Microsoft.WindowsAzure.Management.SqlDatabase.Test.UnitTests.Database.Cmdlet
{
    using System;
    using System.Management.Automation;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.WindowsAzure.Management.CloudService.Test;
    using Microsoft.WindowsAzure.Management.SqlDatabase.Database.Cmdlet;

    /// <summary>
    /// These tests prevent regression in parameter validation attributes.
    /// </summary>
    [TestClass]
    public class DatabaseCmdletAttributionTests : TestBase
    {
        [TestInitialize]
        public void SetupTest()
        {
        }

        [TestMethod]
        public void NewAzureSqlDatabaseServerContextAttributeTest()
        {
            Type cmdlet = typeof(NewAzureSqlDatabaseServerContext);
            UnitTestHelper.CheckConfirmImpact(cmdlet, ConfirmImpact.None);
            UnitTestHelper.CheckCmdletModifiesData(cmdlet, false);
        }

        [TestMethod]
        public void GetAzureSqlDatabaseAttributeTest()
        {
            Type cmdlet = typeof(GetAzureSqlDatabase);
            UnitTestHelper.CheckConfirmImpact(cmdlet, ConfirmImpact.None);
            UnitTestHelper.CheckCmdletModifiesData(cmdlet, false);
        }

        [TestMethod]
        public void NewAzureSqlDatabaseAttributeTest()
        {
            Type cmdlet = typeof(NewAzureSqlDatabase);
            UnitTestHelper.CheckConfirmImpact(cmdlet, ConfirmImpact.Low);
            UnitTestHelper.CheckCmdletModifiesData(cmdlet, true);
        }

        [TestMethod]
        public void RemoveAzureSqlDatabaseAttributeTest()
        {
            Type cmdlet = typeof(RemoveAzureSqlDatabase);
            UnitTestHelper.CheckConfirmImpact(cmdlet, ConfirmImpact.High);
            UnitTestHelper.CheckCmdletModifiesData(cmdlet, true);
        }

        [TestMethod]
        public void SetAzureSqlDatabaseAttributeTest()
        {
            Type cmdlet = typeof(SetAzureSqlDatabase);
            UnitTestHelper.CheckConfirmImpact(cmdlet, ConfirmImpact.Medium);
            UnitTestHelper.CheckCmdletModifiesData(cmdlet, true);
        }
    }
}


text:
package main

import (
	"log"
	"net/http"
	"os"

	"github.com/melvinodsa/fileUpload/app"
	"github.com/melvinodsa/fileUpload/configuration"
	"github.com/melvinodsa/fileUpload/modules/downloadscreen"
	"github.com/melvinodsa/fileUpload/modules/homescreen"
	"github.com/melvinodsa/fileUpload/modules/uploadscreen"
)

func home(w http.ResponseWriter, r *http.Request) {
	homescreen.Home(w, r)
}

func downloadview(w http.ResponseWriter, r *http.Request) {
	downloadscreen.DownloadScreen(w, r)
}

func download(w http.ResponseWriter, r *http.Request) {
	downloadscreen.Download(w, r)
}

func uploadview(w http.ResponseWriter, r *http.Request) {
	uploadscreen.UploadScreen(w, r)
}

func upload(w http.ResponseWriter, r *http.Request) {
	uploadscreen.Upload(w, r)
}

func main() {
	configuration.CacheConfiguration()
	if err := configuration.SaveShortCode(100000); nil != err {
		log.Fatal("Error in intializing the shortcode to 100000.", err)
	} else {
		//Comment this line to prevent app from starting...
		go app.StartFileUpload("http://localhost:9090")
		f, err := os.OpenFile("./logs/fileUpload.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatal("error opening log file: ", err)
		}
		defer f.Close()
		log.SetOutput(f)
		log.Println("The application has started.")
		http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
		//Handling all the url requests.
		http.HandleFunc("/", home)
		http.HandleFunc("/downloadscreen", downloadview)
		http.HandleFunc("/download", download)
		http.HandleFunc("/uploadscreen", uploadview)
		http.HandleFunc("/upload", upload)

		err = http.ListenAndServe(":9090", nil) // setting listening port
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	}
}


text:
package com.graphhopper.storage.index;

/**
 * Helper class used in some Location2IDIndex implementations for findID
 * <p/>
 * @author Peter Karich
 */
class WeightedNode implements Comparable<WeightedNode>
{
    public int node;
    public double weight;

    WeightedNode( int node, double distance )
    {
        this.node = node;
        this.weight = distance;
    }

    @Override
    public int compareTo( WeightedNode o )
    {
        return Double.compare(weight, o.weight);
    }

    @Override
    public String toString()
    {
        return node + " weight is " + weight;
    }
}


text:
{% if site.inter_post_navigation == true %}

  {% if page.categories %}
    {% assign category = page.categories[0] %}
    {% assign posts = site.categories[category] | where:"lang", page.lang %}
    {% for post in posts %}
      {% if post.url == page.url %}
        {% assign post_index0 = forloop.index0 %}
        {% assign post_index1 = forloop.index %}
      {% endif %}
    {% endfor %}
    {% for post in posts %}
      {% if post_index0 == forloop.index %}
        {% assign next_post = post %}
      {% endif %}
      {% if post_index1 == forloop.index0 %}
        {% assign prev_post = post %}
      {% endif %}
    {% endfor %}
  {% endif %}

      {% if next_post.url %}

          {{ next_post.title }}

      {% endif %}

      {% if prev_post.url %}

          {{ prev_post.title }}

      {% endif %}

{% endif %}


text:
namespace kj {

class Win32EventPort: public EventPort {
  // Abstract base interface for EventPorts that can listen on Win32 event types. Due to the
  // absurd complexity of the Win32 API, it's not possible to standardize on a single
  // implementation of EventPort. In particular, there is no way for a single thread to use I/O
  // completion ports (the most efficient way of handling I/O) while at the same time waiting for
  // signalable handles or UI messages.
  //
  // Note that UI messages are not supported at all by this interface because the message queue
  // is implemented by user32.dll and we want libkj to depend only on kernel32.dll. A separate
  // compat library could provide a Win32EventPort implementation that works with the UI message
  // queue.

public:
  // ---------------------------------------------------------------------------
  // overlapped I/O

  struct IoResult {
    DWORD errorCode;
    DWORD bytesTransferred;
  };

  class IoOperation {
  public:
    virtual LPOVERLAPPED getOverlapped() = 0;
    // Gets the OVERLAPPED structure to pass to the Win32 I/O call. Do NOT modify it; just pass it
    // on.

    virtual Promise<IoResult> onComplete() = 0;
    // After making the Win32 call, if the return value indicates that the operation was
    // successfully queued (i.e. the completion event will definitely occur), call this to wait
    // for completion.
    //
    // You MUST call this if the operation was successfully queued, and you MUST NOT call this
    // otherwise. If the Win32 call failed (without queuing any operation or event) then you should
    // simply drop the IoOperation object.
    //
    // Dropping the returned Promise cancels the operation via Win32's CancelIoEx(). The destructor
    // will wait for the cancellation to complete, such that after dropping the proimse it is safe
    // to free the buffer that the operation was reading from / writing to.
    //
    // You may safely drop the `IoOperation` while still waiting for this promise. You may not,
    // however, drop the `IoObserver`.
  };

  class IoObserver {
  public:
    virtual Own<IoOperation> newOperation(uint64_t offset) = 0;
    // Begin an I/O operation. For file operations, `offset` is the offset within the file at
    // which the operation will start. For stream operations, `offset` is ignored.
  };

  virtual Own<IoObserver> observeIo(HANDLE handle) = 0;
  // Given a handle which supports overlapped I/O, arrange to receive I/O completion events via
  // this EventPort.
  //
  // Different Win32EventPort implementations may handle this in different ways, such as by using
  // completion routines (APCs) or by using I/O completion ports. The caller should not assume
  // any particular technique.
  //
  // WARNING: It is only safe to call observeIo() on a particular handle once during its lifetime.
  //   You cannot observe the same handle from multiple Win32EventPorts, even if not at the same
  //   time. This is because the Win32 API provides no way to disassociate a handle from an I/O
  //   completion port once it is associated.

  // ---------------------------------------------------------------------------
  // signalable handles
  //
  // Warning: Due to limitations in the Win32 API, implementations of EventPort may be forced to
  //   spawn additional threads to wait for signaled objects. This is necessary if the EventPort
  //   implementation is based on I/O completion ports, or if you need to wait on more than 64
  //   handles at once.

  class SignalObserver {
  public:
    virtual Promise<void> onSignaled() = 0;
    // Returns a promise that completes the next time the handle enters the signaled state.
    //
    // Depending on the type of handle, the handle may automatically be reset to a non-signaled
    // state before the promise resolves. The underlying implementaiton uses WaitForSingleObject()
    // or an equivalent wait call, so check the documentation for that to understand the semantics.
    //
    // If the handle is a mutex and it is abandoned without being unlocked, the promise breaks with
    // an exception.

    virtual Promise<bool> onSignaledOrAbandoned() = 0;
    // Like onSignaled(), but instead of throwing when a mutex is abandoned, resolves to `true`.
    // Resolves to `false` for non-abandoned signals.
  };

  virtual Own<SignalObserver> observeSignalState(HANDLE handle) = 0;
  // Given a handle that supports waiting for it to become "signaled" via WaitForSingleObject(),
  // return an object that can wait for this state using the EventPort.

  // ---------------------------------------------------------------------------
  // APCs

  virtual void allowApc() = 0;
  // If this is ever called, the Win32EventPort will switch modes so that APCs can be scheduled
  // on the thread, e.g. through the Win32 QueueUserAPC() call. In the future, this may be enabled
  // by default. However, as of this writing, Wine does not support the necessary
  // GetQueuedCompletionStatusEx() call, thus allowApc() breaks Wine support. (Tested on Wine
  // 1.8.7.)
  //
  // If the event port implementation can't support APCs for some reason, this throws.

  // ---------------------------------------------------------------------------
  // time

  virtual Timer& getTimer() = 0;
};

class Win32WaitObjectThreadPool {
  // Helper class that implements Win32EventPort::observeSignalState() by spawning additional
  // threads as needed to perform the actual waiting.
  //
  // This class is intended to be used to assist in building Win32EventPort implementations.

public:
  Win32WaitObjectThreadPool(uint mainThreadCount = 0);
  // `mainThreadCount` indicates the number of objects the main thread is able to listen on
  // directly. Typically this would be zero (e.g. if the main thread watches an I/O completion
  // port) or MAXIMUM_WAIT_OBJECTS (e.g. if the main thread is a UI thread but can use
  // MsgWaitForMultipleObjectsEx() to wait on some handles at the same time as messages).

  Own<Win32EventPort::SignalObserver> observeSignalState(HANDLE handle);
  // Implemetns Win32EventPort::observeSignalState().

  uint prepareMainThreadWait(HANDLE* handles[]);
  // Call immediately before invoking WaitForMultipleObjects() or similar in the main thread.
  // Fills in `handles` with the handle pointers to wait on, and returns the number of handles
  // in this array. (The array should be allocated to be at least the size passed to the
  // constructor).
  //
  // There's no need to call this if `mainThreadCount` as passed to the constructor was zero.

  bool finishedMainThreadWait(DWORD returnCode);
  // Call immediately after invoking WaitForMultipleObjects() or similar in the main thread,
  // passing the value returend by that call. Returns true if the event indicated by `returnCode`
  // has been handled (i.e. it was WAIT_OBJECT_n or WAIT_ABANDONED_n where n is in-range for the
  // last call to prepareMainThreadWait()).
};

class Win32IocpEventPort final: public Win32EventPort {
  // An EventPort implementation which uses Windows I/O completion ports to listen for events.
  //
  // With this implementation, observeSignalState() requires spawning a separate thread.

public:
  Win32IocpEventPort();
  ~Win32IocpEventPort() noexcept(false);

  // implements EventPort ------------------------------------------------------
  bool wait() override;
  bool poll() override;
  void wake() const override;

  // implements Win32IocpEventPort ---------------------------------------------
  Own<IoObserver> observeIo(HANDLE handle) override;
  Own<SignalObserver> observeSignalState(HANDLE handle) override;
  Timer& getTimer() override { return timerImpl; }
  void allowApc() override { isAllowApc = true; }

private:
  class IoPromiseAdapter;
  class IoOperationImpl;
  class IoObserverImpl;

  const MonotonicClock& clock;

  AutoCloseHandle iocp;
  AutoCloseHandle thread;
  Win32WaitObjectThreadPool waitThreads;
  TimerImpl timerImpl;
  mutable std::atomic<bool> sentWake {false};
  bool isAllowApc = false;

  void waitIocp(DWORD timeoutMs);
  // Wait on the I/O completion port for up to timeoutMs and pump events. Does not advance the
  // timer; caller must do that.

  bool receivedWake();

  static AutoCloseHandle newIocpHandle();
  static AutoCloseHandle openCurrentThread();
};

} // namespace kj


text:
void EulerShock2D::Run()
//---------------------------------------------------------
{
  // function Q = EulerShock2D(Q,FinalTime, ExactSolution, ExactSolutionBC, fluxtype)
  // Purpose  : Integrate 2D Euler equations using a 2nd order SSP Runge-Kutta time integrator

  InitRun();

  // choose order to integrate exactly
  CubatureOrder = (int)floor(2.0*(N+1)*3.0/2.0);
  NGauss        = (int)floor(2.0*(N+1));

  // build cubature node data for all elements
  CubatureVolumeMesh2D(CubatureOrder);

  // build Gauss node data for all element faces
  GaussFaceMesh2D(NGauss);

  Resize_cub();         // resize cubature arrays
//MapGaussFaceData();   // {nx = gauss.nx}, etc.
  ti0=timer.read();     // time simulation loop

#if (0)
  //-------------------------------------
  // check all node sets
  //-------------------------------------
  OutputNodes(false);   // volume nodes
  OutputNodes(true);    // face nodes
  OutputNodes_cub();    // cubature
  OutputNodes_gauss();  // quadrature
  Report(true);         // show initial conditions
  umLOG(1, "\n*** Exiting after Cub, Gauss\n\n");
  return;
#endif

  // limit initial condition
  Q = EulerLimiter2D(Q, time);

  // outer time step loop
  while (time<FinalTime) {

    if (time+dt > FinalTime) {dt=FinalTime-time;}
    tw1=timer.read();   // time NDG work
    oldQ = Q;           // store solutuion from previous step

    // 2nd order SSP Runge-Kutta
    this->RHS(Q,  time, BCSolution); Q1 =  Q +      dt*rhsQ;      Q1 = EulerLimiter2D(Q1, time);
    this->RHS(Q1, time, BCSolution); Q  = (Q + Q1 + dt*rhsQ)/2.0; Q  = EulerLimiter2D(Q,  time);

    time += dt;         // increment time
    SetStepSize();      // compute new timestep
    time_work += timer.read() - tw1;  // accumulate cost of NDG work
    Report();           // optional reporting
    ++tstep;            // increment timestep

    // if (tstep>=10) break;      // testing
  }

  time_total = timer.read()-ti0;  // stop timing
  FinalReport();                  // final report
}


text:
from __future__ import absolute_import

from datetime import datetime
from django.utils import timezone

from sentry.testutils import AcceptanceTestCase
from sentry.models import GroupShare
from sentry.utils.samples import create_sample_event

class SharedIssueTest(AcceptanceTestCase):
    def setUp(self):
        super(SharedIssueTest, self).setUp()
        self.user = self.create_user('foo@example.com')
        self.org = self.create_organization(owner=self.user, name='Rowdy Tiger')
        self.team = self.create_team(organization=self.org, name='Mariachi Band')
        self.project = self.create_project(
            organization=self.org,
            team=self.team,
            name='Bengal',
        )
        self.login_as(self.user)

    def create_sample_event(self, platform):
        event = create_sample_event(
            project=self.project,
            platform=platform,
            event_id='d964fdbd649a4cf8bfc35d18082b6b0e',
            timestamp=1452683305,
        )
        event.group.update(
            first_seen=datetime(2015, 8, 13, 3, 8, 25, tzinfo=timezone.utc),
            last_seen=datetime(2016, 1, 13, 3, 8, 25, tzinfo=timezone.utc),
        )
        return event

    def test_cocoa_event(self):
        event = self.create_sample_event(
            platform='cocoa',
        )

        group = event.group

        GroupShare.objects.create(
            project_id=group.project_id,
            group=group,
        )

        self.browser.get('/share/issue/{}/'.format(group.get_share_id()))
        self.browser.wait_until('.entries')
        self.browser.snapshot('shared issue cocoa')


text:
<template>
    <require from="./form-group"></require>
    <require from="./../../../attributes"></require>
    <form-group element.bind="element" containerless>
        <div class="checkbox">
            <label>
                <input attributes.bind="element.attributes"
                       type="checkbox"
                       t.bind="label"
                       name.bind="element.key"
                       checked.bind="element.value">
                ${label}
            </label>
        </div>
    </form-group>
</template>


text:
angular.module('com.likalo.ui')
  .factory('$uiServices', [
    '$window',
    '$rootScope',
    function ($window, $rootScope) {
      var tick = false,
        scroll = {
          x: $window.scrollX,
          y: $window.scrollY
        },
        size = {
          width: $window.outerWidth,
          height: $window.outerHeight
        };

       function notify(event){
        if (!tick) {
          $window.requestAnimationFrame(function () {
            $rootScope.$broadcast(event, scroll);
            tick = false;
          });
        }
        tick = true;
       }

      function windowScroll(e) {
        scroll.x = $window.scrollX;
        scroll.y = $window.scrollY;
        notify('$windowScroll');
      }

      function windowResize(e) {
        size.width = $window.outerWidth;
        size.height = $window.outerHeight;
        notify('$windowResize');
      }

      $window.addEventListener('scroll', windowScroll.bind(this));
      $window.addEventListener('resize', windowResize.bind(this));

      return {
        trackScrollEvents: function (el) {

        }
      };
    }
  ]);


text:
using System;
using System.Collections.Generic;
using AutoFixture.Dsl;
using AutoFixture.Kernel;

namespace AutoFixture.Xunit.UnitTest
{
    internal class DelegatingFixture : IFixture
    {
        private readonly List<ISpecimenBuilder> customizations;
        private readonly List<ISpecimenBuilder> residueCollectors;

        public DelegatingFixture()
        {
            this.customizations = new List<ISpecimenBuilder>();
            this.residueCollectors = new List<ISpecimenBuilder>();
            this.OnCreate = (r, s) => new object();
        }

        public IList<ISpecimenBuilderTransformation> Behaviors
        {
            get { throw new NotImplementedException(); }
        }

        public IList<ISpecimenBuilder> Customizations
        {
            get { return this.customizations; }
        }

        public bool OmitAutoProperties { get; set; }

        public int RepeatCount { get; set; }

        public IList<ISpecimenBuilder> ResidueCollectors
        {
            get { return this.residueCollectors; }
        }

        public void AddManyTo<T>(ICollection<T> collection, Func<T> creator)
        {
            throw new NotImplementedException();
        }

        public void AddManyTo<T>(ICollection<T> collection)
        {
            throw new NotImplementedException();
        }

        public void AddManyTo<T>(ICollection<T> collection, int repeatCount)
        {
            throw new NotImplementedException();
        }

        public ICustomizationComposer<T> Build<T>()
        {
            throw new NotImplementedException();
        }

        public IFixture Customize(ICustomization customization)
        {
            return this.OnCustomize(customization);
        }

        public void Customize<T>(Func<ICustomizationComposer<T>, ISpecimenBuilder> composerTransformation)
        {
            throw new NotImplementedException();
        }

        public void Inject<T>(T item)
        {
            throw new NotImplementedException();
        }

        public void Register<T>(Func<T> creator)
        {
            throw new NotImplementedException();
        }

        public void Register<TInput, T>(Func<TInput, T> creator)
        {
            throw new NotImplementedException();
        }

        public void Register<TInput1, TInput2, T>(Func<TInput1, TInput2, T> creator)
        {
            throw new NotImplementedException();
        }

        public void Register<TInput1, TInput2, TInput3, T>(Func<TInput1, TInput2, TInput3, T> creator)
        {
            throw new NotImplementedException();
        }

        public void Register<TInput1, TInput2, TInput3, TInput4, T>(Func<TInput1, TInput2, TInput3, TInput4, T> creator)
        {
            throw new NotImplementedException();
        }

        public object Create(object request, ISpecimenContext context)
        {
            return this.OnCreate(request, context);
        }

        internal Func<object, ISpecimenContext, object> OnCreate { get; set; }

        internal Func<ICustomization, IFixture> OnCustomize { get; set; }
    }
}


text:
package mesosphere.marathon

import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Named

import akka.actor.SupervisorStrategy.Resume
import akka.actor.{ ActorRef, ActorSystem, OneForOneStrategy, Props }
import akka.event.EventStream
import akka.routing.RoundRobinRouter
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject._
import com.google.inject.name.Names
import com.twitter.common.base.Supplier
import com.twitter.common.zookeeper.{ Candidate, CandidateImpl, ZooKeeperClient, Group => ZGroup }
import mesosphere.chaos.http.HttpConf
import mesosphere.marathon.event.EventModule
import mesosphere.marathon.health.{ DelegatingHealthCheckManager, HealthCheckManager, MarathonHealthCheckManager }
import mesosphere.marathon.io.storage.StorageProvider
import mesosphere.marathon.state._
import mesosphere.marathon.tasks.{ TaskIdUtil, TaskQueue, TaskTracker }
import mesosphere.mesos.util.FrameworkIdUtil
import org.apache.log4j.Logger
import org.apache.mesos.state.{ State, ZooKeeperState }
import org.apache.zookeeper.ZooDefs

object ModuleNames {
  final val NAMED_CANDIDATE = "CANDIDATE"
  final val NAMED_LEADER_ATOMIC_BOOLEAN = "LEADER_ATOMIC_BOOLEAN"
  final val NAMED_SERVER_SET_PATH = "SERVER_SET_PATH"
}

class MarathonModule(conf: MarathonConf, http: HttpConf, zk: ZooKeeperClient)
    extends AbstractModule {

  val log = Logger.getLogger(getClass.getName)

  def configure() {
    bind(classOf[MarathonConf]).toInstance(conf)
    bind(classOf[HttpConf]).toInstance(http)
    bind(classOf[ZooKeeperClient]).toInstance(zk)
    bind(classOf[MarathonSchedulerService]).in(Scopes.SINGLETON)
    bind(classOf[MarathonScheduler]).in(Scopes.SINGLETON)
    bind(classOf[TaskTracker]).in(Scopes.SINGLETON)
    bind(classOf[TaskQueue]).in(Scopes.SINGLETON)

    bind(classOf[GroupManager]).in(Scopes.SINGLETON)

    bind(classOf[HealthCheckManager]).to(
      conf.executorHealthChecks() match {
        case false => classOf[MarathonHealthCheckManager]
        case true  => classOf[DelegatingHealthCheckManager]
      }
    ).asEagerSingleton()

    bind(classOf[String])
      .annotatedWith(Names.named(ModuleNames.NAMED_SERVER_SET_PATH))
      .toInstance(conf.zooKeeperServerSetPath)

    // If running in single scheduler mode, this node is the leader.
    val leader = new AtomicBoolean(!conf.highlyAvailable())
    bind(classOf[AtomicBoolean])
      .annotatedWith(Names.named(ModuleNames.NAMED_LEADER_ATOMIC_BOOLEAN))
      .toInstance(leader)

  }

  @Provides
  @Singleton
  def provideMesosState(): State = {
    new ZooKeeperState(
      conf.zkHosts,
      conf.zkTimeoutDuration.toMillis,
      TimeUnit.MILLISECONDS,
      conf.zooKeeperStatePath
    )
  }

  @Named("schedulerActor")
  @Provides
  @Singleton
  @Inject
  def provideSchedulerActor(
    @Named("restMapper") mapper: ObjectMapper,
    system: ActorSystem,
    appRepository: AppRepository,
    healthCheckManager: HealthCheckManager,
    taskTracker: TaskTracker,
    taskQueue: TaskQueue,
    frameworkIdUtil: FrameworkIdUtil,
    taskIdUtil: TaskIdUtil,
    storage: StorageProvider,
    @Named(EventModule.busName) eventBus: EventStream,
    config: MarathonConf): ActorRef = {
    val supervision = OneForOneStrategy() {
      case _ => Resume
    }

    system.actorOf(
      Props(
        classOf[MarathonSchedulerActor],
        mapper,
        appRepository,
        healthCheckManager,
        taskTracker,
        taskQueue,
        frameworkIdUtil,
        taskIdUtil,
        storage,
        eventBus,
        config).withRouter(RoundRobinRouter(nrOfInstances = 1, supervisorStrategy = supervision)),
      "MarathonScheduler")
  }

  @Named(ModuleNames.NAMED_CANDIDATE)
  @Provides
  @Singleton
  def provideCandidate(zk: ZooKeeperClient): Option[Candidate] = {
    if (Main.conf.highlyAvailable()) {
      log.info("Registering in Zookeeper with hostname:"
        + Main.conf.hostname())
      val candidate = new CandidateImpl(new ZGroup(zk, ZooDefs.Ids.OPEN_ACL_UNSAFE,
        Main.conf.zooKeeperLeaderPath),
        new Supplier[Array[Byte]] {
          def get() = {
            //host:port
            "%s:%d".format(Main.conf.hostname(),
              Main.conf.httpPort()).getBytes
          }
        })
      return Some(candidate)
    }
    None
  }

  @Provides
  @Singleton
  def provideAppRepository(state: State, conf: MarathonConf): AppRepository = new AppRepository(
    new MarathonStore[AppDefinition](state, () => AppDefinition.apply()), conf.zooKeeperMaxVersions.get
  )

  @Provides
  @Singleton
  def provideGroupRepository(state: State, appRepository: AppRepository, conf: MarathonConf): GroupRepository = new GroupRepository(
    new MarathonStore[Group](state, () => Group.empty, "group:"), appRepository, conf.zooKeeperMaxVersions.get
  )

  @Provides
  @Singleton
  def provideActorSystem(): ActorSystem = ActorSystem("marathon")

  @Provides
  @Singleton
  def provideFrameworkIdUtil(state: State): FrameworkIdUtil =
    new FrameworkIdUtil(state)

  @Provides
  @Singleton
  def provideMigration(state: State, appRepo: AppRepository, groupRepo: GroupRepository, config: MarathonConf): Migration =
    new Migration(state, appRepo, groupRepo, config)

  @Provides
  @Singleton
  def provideTaskIdUtil(): TaskIdUtil = new TaskIdUtil

  @Provides
  @Singleton
  def provideStorageProvider(config: MarathonConf, http: HttpConf): StorageProvider = StorageProvider.provider(config, http)
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Phoma neglecta Desm., 1853

### Remarks
null


text:
<!DOCTYPE html>
<!--
Copyright (c) 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/raf.html">
<link rel="import" href="/tracing/core/test_utils.html">
<link rel="import" href="/tracing/model/event_set.html">
<link rel="import" href="/tracing/model/model.html">
<link rel="import" href="/tracing/model/sample.html">
<link rel="import" href="/tracing/model/thread_slice.html">
<link rel="import" href="/tracing/ui/analysis/related_events.html">

<script>
'use strict';

tr.b.unittest.testSuite(function() {
  var newSliceEx = tr.c.test_utils.newSliceEx;
  var newFlowEventEx = tr.c.test_utils.newFlowEventEx;

  function createModel() {
    var m = tr.c.test_utils.newModel(function(m) {
      m.p1 = m.getOrCreateProcess(1);

      m.t2 = m.p1.getOrCreateThread(2);
      m.t3 = m.p1.getOrCreateThread(3);
      m.t4 = m.p1.getOrCreateThread(4);

      // Setup samples and slices in this way:
      //     0    5    10   15   20
      // _____________________________
      // t2              *
      //     [ a  ][ ]aa
      // -----------------------------
      // t3         *  * *  *    *
      //               *    *
      //               [ b  ]
      //                [bb]
      //                 []bbb
      // -----------------------------
      // t4                      |c
      // -----------------------------
      m.samples.push(
        new tr.model.Sample(null, m.t3, 'b10_1', 10),
        new tr.model.Sample(null, m.t3, 'b7', 7),
        new tr.model.Sample(null, m.t3, 'b12', 12),
        new tr.model.Sample(null, m.t3, 'b20', 20),
        new tr.model.Sample(null, m.t3, 'b10_2', 10),
        new tr.model.Sample(null, m.t3, 'b15_1', 15),
        new tr.model.Sample(null, m.t3, 'b15_2', 15),
        new tr.model.Sample(null, m.t2, 'a12', 12)
      );

      m.sA = m.t2.sliceGroup.pushSlice(
          newSliceEx({title: 'a', start: 0, end: 5,
                      type: tr.model.ThreadSlice}));
      m.sAA = m.t2.sliceGroup.pushSlice(
          newSliceEx({title: 'aa', start: 6, end: 8,
                      type: tr.model.ThreadSlice}));
      m.sB = m.t3.sliceGroup.pushSlice(
          newSliceEx({title: 'b', start: 10, end: 15,
                      type: tr.model.ThreadSlice}));
      m.sBB = m.t3.sliceGroup.pushSlice(
          newSliceEx({title: 'bb', start: 11, end: 14,
                      type: tr.model.ThreadSlice}));
      m.sBBB = m.t3.sliceGroup.pushSlice(
          newSliceEx({title: 'bbb', start: 12, end: 13,
                      type: tr.model.ThreadSlice}));
      m.sC = m.t4.sliceGroup.pushSlice(
          newSliceEx({title: 'c', start: 20, end: 20,
                      type: tr.model.ThreadSlice}));

      m.t2.createSubSlices();
      m.t3.createSubSlices();
      m.t4.createSubSlices();

      // Add flow events.
      m.f0 = newFlowEventEx({
        'title': 'a_aa', start: 5, end: 6,
        startSlice: m.sA,
        endSlice: m.sAA
      });
      m.f1 = newFlowEventEx({
        'title': 'a_b', start: 0, end: 10,
        startSlice: m.sA,
        endSlice: m.sB
      });
      m.f2 = newFlowEventEx({
        'title': 'b_bbb', start: 10, end: 12,
        startSlice: m.sB,
        endSlice: m.sBBB
      });
      m.f3 = newFlowEventEx({
        'title': 'bbb_c', start: 13, end: 20,
        startSlice: m.sBBB,
        endSlice: m.sC
      });
    });
    return m;
  };

  test('instantiate', function() {
    var m = createModel();

    var viewEl = document.createElement('tr-ui-a-related-events');
    var selection = new tr.model.EventSet(
        [m.sA, m.f0, m.sAA, m.f1, m.sB, m.f2, m.sBB, m.sBBB, m.f3, m.sC]);
    viewEl.setRelatedEvents(selection);
    this.addHTMLOutput(viewEl);
    tr.b.forcePendingRAFTasksToRun(100000);  // Clear current RAF task queue.

    // Check that the element handles multiple setRelatedEvents calls correctly.
    assert.lengthOf(viewEl.$.table.tableRows, 5);
    viewEl.setRelatedEvents(selection);
    assert.lengthOf(viewEl.$.table.tableRows, 5);
  });

  test('validateFlows', function() {
    var m = createModel();

    var viewEl = document.createElement('tr-ui-a-related-events');
    viewEl.setRelatedEvents(new tr.model.EventSet([m.sB, m.sBB, m.sBBB]));
    this.addHTMLOutput(viewEl);
    tr.b.forcePendingRAFTasksToRun(100000);  // Clear current RAF task queue.

    var inFlows, outFlows, internalFlows;
    viewEl.$.table.tableRows.forEach(function(row) {
      if (row.type === 'Incoming flow') {
        assert.isUndefined(inFlows);
        inFlows = row.selection;
      }
      if (row.type === 'Outgoing flow') {
        assert.isUndefined(outFlows);
        outFlows = row.selection;
      }
      if (row.type === 'Internal flow') {
        assert.isUndefined(internalFlows);
        internalFlows = row.selection;
      }
    });
    assert.equal(inFlows.length, 1);
    assert.equal(inFlows[0].title, 'a_b');
    assert.equal(outFlows.length, 1);
    assert.equal(outFlows[0].title, 'bbb_c');
    assert.equal(internalFlows.length, 1);
    assert.equal(internalFlows[0].title, 'b_bbb');
  });

  test('validateConnectedEvents', function() {
    var m = createModel();

    var viewEl = document.createElement('tr-ui-a-related-events');
    viewEl.setRelatedEvents(new tr.model.EventSet([m.sBB]));
    this.addHTMLOutput(viewEl);
    tr.b.forcePendingRAFTasksToRun(100000);  // Clear current RAF task queue.

    var precedingEvents, followingEvents, allEvents;
    viewEl.$.table.tableRows.forEach(function(row) {
      if (row.type === 'Preceding events') {
        assert.isUndefined(precedingEvents);
        precedingEvents = row.selection;
      }
      if (row.type === 'Following events') {
        assert.isUndefined(followingEvents);
        followingEvents = row.selection;
      }
      if (row.type === 'All connected events') {
        assert.isUndefined(allEvents);
        allEvents = row.selection;
      }
    });

    var precedingTitles = precedingEvents.map(function(e) {
      return e.title;
    });
    assert.sameMembers(precedingTitles, ['a', 'a_b', 'b', 'bb']);

    var followingTitles = followingEvents.map(function(e) {
      return e.title;
    });
    assert.sameMembers(followingTitles, ['bb', 'bbb', 'bbb_c', 'c']);

    var allTitles = allEvents.map(function(e) {
      return e.title;
    });
    assert.sameMembers(allTitles,
        ['a', 'a_aa', 'aa', 'a_b', 'b', 'bb', 'bbb', 'b_bbb', 'bbb_c', 'c']);
  });

  test('validateOverlappingSamples', function() {
    var m = createModel();

    var viewEl = document.createElement('tr-ui-a-related-events');
    viewEl.setRelatedEvents(new tr.model.EventSet([m.sB]));
    this.addHTMLOutput(viewEl);
    tr.b.forcePendingRAFTasksToRun(100000);  // Clear current RAF task queue.

    var overlappingSamples;
    viewEl.$.table.tableRows.forEach(function(row) {
      if (row.type === 'Overlapping samples') {
        assert.isUndefined(overlappingSamples);
        overlappingSamples = row.selection;
      }
    });

    var samplesTitles = overlappingSamples.map(function(e) {
      return e.title;
    });
    assert.sameMembers(samplesTitles,
        ['b10_1', 'b10_2', 'b12', 'b15_1', 'b15_2']);
  });

});
</script>


text:
package ts.eclipse.ide.internal.core.compiler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;

import ts.cmd.tsc.TypeScriptCompilerHelper;
import ts.eclipse.ide.core.compiler.IDETypeScriptCompilerMessageHandler;
import ts.eclipse.ide.core.utils.TypeScriptResourceUtil;
import ts.eclipse.ide.core.utils.WorkbenchResourceUtil;
import ts.nodejs.INodejsProcess;
import ts.nodejs.INodejsProcessListener;

/**
 * IDE TypeScript compiler reporter.
 */
public class IDETypeScriptCompilerReporter extends IDETypeScriptCompilerMessageHandler
		implements INodejsProcessListener {

	private INodejsProcess process;
	private final List<String> tsFileNames;

	public IDETypeScriptCompilerReporter(IContainer container, boolean listEmittedFiles, List<IFile> tsFiles)
			throws CoreException {
		super(container, listEmittedFiles, tsFiles == null);
		if (tsFiles != null) {
			tsFileNames = new ArrayList<String>();
			for (IFile tsFile : tsFiles) {
				// delete marker for the given ts files.
				TypeScriptResourceUtil.deleteTscMarker(tsFile);
				// add to the list file names
				tsFileNames.add(WorkbenchResourceUtil.getRelativePath(tsFile, container).toString());
			}
		} else {
			tsFileNames = null;
		}
	}

	@Override
	public void onCreate(INodejsProcess process, List<String> commands, File projectDir) {

	}

	@Override
	public void onStart(INodejsProcess process) {
		this.process = process;
	}

	@Override
	public void onMessage(INodejsProcess process, String response) {
		TypeScriptCompilerHelper.processMessage(response, this);
	}

	@Override
	public void onStop(INodejsProcess process) {
	}

	@Override
	public void onError(INodejsProcess process, String line) {
	}

	@Override
	public void onCompilationCompleteWatchingForFileChanges() {
		process.kill();
	}

	public List<String> getFileNames() {
		return tsFileNames;
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/constant.ITIMER_VIRTUAL.html">

Redirecting to ../../../../libc/constant.ITIMER_VIRTUAL.html...


text:
package org.apache.lucene.demo.facet;

import java.util.List;

import org.apache.lucene.facet.FacetResult;
import org.apache.lucene.util.LuceneTestCase;
import org.junit.Test;

public class TestMultiCategoryListsFacetsExample extends LuceneTestCase {

  @Test
  public void testExample() throws Exception {
    List<FacetResult> results = new MultiCategoryListsFacetsExample().runSearch();
    assertEquals(2, results.size());
    assertEquals("dim=Author path=[] value=5 childCount=4\n  Lisa (2)\n  Bob (1)\n  Susan (1)\n  Frank (1)\n", results.get(0).toString());
    assertEquals("dim=Publish Date path=[] value=5 childCount=3\n  2010 (2)\n  2012 (2)\n  1999 (1)\n", results.get(1).toString());
  }
}