text:
FirefoxDriver.prototype.elementEquals = function(respond, parameters) {
  var elementA = Utils.getElementAt(parameters.id,
                                    respond.session.getDocument());
  var elementB = Utils.getElementAt(parameters.other,
                                    respond.session.getDocument());
  respond.value = elementA == elementB;
  respond.send();
};

FirefoxDriver.prototype.clickElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element, true) && !Utils.isInHead(element)) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE,
        "Element is not currently visible and so may not be clicked");
  }

  var nativeEvents = Utils.getNativeEvents();
  var node = Utils.getNodeForNativeEvents(element);
  var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].
      getService(Components.interfaces.nsIXULAppInfo);
  var versionChecker = Components.
      classes["@mozilla.org/xpcom/version-comparator;1"].
      getService(Components.interfaces.nsIVersionComparator);

  // I'm having trouble getting clicks to work on Firefox 2 on Windows. Always
  // fall back for that
  var useNativeClick =
      versionChecker.compare(appInfo.platformVersion, "1.9") >= 0;

  if (this.enableNativeEvents && nativeEvents && node && useNativeClick) {
    Utils.dumpn("Using native events for click");
    var loc = Utils.getLocationOnceScrolledIntoView(element);
    var x = loc.x + (loc.width ? loc.width / 2 : 0);
    var y = loc.y + (loc.height ? loc.height / 2 : 0);

    // In Firefox 3.6 and above, there's a shared window handle. We need to calculate an offset
    // to add to the x and y locations.

    var appInfo = Components.classes['@mozilla.org/xre/app-info;1'].
        getService(Components.interfaces.nsIXULAppInfo);
    var versionChecker = Components.classes['@mozilla.org/xpcom/version-comparator;1'].
        getService(Components.interfaces.nsIVersionComparator);
    if (versionChecker.compare(appInfo.version, '3.6') >= 0) {
      // Get the ultimate parent frame
      var current = element.ownerDocument.defaultView;
      var ultimateParent = element.ownerDocument.defaultView.parent;
      while (ultimateParent != current) {
        current = ultimateParent;
        ultimateParent = current.parent;
      }
      var offX = element.ownerDocument.defaultView.mozInnerScreenX - ultimateParent.mozInnerScreenX;
      var offY = element.ownerDocument.defaultView.mozInnerScreenY - ultimateParent.mozInnerScreenY;

      x += offX;
      y += offY;
    }

    try {
      nativeEvents.mouseMove(node, this.currentX, this.currentY, x, y);
      nativeEvents.click(node, x, y);
      this.currentX = x;
      this.currentY = y;
      respond.send();
      return;
    } catch (e) {
      // Make sure that we only fall through only if
      // the error returned from the native call indicates it's not
      // implemented.

      Utils.dumpn("Detected error when clicking: " + e.name);

      if (e.name != "NS_ERROR_NOT_IMPLEMENTED") {
        throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE, e);
      }

      // Fall through to the synthesized click code.
    }
  }

  Utils.dumpn("Falling back to synthesized click");
  var doc = respond.session.getDocument()
  var currentlyActive = Utils.getActiveElement(doc);

  Utils.fireMouseEventOn(element, "mouseover");
  Utils.fireMouseEventOn(element, "mousemove");
  Utils.fireMouseEventOn(element, "mousedown");
  if (element != currentlyActive) {
    // Some elements may not have blur, focus functions - for example,
    // elements under an SVG element. Call those only if they exist.
    if (typeof currentlyActive.blur == 'function') {
      currentlyActive.blur();
    }
    if (typeof element.focus == 'function') {
      element.focus();
    }
  }

  Utils.fireMouseEventOn(element, "mouseup");
  Utils.fireMouseEventOn(element, "click");

  var browser = respond.session.getBrowser();
  var alreadyReplied = false;

  var clickListener = new WebLoadingListener(browser, function(event) {
    if (!alreadyReplied) {
      alreadyReplied = true;
      respond.send();
    }
  });

  var contentWindow = browser.contentWindow;

  var checkForLoad = function() {
    // Returning should be handled by the click listener, unless we're not
    // actually loading something. Do a check and return if we are. There's a
    // race condition here, in that the click event and load may have finished
    // before we get here. For now, let's pretend that doesn't happen. The other
    // race condition is that we make this check before the load has begun. With
    // all the javascript out there, this might actually be a bit of a problem.
    var docLoaderService = browser.webProgress;
    if (!docLoaderService.isLoadingDocument) {
      WebLoadingListener.removeListener(browser, clickListener);
      if (!alreadyReplied) {
        alreadyReplied = true;
        respond.send();
      }
    }
  };

  if (contentWindow.closed) {
    // Nulls out the session; client will have to switch to another
    // window on their own.
    respond.send();
    return;
  }
  contentWindow.setTimeout(checkForLoad, 50);
};

FirefoxDriver.prototype.getElementText = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (element.tagName == "TITLE") {
    respond.value = respond.session.getBrowser().contentTitle;
  } else {
    respond.value = Utils.getText(element, true);
  }

  respond.send();
};

FirefoxDriver.prototype.getElementValue = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (element["value"] !== undefined) {
    respond.value = element.value;
    respond.send();
    return;
  }

  if (element.hasAttribute("value")) {
    respond.value = element.getAttribute("value");
    respond.send();
    return;
  }

  throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE,
      'Element does not have a value attribute');
};

FirefoxDriver.prototype.sendKeysToElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element, true) && !Utils.isInHead(element)) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE,
        "Element is not currently visible and so may not be used for typing");
  }

  var currentlyActive = Utils.getActiveElement(respond.session.getDocument());
  if (currentlyActive != element) {
    currentlyActive.blur();
    element.focus();
    element.ownerDocument.defaultView.focus();
  }

  var use = element;
  var tagName = element.tagName.toLowerCase();
  if (tagName == "body" && element.ownerDocument.defaultView.frameElement) {
    element.ownerDocument.defaultView.focus();

    // Turns out, this is what we should be using as the target
    // to send events to
    use = element.ownerDocument.getElementsByTagName("html")[0];
  }

  Utils.type(respond.session.getDocument(), use, parameters.value.join(''), this.enableNativeEvents);

  respond.send();
};

FirefoxDriver.prototype.clearElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element, true) && !Utils.isInHead(element)) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE,
        "Element is not currently visible and so may not be cleared");
  }

  var isTextField = element["value"] !== undefined;

  var currentlyActive = Utils.getActiveElement(respond.session.getDocument());
  if (currentlyActive != element) {
    currentlyActive.blur();
    element.focus();
  }

  var currentValue = undefined;
  if (element["value"] !== undefined) {
    currentValue = element.value;
  } else if (element.hasAttribute("value")) {
    currentValue = element.getAttribute("value");
  }

  if (isTextField) {
    element.value = "";
  } else {
    element.setAttribute("value", "");
  }

  if (currentValue !== undefined && currentValue != "") {
    Utils.fireHtmlEvent(element, "change");
  }

  respond.send();
};

FirefoxDriver.prototype.getElementTagName = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  respond.value = element.tagName.toLowerCase();
  respond.send();
};

FirefoxDriver.prototype.getElementAttribute = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var attributeName = parameters.name;

  if (element.hasAttribute(attributeName)) {
    respond.value = element.getAttribute(attributeName);
    // Is this block necessary?
    if (attributeName.toLowerCase() == "disabled") {
      respond.value = element.disabled;
    } else if (attributeName.toLowerCase() == "selected") {
      respond.value = element.selected;
    } else if (attributeName.toLowerCase() == "checked") {
      respond.value = element.checked;
    } else if (attributeName.toLowerCase() == "readonly") {
      respond.value = element.readOnly;
    }

    respond.send();
    return;
  }

  attributeName = attributeName.toLowerCase();

  if (attributeName == "disabled") {
    respond.value = (element.disabled === undefined ? false : element.disabled);
    respond.send();
    return;
  } else if ((attributeName == "checked" || attributeName == "selected") &&
             element.tagName.toLowerCase() == "input") {
    respond.value = element.checked;
    respond.send();
    return;
  } else if (attributeName == "selected" && element.tagName.toLowerCase()
      == "option") {
    respond.value = element.selected;
    respond.send();
    return;
  } else if (attributeName == "index" && element.tagName.toLowerCase()
      == "option") {
    respond.value = element.index;
    respond.send();
    return;
  }
  respond.value = null;
  respond.send();
};

FirefoxDriver.prototype.isElementEnabled = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());
  respond.value = !!!element.disabled;
  respond.send();
};

FirefoxDriver.prototype.hoverOverElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var events = Utils.getNativeEvents();
  var node = Utils.getNodeForNativeEvents(element);

  if (this.enableNativeEvents && events && node) {
    var loc = Utils.getLocationOnceScrolledIntoView(element);

    var x = loc.x + (loc.width ? loc.width / 2 : 0);
    var y = loc.y + (loc.height ? loc.height / 2 : 0);

    events.mouseMove(node, this.currentX, this.currentY, x, y);
    this.currentX = x;
    this.currentY = y;
  } else {
    // TODO: use the correct error type here.
    throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE,
        "Unable to hover over element");
  }

  respond.send();
};

FirefoxDriver.prototype.submitElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (element) {
    while (element.parentNode != null && element.tagName.toLowerCase() != "form") {
      element = element.parentNode;
    }
    if (element.tagName && element.tagName.toLowerCase() == "form") {
      if (Utils.fireHtmlEvent(element, "submit")) {
        new WebLoadingListener(respond.session.getBrowser(), function() {
          respond.send();
        });
        element.submit();
        return;
      } else {
        //Event was blocked, so don't submit
        respond.send();
        return;
      }
    } else {
      throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE,
          "Element was not in a form so couldn't submit");
    }
  } else {
    respond.send();
    return;
  }
};

FirefoxDriver.prototype.isElementSelected = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var selected = false;

  try {
    var option =
        element.QueryInterface(Components.interfaces.nsIDOMHTMLOptionElement);
    selected = option.selected;
  } catch(e) {
  }

  try {
    var inputElement =
        element.QueryInterface(Components.interfaces.nsIDOMHTMLInputElement);
    if (inputElement.type == "checkbox" || inputElement.type == "radio") {
      selected = inputElement.checked;
    }
  } catch(e) {
  }

  respond.value = selected;
  respond.send();
};

FirefoxDriver.prototype.setElementSelected = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element, true) && !Utils.isInHead(element)) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE,
        "Element is not currently visible and so may not be selected");
  }

  function safeQueryInterface(element, queryFor) {
    try {
      return element.QueryInterface(queryFor);
    } catch (ignored) {
      return null;
    }
  }

  var option = safeQueryInterface(
      element, Components.interfaces.nsIDOMHTMLOptionElement);
  if (option) {
    var select = element;
    while (select.parentNode && select.tagName.toLowerCase() != 'select') {
      select = select.parentNode;
    }
    select = safeQueryInterface(
        select, Components.interfaces.nsIDOMHTMLSelectElement);
    if (!select) {
      //If we're not within a select element, fire the event from the option, and hope that it bubbles up
      Utils.dumpn("Falling back to event firing from option, not select element");
      select = option;
    }

    if (!option.selected) {
      option.selected = true;
      Utils.fireHtmlEvent(select, 'change');
    }

    respond.status = ErrorCode.SUCCESS;
    respond.value = '';
    respond.send();
    return;
  }

  var inputElement = safeQueryInterface(
      element, Components.interfaces.nsIDOMHTMLInputElement);
  if (inputElement) {
    if (inputElement.disabled) {
      throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE,
          "You may not select a disabled element");
    }

    if (inputElement.type == 'checkbox' || inputElement.type == 'radio') {
      if (!inputElement.checked) {
        inputElement.checked = true;
        Utils.fireHtmlEvent(inputElement, 'change');
      }

      respond.status = ErrorCode.SUCCESS;
      respond.value = '';
      respond.send();
      return;
    }
  }

  throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE,
      'You may not select an unselectable element');
};

FirefoxDriver.prototype.toggleElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element) && !Utils.isInHead(element)) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE,
        "Element is not currently visible and so may not be toggled");
  }

  try {
    var checkbox =
        element.QueryInterface(Components.interfaces.nsIDOMHTMLInputElement);
    if (checkbox.type == "checkbox") {
      checkbox.checked = !checkbox.checked;
      Utils.fireHtmlEvent(checkbox, "change");
      respond.value = checkbox.checked;
      respond.send();
      return;
    }
  } catch(e) {
  }

  try {
    var option =
        element.QueryInterface(Components.interfaces.nsIDOMHTMLOptionElement);

    // Find our containing select and see if it allows multiple selections
    var select = option.parentNode;
    while (select && select.tagName != "SELECT") {
      select = select.parentNode;
    }

    if (select && select.multiple) {
      option.selected = !option.selected;
      Utils.fireHtmlEvent(option, "change");
      respond.value = option.selected;
      respond.send();
      return;
    }
  } catch(e) {
  }

    throw new WebDriverError(ErrorCode.INVALID_ELEMENT_STATE,
      "You may only toggle an element that is either a checkbox or an "  +
      "option in a select that allows multiple selections");
};

FirefoxDriver.prototype.isElementDisplayed = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());
  respond.value = Utils.isDisplayed(element, false);
  respond.send();
};

FirefoxDriver.prototype.getElementLocation = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var location = Utils.getElementLocation(element);

  respond.value = {
    x: Math.round(location.x),
    y: Math.round(location.y)
  };

  respond.send();
};

FirefoxDriver.prototype.getElementSize = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  var box = Utils.getLocationOnceScrolledIntoView(element);

  respond.value = {
    width: Math.round(box.width),
    height: Math.round(box.height)
  };
  respond.send();
};

FirefoxDriver.prototype.dragElement = function(respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element, true) && !Utils.isInHead(element)) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE,
        "Element is not currently visible and so may not be used for " +
        "drag and drop");
  }

  // Scroll the first element into view
  //  element.scrollIntoView(true);

  var clientStartXY = Utils.getElementLocation(element);

  var clientStartX = clientStartXY.x;
  var clientStartY = clientStartXY.y;

  var movementX = parameters.x;
  var movementY = parameters.y;

  var clientFinishX = ((clientStartX + movementX) < 0) ? 0 : (clientStartX
      + movementX);
  var clientFinishY = ((clientStartY + movementY) < 0) ? 0 : (clientStartY
      + movementY);

  // Restrict the desitnation into the sensible dimension
  var body = element.ownerDocument.body;

  if (clientFinishX > body.scrollWidth)
    clientFinishX = body.scrollWidth;
  if (clientFinishY > body.scrollHeight)
    clientFinishY = body.scrollHeight;

  var mouseSpeed = respond.session.getInputSpeed();
  var move = function(current, dest) {
    if (current == dest) return current;
    if (Math.abs(current - dest) < mouseSpeed) return dest;
    return (current < dest) ? current + mouseSpeed : current - mouseSpeed;
  };

  Utils.triggerMouseEvent(element, 'mousedown', clientStartX, clientStartY);
  Utils.triggerMouseEvent(element, 'mousemove', clientStartX, clientStartY);
  var clientX = clientStartX;
  var clientY = clientStartY;

  while ((clientX != clientFinishX) || (clientY != clientFinishY)) {
    clientX = move(clientX, clientFinishX);
    clientY = move(clientY, clientFinishY);

    Utils.triggerMouseEvent(element, 'mousemove', clientX, clientY);
  }

  Utils.triggerMouseEvent(element, 'mousemove', clientFinishX, clientFinishY);

  // TODO(simon.m.stewart) If we can tell which element is under the cursor,
  // send the mouseup to that
  Utils.triggerMouseEvent(element, 'mouseup', clientFinishX, clientFinishY);

  var finalLoc = Utils.getElementLocation(element);

  respond.value = finalLoc.x + "," + finalLoc.y;
  respond.send();
};

FirefoxDriver.prototype.getElementValueOfCssProperty = function(respond,
                                                                parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());
  respond.value = Utils.getStyleProperty(element, parameters.propertyName); // Coeerce to a string
  respond.send();
};

FirefoxDriver.prototype.getElementLocationOnceScrolledIntoView = function(
    respond, parameters) {
  var element = Utils.getElementAt(parameters.id,
                                   respond.session.getDocument());

  if (!Utils.isDisplayed(element, true)) {
    respond.value = undefined;
    respond.send();
    return;
  }

  var theDoc = element.ownerDocument;
  theDoc.body.focus();
  element.scrollIntoView(true);

  var retrieval = Utils.newInstance(
      "@mozilla.org/accessibleRetrieval;1", "nsIAccessibleRetrieval");

  try {
    var accessible = retrieval.getAccessibleFor(element);
    var x = {}, y = {}, width = {}, height = {};
    accessible.getBounds(x, y, width, height);

    respond.value = {
      x : x.value,
      y : y.value
    };
    respond.send();
    return;
  } catch(e) {
    // Element doesn't have an accessibility node. Fall through
  }

  // If we have the box object (which is deprecated) we could try using it
  var theDoc = respond.session.getDocument();
  if (theDoc.getBoxObjectFor) {
    // Fallback. Use the (deprecated) method to find out where the element is in
    // the viewport. This should be fine to use because we only fall down this
    // code path on older versions of Firefox (I think!)

    var box = theDoc.getBoxObjectFor(element);

    respond.value = {
      x : box.screenX,
      y : box.screenY
    };
    respond.send();
  }

  // Fine. Come up with a good guess. This should be the element location
  // added to the current window location. It'll probably be off
  var x = theDoc.defaultView.screenX;
  var y = theDoc.defaultView.screenY;

  var rect = element.getBoundingClientRect()
  respond.value = {
    x : x + rect.left,
    y : y + rect.top
  }
  respond.send();
};


text:
package com.sxt.service.product;

import java.util.List;

import com.sxt.models.SurplusProduct;

public interface SurplusProductService {
	public List<SurplusProduct> fQuerySurplusPro();
	public SurplusProduct fQuerySurplusProById(String product_id);
}

redpajama_set_name: RedPajamaGithub


text:
package server.persistence;

import java.util.Date;

import org.springframework.data.annotation.Id;

import server.business.ErrorHolder;

public abstract class TaskEntity {
	@Id
	private String id;
	private Date created; // the time when upload-process started
	private Date canceled; // the time when canceled, if at all
	private Date finished; // when finished normally
	private ErrorHolder error; // error, if any happened

	public TaskEntity(){
	}

	public TaskEntity(Date created) {
		super();
		this.created = created;
	}

	public boolean hasTerminated(){
		return canceled != null || finished != null || error != null;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

	public ErrorHolder getError() {
		return error;
	}

	public void setError(ErrorHolder error) {
		this.error = error;
	}

	public Date getCanceled() {
		return canceled;
	}

	public void setCanceled(Date canceled) {
		this.canceled = canceled;
	}

	public String getId() {
		return id;
	}

	public Date getFinished() {
		return finished;
	}

	public void setFinished(Date finished) {
		this.finished = finished;
	}

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


text:
package pl.edu.osp

class PrimeBank (max:Int) {
  var bank:scala.collection.mutable.ListBuffer[Int] = scala.collection.mutable.ListBuffer()
  def check(numb: Int): Int = {
    if (bank.isEmpty) {
      bank += numb
      return 0
    } else if (!foundFactorial(numb)) {
      if (numb <= max) {
        bank += numb
        return 0
      } else numb
    } else 0

  }

  def getSize = bank.size

	private def foundFactorial(numb:Int):Boolean = {
	  for(bNumb <- bank){
      if(bNumb*bNumb > numb ) return false
	    if(numb % bNumb == 0) return true
	  }
	  return false
	}

}


text:
package cz.cuni.mff.spl.evaluator.statistics;

import org.apache.commons.math3.stat.inference.MannWhitneyUTest;
import org.apache.commons.math3.stat.descriptive.StatisticalSummary;

import cz.cuni.mff.spl.annotation.Comparison;
import cz.cuni.mff.spl.annotation.Lambda;
import cz.cuni.mff.spl.annotation.MeasurementState;
import cz.cuni.mff.spl.annotation.MeasurementState.LastPhase;
import cz.cuni.mff.spl.annotation.Sign;
import cz.cuni.mff.spl.configuration.SplEvaluatorConfiguration;
import cz.cuni.mff.spl.evaluator.output.results.ComparisonResult;
import cz.cuni.mff.spl.evaluator.input.MeasurementDataProvider.MeasurementDataNotFoundException;

/**
 * Processes comparison evaluation for Mann Whitney U test.
 *
 * @author Lottie Carruthers
 *
 */
public class ComparisonEvaluatorMWW extends ComparisonEvaluator {

    /** The MannWhitneyUTest singleton instance to be used. */
    private static final MannWhitneyUTest              MWWTEST = new MannWhitneyUTest();

    /**
     * Instantiates a new comparison evaluator.
     *
     * @param configuration
     *            The configuration.
     * @param checker
     */
    public ComparisonEvaluatorMWW(SplEvaluatorConfiguration configuration, StatisticValueChecker checker) {
	super(configuration, checker);
    }

/**
     * Calls the comparison processor for this class, ommitting extra
     * parameters
     *
     * @param comparison
     *            The comparison.
     * @param dataArray1
     *            The left measurement sample.
     * @param dataArray2
     *            The right measurement sample.
     * @param  measuredData1
     *            The statistical summary of the left measurement.
     * @param measuredData2
     *            The statistical summary of the right measurement.
     * @param median1
     *            The median of the left measurement
     * @param median2
     *            The median of the right measurement
     * @param comparisonType
     *            The comparison type.
     * @return The comparison result.
     */
    public ComparisonResult processComparison(Comparison comparison,
             double[] dataArray1, double[] dataArray2, StatisticalSummary measuredData1,
             StatisticalSummary measuredData2, double median1, double median2, Sign comparisonType) {

    	return(processComparison( comparison, median1, median2,
    				  dataArray1, dataArray2,  comparisonType));
    }

    /**
     * Processes the comparison using a Mann Whitney U test
     *
     * @param comparison
     *            The comparison.
     * @param dataArray1
     *            The left measurement sample.
     * @param dataArray2
     *            The right measurement sample.
     * @param median1
     *            The median of the left measurement
     * @param median2
     *            The median of the right measurement
     * @param comparisonType
     *            The comparison type.
     * @return The comparison result.
     * @see ComparisonResult
     * @See MannWhitneyUTest#mannWhitneyUTest(double[], double[])
     */
    private ComparisonResult processComparison(Comparison comparison, double median1, double median2,
             double[] dataArray1, double[] dataArray2, Sign comparisonType) {

        if (dataArray1.length < 2 || dataArray2.length < 2) {
            return ComparisonResult.createNotComputedComparisonResult("Not enough measurement samples for statistical Mann Whitney Wilcoxon test.");
        }

        switch (comparisonType) {
            case EQI:
                // this is the most complex case as we need to evaluate equality
                // with interval check
                return processIntervalEqualityComparison(comparison, median2,
                	median1, dataArray2, dataArray1);

            case GE:
                // just swap values and test for LE
                return processComparison(comparison, median2, median1,
                 dataArray2, dataArray1, Sign.LE);
            case GT:
                // just swap values and test for LT
                return processComparison(comparison, median2, median1,
                    dataArray2, dataArray1, Sign.LT);
            case LE: {
                ComparisonResult lt = processComparison(comparison, median1, median2,
                    dataArray1, dataArray2, Sign.LT);
                ComparisonResult eq = processComparison(comparison, median1, median2,
                    dataArray1, dataArray2, Sign.EQ);
                if (lt.isSatisfied() && eq.isSatisfied()) {
                    return new ComparisonResult(Math.max(lt.getPValue(), eq.getPValue()), true);
                } else if (lt.isSatisfied()) {
                    return lt;
                } else {
                    return eq;
                }
            }
            case LT:

                // need to divide answer by 2 for a one sided test
                // first need to check that the test statistic is not in upper tail
                if (median1 < median2) {
                    double pValueNegate = MWWTEST.mannWhitneyUTest(dataArray1, dataArray2) / 2.0;
                    // MWW test validation says, that both series means are equal
                    // but we don't want this result, we want negation
                    boolean result = !confidenceChecker.isPvalueAcceptable(pValueNegate);
                    return new ComparisonResult(pValueNegate, result);
                } else {
                    // medians are not in correct relation => it is certain
                    return new ComparisonResult(0, false);
                }
            case EQ:
                double pValue = MWWTEST.mannWhitneyUTest(dataArray1, dataArray2);
                boolean acceptable = confidenceChecker.isPvalueAcceptable(pValue);
                return new ComparisonResult(pValue, acceptable);
            default:
                throw new IllegalStateException("Unexpected switch value " + comparisonType.toString());
        }
    }

    /**
     * Calls the  equality processor for this class, ommitting extra
     * parameters
     *
     * @param comparison
     *            The comparison.
     * @param dataArray1
     *            The left measurement sample.
     * @param dataArray2
     *            The right measurement sample.
     * @param  measuredData1
     *            The statistical summary of the left measurement.
     * @param measuredData2
     *            The statistical summary of the right measurement.
     * @param median1
     *            The median of the left measurement
     * @param median2
     *            The median of the right measurement
     * @param comparisonType
     *            The comparison type.
     * @return The comparison result.
     */
    public ComparisonResult processIntervalEqualityComparison(Comparison comparison,
             double[] dataArray2, double[] dataArray1, StatisticalSummary measuredData2,
             StatisticalSummary measuredData1, double median2, double median1) {

	   return (processIntervalEqualityComparison( comparison,  median2, median1, dataArray2,
						   dataArray1));
    }

    /**
     * Process interval equality comparison
     * using a Mann Whitney U test.
     *
     * @param comparison
     *            The comparison.
     * @param measuredData2
     *            The measured data2.
     * @param measuredData1
     *            The measured data1.
     * @param confidenceChecker
     *            The confidence checker.
     * @return The comparison result.
     */
    private ComparisonResult processIntervalEqualityComparison(Comparison comparison,
         double median2, double median1, double[] dataArray2, double[] dataArray1) {

        Double interval = comparison.getInterval();
        interval = interval != null ? interval : configuration.getEqualityInterval();

        double leftLowerMedian = transformMedianValue(median1, 1.0d - interval);
        double rightLowerMedian = transformMedianValue(median2, 1.0d + interval);

        double[] leftLowerMeasurement = transformMeasuredArray(dataArray1, 1.0d - interval);
        double[] rightLowerMeasurement = transformMeasuredArray(dataArray2, 1.0d + interval);

        double leftGreaterMedian = transformMedianValue(median1, 1.0d + interval);
        double rightGreaterMedian = transformMedianValue(median2, 1.0d - interval);

        double[] leftGreaterMeasurement = transformMeasuredArray(dataArray1, 1.0d + interval);
        double[] rightGreaterMeasurement = transformMeasuredArray(dataArray2, 1.0d - interval);

        ComparisonResult lowerResult = processComparison(comparison, leftLowerMedian, rightLowerMedian,
							 leftLowerMeasurement, rightLowerMeasurement,  Sign.LE);
        ComparisonResult greaterResult = processComparison(comparison, leftGreaterMedian, rightGreaterMedian,
							   leftGreaterMeasurement, rightGreaterMeasurement, Sign.GE);

        // combine results if satisfied, or return the one that failed
        if (lowerResult.isSatisfied() && greaterResult.isSatisfied()) {
            return new ComparisonResult(Math.min(lowerResult.getPValue(), greaterResult.getPValue()), true);
        } else if (lowerResult.isSatisfied()) {
            return greaterResult;
        } else {
            return lowerResult;
        }
    }

}


text:
<html>
<head><title>Web Socket Test</title></head>
<body>
<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8080/web-socket-example");
        socket.onmessage = function(event) {
            alert("Received data from websocket: " + event.data);
        };
        socket.onopen = function(event) {
            alert("Web Socket opened!");
        };
        socket.onclose = function(event) {
            alert("Web Socket closed.");
        };
    } else {
        alert("Your browser does not support Websockets. (Use Chrome)");
    }
    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("The socket is not open.");
        }
    }
</script>
<form onsubmit="return false;">
    <input type="text" name="message" value="Hello, World!"/>
    <input type="button" value="Send Web Socket Data" onclick="send(this.form.message.value)"/>
</form>
</body>
</html>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>lib/authenticated_system.rb - C0 code coverage information</title>

C0 code coverage information

Generated on mié feb 28 00:15:55 CET 2007 with rcov 0.6.0

Code reported as executed by Ruby looks like this...
and this: this line is also marked as covered.
Lines considered as run by rcov, but not reported by Ruby, look like this,
and this: these lines were inferred by rcov (using simple heuristics).
Finally, here's a line marked as not executed.

          Name
          Total lines
          Lines of code
          Total coverage
          Code coverage

            lib/authenticated_system.rb

            <tt>131</tt>

            <tt>68</tt>

                  <tt>56.5%</tt>

                  <tt>23.5%</tt>

  1 module AuthenticatedSystem
  2   protected
  3     # Returns true or false if the user is logged in.
  4     # Preloads @current_user with the user model if they're logged in.
  5     def logged_in?
  6       (@current_user ||= session[:user] ? User.find_by_id(session[:user]) : :false).is_a?(User)
  7     end
  8
  9     # Accesses the current user from the session.
 10     def current_user
 11       @current_user if logged_in?
 12     end
 13
 14     # Store the given user in the session.
 15     def current_user=(new_user)
 16       session[:user] = (new_user.nil? || new_user.is_a?(Symbol)) ? nil : new_user.id
 17       @current_user = new_user
 18     end
 19
 20     # Check if the user is authorized.
 21     #
 22     # Override this method in your controllers if you want to restrict access
 23     # to only a few actions or if you want to check if the user
 24     # has the correct rights.
 25     #
 26     # Example:
 27     #
 28     #  # only allow nonbobs
 29     #  def authorize?
 30     #    current_user.login != "bob"
 31     #  end
 32     def authorized?
 33       true
 34     end
 35
 36     # Filter method to enforce a login requirement.
 37     #
 38     # To require logins for all actions, use this in your controllers:
 39     #
 40     #   before_filter :login_required
 41     #
 42     # To require logins for specific actions, use this in your controllers:
 43     #
 44     #   before_filter :login_required, :only => [ :edit, :update ]
 45     #
 46     # To skip this in a subclassed controller:
 47     #
 48     #   skip_before_filter :login_required
 49     #
 50     def login_required
 51       username, passwd = get_auth_data
 52       self.current_user ||= User.authenticate(username, passwd) || :false if username && passwd
 53       logged_in? && authorized? ? true : access_denied
 54     end
 55
 56     # Redirect as appropriate when an access request fails.
 57     #
 58     # The default action is to redirect to the login screen.
 59     #
 60     # Override this method in your controllers if you want to have special
 61     # behavior in case the user is not authorized
 62     # to access the requested action.  For example, a popup window might
 63     # simply close itself.
 64     def access_denied
 65       respond_to do |accepts|
 66         accepts.html do
 67           store_location
 68           redirect_to :controller => ':admin', :action => 'signin'
 69         end
 70         accepts.xml do
 71           headers["Status"]           = "Unauthorized"
 72           headers["WWW-Authenticate"] = %(Basic realm="Web Password")
 73           render :text => "Could't authenticate you", :status => '401 Unauthorized'
 74         end
 75       end
 76       false
 77     end
 78
 79     # Store the URI of the current request in the session.
 80     #
 81     # We can return to this location by calling #redirect_back_or_default.
 82     def store_location
 83       session[:return_to] = request.request_uri
 84     end
 85
 86     # Redirect to the URI stored by the most recent store_location call or
 87     # to the passed default.
 88     def redirect_back_or_default(default)
 89       session[:return_to] ? redirect_to_url(session[:return_to]) : redirect_to(default)
 90       session[:return_to] = nil
 91     end
 92
 93     # Inclusion hook to make #current_user and #logged_in?
 94     # available as ActionView helper methods.
 95     def self.included(base)
 96       base.send :helper_method, :current_user, :logged_in?
 97     end
 98
 99     # When called with before_filter :login_from_cookie will check for an :auth_token
100     # cookie and log the user back in if apropriate
101     def login_from_cookie
102       return unless cookies[:auth_token] && !logged_in?
103       user = User.find_by_remember_token(cookies[:auth_token])
104       if user && user.remember_token?
105         user.remember_me
106         self.current_user = user
107         cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
108         flash[:notice] = "Logged in successfully"
109       end
110     end
111
112   private
113     # gets BASIC auth info
114     def get_auth_data
115       user, pass = nil, nil
116       # extract authorisation credentials
117       if request.env.has_key? 'X-HTTP_AUTHORIZATION'
118         # try to get it where mod_rewrite might have put it
119         authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
120       elsif request.env.has_key? 'HTTP_AUTHORIZATION'
121         # this is the regular location
122         authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
123       end
124
125       # at the moment we only support basic authentication
126       if authdata && authdata[0] == 'Basic'
127         user, pass = Base64.decode64(authdata[1]).split(':')[0..1]
128       end
129       return [user, pass]
130     end
131 end

Generated using the rcov code coverage analysis tool for Ruby version 0.6.0.


text:
A Bootstrap (http://getbootstrap.com/) theme for EPrints.

## Description

This is a basic bootstrap eprints theme with as few design decisions as possible. It is supposed to be a blank canvas for you to build on. It uses some JQuery to remove and change existing eprints classes, to bootstrap classes. This allows the bootstrap CSS (which is called in the template) to style the side.

## Releases

### 1.0.0 Beta

Very close to feature complete. Report any issues on Github issue tracker: https://github.com/eprintsug/bootstrap/issues

Issues will be fixed in future releases.

## Branding

The theme should work with any Bootstrap theme. Themes can be crated using the amazing theme generator here: http://pikock.github.io/bootstrap-magic/app/index.html#!/editor

The headers can be updated and changed by replacing the corresponding phrases. This should be done by copying ~/lib/lang/en/phrases/bootstrap.xml to ~/lib/lang/en/phrases/z_bootstrap.xml and editing the new file.

This might change in future releases (possibly to js templating).


text:
/*
 * 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.
 */

package org.bitcoinj.core;

import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.FullPrunedBlockStore;
import org.bitcoinj.store.MemoryFullPrunedBlockStore;

/**
 * A MemoryStore implementation of the FullPrunedBlockStoreTest
 */
public class MemoryFullPrunedBlockChainTest extends AbstractFullPrunedBlockChainTest
{
    @Override
    public FullPrunedBlockStore createStore(NetworkParameters params, int blockCount) throws BlockStoreException
    {
        return new MemoryFullPrunedBlockStore(params, blockCount);
    }

    @Override
    public void resetStore(FullPrunedBlockStore store) throws BlockStoreException
    {
        //No-op for memory store, because it's not persistent
    }
}


text:
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.

/**
 * SwingSpy examines swing layouts.
 *

 * Installation is simple, just add the following lines in your startup code:
 *

 * try {
 * 		Class.forName("jodd.swingspy.SwingSpy").getMethod("install").invoke(null);
 * } catch (Exception e) {
 * 		System.err.println("SwingSpy is not installed... ");
 * }
 *

 *

 * When SwingSpy is installed, you can invoke it by pressing
 * SHIFT + CTRL + click hot-key combination.
 */
package jodd.swingspy;


text:
package br.com.livraria.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import br.com.livraria.dao.DAO;
import br.com.livraria.exceptions.DBException;
import br.com.livraria.exceptions.IdNotFoundException;

/**
 *
 * Classe responsavel por realizar a implementacao do DAO Generico para as operacoes de CRUD basica.
 *
 * @author Elton
 * @version 1.0
 */
public abstract class DAOImpl<T, K> implements DAO<T, K> {

	@PersistenceContext
	private EntityManager em;

	private Class<T> classe;

	@SuppressWarnings("unchecked")
	public DAOImpl() {
		classe =
			(Class<T>) ((ParameterizedType)
					getClass().getGenericSuperclass())
						.getActualTypeArguments()[0];
	}

	public void insert(T entity) throws DBException {
		try {
			em.persist(entity);
		} catch (Exception e) {
			throw new DBException("Erro ao persistir " + e.getMessage());
		}
	}

	public void update(T entity) throws DBException {
		try{
			em.merge(entity);
		}catch(Exception e){
			throw new DBException("Erro ao atualizar");
		}
	}

	public void delete(K id) throws DBException, IdNotFoundException {
		T entity = searchByID(id);
		if (entity == null)
			throw new IdNotFoundException();
		try{
			em.remove(entity);
		}catch(Exception e){
			throw new DBException("Erro ao Remover");
		}
	}

	public T searchByID(K id) {
		return em.find(classe, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return em.createQuery( "from " + classe.getName()).getResultList();

	}
}


text:
from pythonforandroid.toolchain import CompiledComponentsPythonRecipe, shprint, current_directory
from os.path import exists, join
import sh
import glob

class NumpyRecipe(CompiledComponentsPythonRecipe):

    version = '1.7.1'
    url = 'http://pypi.python.org/packages/source/n/numpy/numpy-{version}.tar.gz'
    site_packages_name= 'numpy'

    depends = ['python2']

    def prebuild_arch(self, arch):
        super(NumpyRecipe, self).prebuild_arch(arch)
        build_dir = self.get_build_dir(arch.arch)
        if exists(join(build_dir, '.patched')):
            print('numpy already patched, skipping')
            return

        self.apply_patch('patches/fix-numpy.patch')

        shprint(sh.touch, join(build_dir, '.patched'))

recipe = NumpyRecipe()


text:
package nam.ui.design;

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

import nam.model.Project;
import nam.ui.tree.ModelTreeNode;
import nam.ui.tree.TreeNodeFactory;

import org.aries.runtime.BeanContext;
import org.richfaces.model.TreeNode;

public abstract class AbstractTreeBuilder {

	protected Integer correlationId;

	protected Map<String, ModelTreeNode> groupNodes;

	protected Map<String, ModelTreeNode> treeNodes;

	protected TreeNodeFactory treeNodeFactory;

	public TreeNode getNodeById(String nodeId) {
		return treeNodes.get(nodeId);
	}

	protected void initializeTreeBuilder() {
		correlationId = new Integer(0);
		groupNodes = new HashMap<String, ModelTreeNode>();
		treeNodes = new HashMap<String, ModelTreeNode>();
		treeNodeFactory = BeanContext.getFromSession("treeNodeFactory");
	}

	public ModelTreeNode createTree(Collection<Project> projects) {
		initializeTreeBuilder();
		ModelTreeNode rootNode = treeNodeFactory.createROOTNode();
		Iterator<Project> iterator = projects.iterator();
		while (iterator.hasNext()) {
			Project project = iterator.next();
			if (project != null)
				createTree(rootNode, project);
		}
		populateTreeNodeMap(rootNode);
		return rootNode;
	}

	protected void createTree(ModelTreeNode rootNode, Project project) {
	}

	protected Collection<ModelTreeNode> createTree(Project project) {
		return new ArrayList<ModelTreeNode>();
	}

	protected void populateTreeNodeMap(ModelTreeNode treeNode) {
		//String nodeKey = treeNodeFactory.getNodeKey(treeNode);
		//String nodeId = treeNodeFactory.getNodeId(treeNode);
		//treeNode.setId(nodeId);
		String nodeId = treeNode.getId();
		treeNodes.put(nodeId, treeNode);
		Iterator<Object> iterator = treeNode.getChildrenKeysIterator();
		while (iterator.hasNext()) {
			Object key = (Object) iterator.next();
			ModelTreeNode childNode = (ModelTreeNode) treeNode.getChild(key);
			populateTreeNodeMap(childNode);
		}
	}

}


text:
#ifndef CORELIB_MAKE_UNIQUE_HPP
#define CORELIB_MAKE_UNIQUE_HPP

#if 0

#include <memory>
#include <utility>

namespace std {
template<typename _T, typename ..._ARGS>
std::unique_ptr<_T> make_unique(_ARGS &&...args)
{
    return std::unique_ptr<_T>(new _T(std::forward<_ARGS>(args)...));
}
}

#endif /* 0 */

#endif /* CORELIB_MAKE_UNIQUE_HPP */


text:
package org.assertj.core.api.short2darray;

import static org.assertj.core.test.TestData.someIndex;
import static org.mockito.Mockito.verify;

import org.assertj.core.api.Short2DArrayAssert;
import org.assertj.core.api.Short2DArrayAssertBaseTest;
import org.assertj.core.data.Index;
import org.junit.jupiter.api.DisplayName;

/**
 * Tests for <code>{@link Short2DArrayAssert#contains(short[], Index)}</code>.
 *
 * @author Maciej Wajcht
 */
@DisplayName("Short2DArrayAssert contains")
class Short2DArrayAssert_contains_at_Index_Test extends Short2DArrayAssertBaseTest {
  private final Index index = someIndex();

  @Override
  protected Short2DArrayAssert invoke_api_method() {
    return assertions.contains(new short[] { 8, 9 }, index);
  }

  @Override
  protected void verify_internal_effects() {
    verify(arrays).assertContains(getInfo(assertions), getActual(assertions), new short[] { 8, 9 }, index);
  }
}


text:
package run.var.teamcity.cloud.docker.util;

import org.junit.Before;
import org.junit.Test;
import run.var.teamcity.cloud.docker.client.DockerClientProcessingException;
import run.var.teamcity.cloud.docker.client.TestDockerClientRegistryFactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
 * {@link OfficialAgentImageResolver} test suite.
 */
public class OfficialAgentImageResolverTest {

    private TestDockerClientRegistryFactory clientFty;

    private String version;

    @Before
    public void init() {
        clientFty = new TestDockerClientRegistryFactory();
        version = "10.0.3";
    }

    @Test
    public void normalResolution() {
        clientFty.configureClient((clt) -> clt.knownImage(OfficialAgentImageResolver.REPO, "4.0", "5.2", "5.2.1",
                                                          "5.2.1.1", "6.0", version));

        OfficialAgentImageResolver resolver = createResolver();

        assertThat(resolver.resolve()).isEqualTo(OfficialAgentImageResolver.REPO + ":" + version);

        assertThat(clientFty.getClient().isClosed()).isTrue();
    }

    @Test
    public void usingLatestWhenNoMatchingVersion() {
        clientFty.configureClient((clt) -> clt.knownImage(OfficialAgentImageResolver.REPO, "4.0", "6.0"));

        OfficialAgentImageResolver resolver = createResolver();

        assertThat(resolver.resolve()).isEqualTo(OfficialAgentImageResolver.LATEST);
    }

    @Test
    public void usingDefaultWhenRepoLookupFail() {
        clientFty.configureClient(clt -> clt.failOnAccess(new DockerClientProcessingException("Test failure.")));

        OfficialAgentImageResolver resolver = createResolver();

        assertThat(resolver.resolve()).isEqualTo(OfficialAgentImageResolver.REPO + ":" + version);
    }

    @Test
    public void mustCacheResult() {
        clientFty.configureClient((clt) -> clt.knownImage(OfficialAgentImageResolver.REPO, "4.0", "6.0"));

        OfficialAgentImageResolver resolver = createResolver();

        String resolved = resolver.resolve();

        clientFty.getClient().failOnAccess(new DockerClientProcessingException("Test failure."));

        assertThat(resolver.resolve()).isEqualTo(resolved);
    }

    @Test
    public void constructor() {
        // No error expected.
        createResolver();
        version = null;
        assertThatExceptionOfType(NullPointerException.class).isThrownBy(this::createResolver);
        version = "1.0";
        clientFty = null;
        assertThatExceptionOfType(NullPointerException.class).isThrownBy(this::createResolver);
    }

    @Test
    public void usingAPIStaticVersion() {
        OfficialAgentImageResolver resolver = OfficialAgentImageResolver.forCurrentServer(clientFty);

        // Check that the resolution process complete without error.
        // We also assert that the version tag will always the latest since the no image is available in our test
        // registry.
        assertThat(resolver.resolve()).isEqualTo(OfficialAgentImageResolver.LATEST);
    }

    private OfficialAgentImageResolver createResolver() {
        return new OfficialAgentImageResolver(version, clientFty);
    }

}


text:
/* -*- C++ -*- */

/********************************************************************
Copyright (c) 2010-2015, Regents of the University of Colorado

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of the University of Colorado nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
********************************************************************/

#ifndef _ProofAttachment_
#define _ProofAttachment_

/** @file ProofAttachment.h */

#include "ExprAttachment.h"
#include "Model.h"

struct Transition {
  Transition(void) { };
  Transition(const std::vector<ID> & _state, const std::vector<ID> & _inputs) :
      state(_state), inputs(_inputs) { };
  std::vector<ID> state;
  std::vector<ID> inputs;
};

struct Lasso {
  std::vector<Transition> stem; //Excludes all states in the loop
  std::vector<Transition> loop;
};

/**
 * A class to collect information about the proof.
 */
class ProofAttachment : public Model::Attachment {
public:
  ProofAttachment(Model& model) : Model::Attachment(model), _hasConclusion(false) {
    ExprAttachment::Factory eaf;
    requires(Key::EXPR, &eaf);
  }

  ProofAttachment(const ProofAttachment & from, Model & model) :
    Model::Attachment(from, model), _hasConclusion(false) { }

  Key::Type key(void) const { return Key::PROOF; }
  void build(void) {
    Options::Verbosity verbosity = _model.verbosity();
    if (verbosity > Options::Silent)
      std::cout << "Building proof attachment for model "
                << _model.name() << std::endl;
  }
  std::string string(bool includeDetails = false) const;
  bool hasConclusion(void) const { return _hasConclusion; }
  int conclusion(void) const { return _safe; }
  void printConclusion(std::ostream& os = std::cout) const;
  void setConclusion(const int conclusion) {
    assert(conclusion == 0 || conclusion == 1);
    if (_hasConclusion) {
      assert(_safe == conclusion);
    } else {
      _safe = conclusion;
      _hasConclusion = true;
    }
  }
  void produceEvidenceForFailure(void);
  void setCex(const std::vector<Transition> & cex) {
    if (_cex.empty())
    _cex = cex;
  }
  void printProof(std::ostream& os = std::cout) const;
  void addEquivalenceInfo(void);
  void setProof(const std::vector< std::vector<ID> > & proof) {
    _proof = proof;
  }

  class Factory : public Model::AttachmentFactory {
  public:
    virtual ProofAttachment * operator()(Model & model) {
      return new ProofAttachment(model);
    }
  };

protected:
  ProofAttachment* clone(Model & model) const { return new ProofAttachment(*this, model); }

private:
  void restoreInitialCondition(void);
  void restoreDroppedLatches(void);
  void decodeCounterexample(void);
  void unfoldCounterexample(void);
  void printCex(std::ostream& os = std::cout) const;
  void printWitness(std::ostream& os = std::cout);

  bool _hasConclusion;
  int _safe;
  std::vector<Transition> _cex;
  std::vector< std::vector<ID> > _proof;
};

#endif // _ProofAttachment_


text:
<?php

namespace allejo\DaPulse\Tests;

use allejo\DaPulse\Objects\PulseColumnStatusValue;
use allejo\DaPulse\Objects\PulseColumnValue;
use allejo\DaPulse\Pulse;
use allejo\DaPulse\PulseBoard;
use allejo\DaPulse\PulseUser;

class PulseColumnGettersTest extends PulseUnitTestCase
{
    private $id;

    private $userId;

    /**
     * @var PulseBoard
     */
    private $board;

    /**
     * @var Pulse[]
     */
    private $pulses;

    public function setUp()
    {
        parent::setUp();

        $this->id = self::BoardId; // Board ID
        $this->userId = self::MainUser; // Main User Account

        $this->board = new PulseBoard($this->id);
        $this->pulses = $this->board->getPulses(25, 1);
    }

    public function testGetNameColumnValues()
    {
        $expectedValues = array(
            "Mock Pulse One",
            "Mock Pulse Two",
            "Mockery Onion",
            "Jar of Jam"
        );
        $count = count($expectedValues);

        for ($i = 0; $i < $count; $i++)
        {
            $this->assertEquals($expectedValues[$i], $this->pulses[$i]->getName());
        }
    }

    public function testGetTextColumnValues()
    {
        $expectedValues = array(
            "Silver Pet Rock",
            "Oblivious Platypus",
            "Aspiring Platinum Duck",
            null
        );
        $count = count($expectedValues);

        for ($i = 0; $i < $count; $i++)
        {
            $this->assertEquals($expectedValues[$i], $this->pulses[$i]->getTextColumn('text')->getValue());
        }
    }

    public function testGetPersonColumnValues()
    {
        $user = new PulseUser($this->userId);

        $this->assertEquals($user, $this->pulses[0]->getPersonColumn('person')->getValue());
    }

    public function testGetPersonNullColumn()
    {
        $this->assertNull($this->pulses[1]->getPersonColumn('person')->getValue());
    }

    public function testGetDateNullColumn()
    {
        $this->assertNull($this->pulses[2]->getDateColumn('due_date')->getValue());
    }

    public function testGetDateColumnValues()
    {
        $date = array(
            new \DateTime("2017-01-03"),
            new \DateTime("2016-10-31"),
            null
        );

        $this->assertEquals($date[0], $this->pulses[0]->getDateColumn('due_date')->getValue());
        $this->assertEquals($date[1], $this->pulses[1]->getDateColumn('due_date')->getValue());
        $this->assertEquals($date[2], $this->pulses[2]->getDateColumn('due_date')->getValue());
    }

    public function testGetStatusColumnValues()
    {
        $expectedValues = array(
            PulseColumnStatusValue::Orange,
            PulseColumnStatusValue::Red,
            PulseColumnStatusValue::L_Green,
            PulseColumnStatusValue::Grey
        );
        $count = count($expectedValues);

        for ($i = 0; $i < $count; $i++)
        {
            $this->assertEquals($expectedValues[$i], $this->pulses[$i]->getStatusColumn('status')->getValue());
        }
    }

    public function testGetNumericColumnValue()
    {
        $this->assertEquals(100.5, $this->pulses[0]->getNumericColumn('numbers')->getValue());
        $this->assertEquals(50, $this->pulses[1]->getNumericColumn('numbers')->getValue());
    }

    public function testGetNumericColumnNullValue()
    {
        $this->assertNull($this->pulses[2]->getNumericColumn('numbers')->getValue());
    }

    public function testGetTimelineColumnValue()
    {
        $this->assertEquals([
            'from' => new \DateTime('2017-01-09'),
            'to'   => new \DateTime('2017-01-15')
        ], $this->pulses[0]->getTimelineColumn('timeline')->getValue());
    }

    public function testGetTimelineColumnNullValue()
    {
        $this->assertNull($this->pulses[1]->getTimelineColumn('timeline')->getValue());
    }

    public function testGetBadColumnType()
    {
        $this->setExpectedException('allejo\DaPulse\Exceptions\InvalidObjectException');

        PulseColumnValue::_createColumnType("non-existent", array());
    }

    public function testGetNonExistentColumn()
    {
        $this->setExpectedException('allejo\DaPulse\Exceptions\ColumnNotFoundException');

        $this->pulses[1]->getDateColumn("non-existent")->getValue();
    }

    public function testGetWrongColumnType()
    {
        $this->setExpectedException('allejo\DaPulse\Exceptions\InvalidColumnException');

        $this->pulses[1]->getDateColumn('person')->getValue();
    }
}


text:
title: Install Drupal Console Using Composer
---

Change directory to Drupal site:

```bash
cd /path/to/drupal8.dev
```

Execute composer require command:

```bash
composer require drupal/console:~1.0 \
--prefer-dist \
--optimize-autoloader
```

## Download using DrupalComposer project template

```bash
composer create-project \
drupal-composer/drupal-project:8.x-dev \
drupal8.dev \
--prefer-dist \
--no-progress \
--no-interaction
```

## Update DrupalConsole

```bash
composer update drupal/console --with-dependencies
```


text:
import secrets
import uuid
from collections.abc import Callable

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.timezone import now

DEFAULT_CHOICES_NAME = 'STATUS'

class AutoCreatedField(models.DateTimeField):
    """
    A DateTimeField that automatically populates itself at
    object creation.

    By default, sets editable=False, default=datetime.now.

    """

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('editable', False)
        kwargs.setdefault('default', now)
        super().__init__(*args, **kwargs)

class AutoLastModifiedField(AutoCreatedField):
    """
    A DateTimeField that updates itself on each save() of the model.

    By default, sets editable=False and default=datetime.now.

    """
    def get_default(self):
        """Return the default value for this field."""
        if not hasattr(self, "_default"):
            self._default = self._get_default()
        return self._default

    def pre_save(self, model_instance, add):
        value = now()
        if add:
            current_value = getattr(model_instance, self.attname, self.get_default())
            if current_value != self.get_default():
                # when creating an instance and the modified date is set
                # don't change the value, assume the developer wants that
                # control.
                value = getattr(model_instance, self.attname)
            else:
                for field in model_instance._meta.get_fields():
                    if isinstance(field, AutoCreatedField):
                        value = getattr(model_instance, field.name)
                        break
        setattr(model_instance, self.attname, value)
        return value

class StatusField(models.CharField):
    """
    A CharField that looks for a ``STATUS`` class-attribute and
    automatically uses that as ``choices``. The first option in
    ``STATUS`` is set as the default.

    Also has a default max_length so you don't have to worry about
    setting that.

    Also features a ``no_check_for_status`` argument to make sure
    South can handle this field when it freezes a model.
    """

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('max_length', 100)
        self.check_for_status = not kwargs.pop('no_check_for_status', False)
        self.choices_name = kwargs.pop('choices_name', DEFAULT_CHOICES_NAME)
        super().__init__(*args, **kwargs)

    def prepare_class(self, sender, **kwargs):
        if not sender._meta.abstract and self.check_for_status:
            assert hasattr(sender, self.choices_name), \
                "To use StatusField, the model '%s' must have a %s choices class attribute." \
                % (sender.__name__, self.choices_name)
            self.choices = getattr(sender, self.choices_name)
            if not self.has_default():
                self.default = tuple(getattr(sender, self.choices_name))[0][0]  # set first as default

    def contribute_to_class(self, cls, name):
        models.signals.class_prepared.connect(self.prepare_class, sender=cls)
        # we don't set the real choices until class_prepared (so we can rely on
        # the STATUS class attr being available), but we need to set some dummy
        # choices now so the super method will add the get_FOO_display method
        self.choices = [(0, 'dummy')]
        super().contribute_to_class(cls, name)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['no_check_for_status'] = True
        return name, path, args, kwargs

class MonitorField(models.DateTimeField):
    """
    A DateTimeField that monitors another field on the same model and
    sets itself to the current date/time whenever the monitored field
    changes.

    """

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('default', now)
        monitor = kwargs.pop('monitor', None)
        if not monitor:
            raise TypeError(
                '%s requires a "monitor" argument' % self.__class__.__name__)
        self.monitor = monitor
        when = kwargs.pop('when', None)
        if when is not None:
            when = set(when)
        self.when = when
        super().__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name):
        self.monitor_attname = '_monitor_%s' % name
        models.signals.post_init.connect(self._save_initial, sender=cls)
        super().contribute_to_class(cls, name)

    def get_monitored_value(self, instance):
        return getattr(instance, self.monitor)

    def _save_initial(self, sender, instance, **kwargs):
        if self.monitor in instance.get_deferred_fields():
            # Fix related to issue #241 to avoid recursive error on double monitor fields
            return
        setattr(instance, self.monitor_attname, self.get_monitored_value(instance))

    def pre_save(self, model_instance, add):
        value = now()
        previous = getattr(model_instance, self.monitor_attname, None)
        current = self.get_monitored_value(model_instance)
        if previous != current:
            if self.when is None or current in self.when:
                setattr(model_instance, self.attname, value)
                self._save_initial(model_instance.__class__, model_instance)
        return super().pre_save(model_instance, add)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['monitor'] = self.monitor
        if self.when is not None:
            kwargs['when'] = self.when
        return name, path, args, kwargs

SPLIT_MARKER = getattr(settings, 'SPLIT_MARKER', '<!-- split -->')

# the number of paragraphs after which to split if no marker
SPLIT_DEFAULT_PARAGRAPHS = getattr(settings, 'SPLIT_DEFAULT_PARAGRAPHS', 2)

def _excerpt_field_name(name):
    return '_%s_excerpt' % name

def get_excerpt(content):
    excerpt = []
    default_excerpt = []
    paras_seen = 0
    for line in content.splitlines():
        if not line.strip():
            paras_seen += 1
        if paras_seen < SPLIT_DEFAULT_PARAGRAPHS:
            default_excerpt.append(line)
        if line.strip() == SPLIT_MARKER:
            return '\n'.join(excerpt)
        excerpt.append(line)

    return '\n'.join(default_excerpt)

class SplitText:
    def __init__(self, instance, field_name, excerpt_field_name):
        # instead of storing actual values store a reference to the instance
        # along with field names, this makes assignment possible
        self.instance = instance
        self.field_name = field_name
        self.excerpt_field_name = excerpt_field_name

    # content is read/write
    @property
    def content(self):
        return self.instance.__dict__[self.field_name]

    @content.setter
    def content(self, val):
        setattr(self.instance, self.field_name, val)

    # excerpt is a read only property
    def _get_excerpt(self):
        return getattr(self.instance, self.excerpt_field_name)
    excerpt = property(_get_excerpt)

    # has_more is a boolean property
    def _get_has_more(self):
        return self.excerpt.strip() != self.content.strip()
    has_more = property(_get_has_more)

    def __str__(self):
        return self.content

class SplitDescriptor:
    def __init__(self, field):
        self.field = field
        self.excerpt_field_name = _excerpt_field_name(self.field.name)

    def __get__(self, instance, owner):
        if instance is None:
            raise AttributeError('Can only be accessed via an instance.')
        content = instance.__dict__[self.field.name]
        if content is None:
            return None
        return SplitText(instance, self.field.name, self.excerpt_field_name)

    def __set__(self, obj, value):
        if isinstance(value, SplitText):
            obj.__dict__[self.field.name] = value.content
            setattr(obj, self.excerpt_field_name, value.excerpt)
        else:
            obj.__dict__[self.field.name] = value

class SplitField(models.TextField):
    def __init__(self, *args, **kwargs):
        # for South FakeORM compatibility: the frozen version of a
        # SplitField can't try to add an _excerpt field, because the
        # _excerpt field itself is frozen as well. See introspection
        # rules below.
        self.add_excerpt_field = not kwargs.pop('no_excerpt_field', False)
        super().__init__(*args, **kwargs)

    def contribute_to_class(self, cls, name):
        if self.add_excerpt_field and not cls._meta.abstract:
            excerpt_field = models.TextField(editable=False)
            cls.add_to_class(_excerpt_field_name(name), excerpt_field)
        super().contribute_to_class(cls, name)
        setattr(cls, self.name, SplitDescriptor(self))

    def pre_save(self, model_instance, add):
        value = super().pre_save(model_instance, add)
        excerpt = get_excerpt(value.content)
        setattr(model_instance, _excerpt_field_name(self.attname), excerpt)
        return value.content

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return value.content

    def get_prep_value(self, value):
        try:
            return value.content
        except AttributeError:
            return value

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['no_excerpt_field'] = True
        return name, path, args, kwargs

class UUIDField(models.UUIDField):
    """
    A field for storing universally unique identifiers. Use Python UUID class.
    """

    def __init__(self, primary_key=True, version=4, editable=False, *args, **kwargs):
        """
        Parameters
        ----------
        primary_key : bool
            If True, this field is the primary key for the model.
        version : int
            An integer that set default UUID version.
        editable : bool
            If False, the field will not be displayed in the admin or any other ModelForm,
            default is false.

        Raises
        ------
        ValidationError
            UUID version 2 is not supported.
        """

        if version == 2:
            raise ValidationError(
                'UUID version 2 is not supported.')

        if version < 1 or version > 5:
            raise ValidationError(
                'UUID version is not valid.')

        if version == 1:
            default = uuid.uuid1
        elif version == 3:
            default = uuid.uuid3
        elif version == 4:
            default = uuid.uuid4
        elif version == 5:
            default = uuid.uuid5

        kwargs.setdefault('primary_key', primary_key)
        kwargs.setdefault('editable', editable)
        kwargs.setdefault('default', default)
        super().__init__(*args, **kwargs)

class UrlsafeTokenField(models.CharField):
    """
    A field for storing a unique token in database.
    """

    def __init__(self, editable=False, max_length=128, factory=None, **kwargs):
        """
        Parameters
        ----------
        editable: bool
            If true token is editable.
        max_length: int
            Maximum length of the token.
        factory: callable
            If provided, called with max_length of the field instance to generate token.

        Raises
        ------
        TypeError
            non-callable value for factory is not supported.
        """

        if factory is not None and not isinstance(factory, Callable):
            raise TypeError("'factory' should either be a callable not 'None'")
        self._factory = factory

        kwargs.pop('default', None)  # passing default value has not effect.

        super().__init__(editable=editable, max_length=max_length, **kwargs)

    def get_default(self):
        if self._factory is not None:
            return self._factory(self.max_length)
        # generate a token of length x1.33 approx. trim up to max length
        token = secrets.token_urlsafe(self.max_length)[:self.max_length]
        return token

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['factory'] = self._factory
        return name, path, args, kwargs


text:
Install
=======

External Dependencies
---------------------

Only *Vim* is required.

.. code:: sh

    vim --version

.. note::

    *headlessvim* does **NOT** depend on *Vim*'s *+clientserver* feature.
    Also, *+python* and *+python3* are **NOT** required.

.. note::

    If *Vim* is not in the ``$PATH`` environment variable,
    you can indicate which *Vim* to use in the code (mentioned later).

Python Versions
---------------

*headlessvim* is tested on *Python* s below:

* *Python 2.6*
* *Python 2.7*
* *Python 3.2*
* *Python 3.3*
* *Python 3.4*

Installation
------------

The easy way (using package manager)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Using *pip* (recommended)

.. code:: sh

    pip install headlessvim

The hard way (build from source)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Checkout from the repository, then the good old *setup.py*

.. code:: sh

    git clone https://github.com/manicmaniac/headlessvim.git
    cd headlessvim
    python setup.py install

Windows Support
---------------

Sorry, *Windows* is not supported currently.


text:
package com.google.javascript.jscomp.debugger;

import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.CellPanel;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.SourceFile;

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

/**
 * A GWT-based version of the Closure Compiler debugger
 *
 * @author moz@google.com (Michael Zhou)
 * @author blickly@google.com (Ben Lickly)
 */
public class DebuggerGwtMain implements EntryPoint {
  final CompilerOptions options = new CompilerOptions();
  final TextArea externs = new TextArea();
  final TextArea input0 = new TextArea();
  final VerticalPanel rightPane = new VerticalPanel();

  private void doCompile() {
    SourceFile externFile = SourceFile.fromCode("externs", externs.getValue());
    SourceFile srcFile = SourceFile.fromCode("input0", input0.getValue());
    Compiler compiler = new Compiler();
    try {
      Result result = compiler.compile(externFile, srcFile, options);
      updateUi(compiler, result);
    } catch (Exception e) {
      updateUiException(e);
    }
  }

  private void updateUi(Compiler compiler, Result result) {
    rightPane.clear();
    rightPane.add(new HTML("
Output
"));
    String outputCode = compiler.toSource();
    rightPane.add(new Label(outputCode));
    rightPane.add(new HTML("
Warnings
"));
    List<JSError> errors = Arrays.asList(result.errors);
    List<JSError> warnings = Arrays.asList(result.warnings);
    rightPane.add(new Label(Joiner.on("\n\n").join(Iterables.concat(errors, warnings))));
    rightPane.add(new HTML("
AST
"));
    String outputAst = compiler.getRoot().toStringTree();
    rightPane.add(new Label(outputAst));
  }

  private void updateUiException(Exception e) {
    rightPane.clear();
    rightPane.add(new HTML("
Exception
"));
    rightPane.add(new Label(e.toString()));
  }

  @Override
  public void onModuleLoad() {
    externs.setCharacterWidth(80);
    externs.setVisibleLines(5);
    externs.addKeyUpHandler(new KeyUpHandler() {
      @Override
      public void onKeyUp(KeyUpEvent event) {
        doCompile();
      }
    });

    input0.setCharacterWidth(80);
    input0.setVisibleLines(25);
    input0.addKeyUpHandler(new KeyUpHandler() {
      @Override
      public void onKeyUp(KeyUpEvent event) {
        doCompile();
      }
    });

    HorizontalPanel panel = new HorizontalPanel();
    VerticalPanel leftPane = new VerticalPanel();
    leftPane.add(new HTML("
Externs
"));
    leftPane.add(externs);
    leftPane.add(new HTML("
Input
"));
    leftPane.add(input0);
    leftPane.add(new HTML("
Options
"));
    createCheckboxes(leftPane);
    panel.add(leftPane);
    panel.add(rightPane);
    RootPanel.get().add(panel);
  }

  private void createCheckboxes(CellPanel checkboxPanel) {
    for (final CompilationParam param : CompilationParam.getSortedValues()) {
      CheckBox cb = new CheckBox(param.toString());
      cb.setValue(param.getDefaultValue());
      param.apply(options, param.getDefaultValue());
      cb.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
          boolean checked = ((CheckBox) event.getSource()).getValue();
          param.apply(options, checked);
          doCompile();
        }
      });
      checkboxPanel.add(cb);
    }
  }
}


text:
"""
Shared main-point between utilities.
"""

from calendarserver.tap.util import checkDirectories
from calendarserver.tools.util import loadConfig, autoDisableMemcached

from twext.python.log import StandardIOObserver

from twistedcaldav.config import ConfigurationError
from twisted.internet.defer import inlineCallbacks, succeed
from twisted.application.service import Service

import sys
from calendarserver.tap.util import getRootResource
from errno import ENOENT, EACCES
from twext.enterprise.jobqueue import NonPerformingQueuer

# TODO: direct unit tests for these functions.

def utilityMain(
    configFileName, serviceClass, reactor=None, serviceMaker=None,
    patchConfig=None, onShutdown=None, verbose=False
):
    """
    Shared main-point for utilities.

    This function will:

        - Load the configuration file named by C{configFileName},
        - launch a L{CalDAVServiceMaker}'s with the C{ProcessType} of
          C{"Utility"}
        - run the reactor, with start/stop events hooked up to the service's
          C{startService}/C{stopService} methods.

    It is C{serviceClass}'s responsibility to stop the reactor when it's
    complete.

    @param configFileName: the name of the configuration file to load.
    @type configuration: C{str}

    @param serviceClass: a 1-argument callable which takes an object that
        provides L{ICalendarStore} and/or L{IAddressbookStore} and returns an
        L{IService}.

    @param patchConfig: a 1-argument callable which takes a config object
        and makes and changes necessary for the tool.

    @param onShutdown: a 0-argument callable which will run on shutdown.

    @param reactor: if specified, the L{IReactorTime} / L{IReactorThreads} /
        L{IReactorTCP} (etc) provider to use.  If C{None}, the default reactor
        will be imported and used.
    """

    from calendarserver.tap.caldav import CalDAVServiceMaker, CalDAVOptions
    if serviceMaker is None:
        serviceMaker = CalDAVServiceMaker

    # We want to validate that the actual service is always an instance of WorkerService, so wrap the
    # service maker callback inside a function that does that check
    def _makeValidService(store):
        service = serviceClass(store)
        assert isinstance(service, WorkerService)
        return service

    # Install std i/o observer
    if verbose:
        observer = StandardIOObserver()
        observer.start()

    if reactor is None:
        from twisted.internet import reactor
    try:
        config = loadConfig(configFileName)
        if patchConfig is not None:
            patchConfig(config)

        checkDirectories(config)

        config.ProcessType = "Utility"
        config.UtilityServiceClass = _makeValidService

        autoDisableMemcached(config)

        maker = serviceMaker()

        # Only perform post-import duties if someone has explicitly said to
        maker.doPostImport = getattr(maker, "doPostImport", False)

        options = CalDAVOptions
        service = maker.makeService(options)

        reactor.addSystemEventTrigger("during", "startup", service.startService)
        reactor.addSystemEventTrigger("before", "shutdown", service.stopService)
        if onShutdown is not None:
            reactor.addSystemEventTrigger("before", "shutdown", onShutdown)

    except (ConfigurationError, OSError), e:
        sys.stderr.write("Error: %s\n" % (e,))
        return

    reactor.run()

class WorkerService(Service):

    def __init__(self, store):
        self.store = store

    def rootResource(self):
        try:
            from twistedcaldav.config import config
            rootResource = getRootResource(config, self.store)
        except OSError, e:
            if e.errno == ENOENT:
                # Trying to re-write resources.xml but its parent directory does
                # not exist.  The server's never been started, so we're missing
                # state required to do any work.
                raise ConfigurationError(
                    "It appears that the server has never been started.\n"
                    "Please start it at least once before running this tool.")
            elif e.errno == EACCES:
                # Trying to re-write resources.xml but it is not writable by the
                # current user.  This most likely means we're in a system
                # configuration and the user doesn't have sufficient privileges
                # to do the other things the tool might need to do either.
                raise ConfigurationError("You must run this tool as root.")
            else:
                raise
        return rootResource

    @inlineCallbacks
    def startService(self):

        try:
            # Work can be queued but will not be performed by the command
            # line tool
            if self.store is not None:
                self.store.queuer = NonPerformingQueuer()
                yield self.doWork()
            else:
                yield self.doWorkWithoutStore()
        except ConfigurationError, ce:
            sys.stderr.write("Error: %s\n" % (str(ce),))
        except Exception, e:
            sys.stderr.write("Error: %s\n" % (e,))
            raise
        finally:
            self.postStartService()

    def doWorkWithoutStore(self):
        """
        Subclasses can override doWorkWithoutStore if there is any work they
        can accomplish without access to the store, or if they want to emit
        their own error message.
        """
        sys.stderr.write("Error: Data store is not available\n")
        return succeed(None)

    def postStartService(self):
        """
        By default, stop the reactor after doWork( ) finishes.  Subclasses
        can override this if they want different behavior.
        """
        if hasattr(self, "reactor"):
            self.reactor.stop()
        else:
            from twisted.internet import reactor
            reactor.stop()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XData.Data.DataObjects
{
    public sealed class Column
    {
        public string Table { get; private set; }
        public string Name { get; private set; }

        public string TableAlias { get; internal set; }

        public Column(string table, string name)
        {
            Table = table;
            Name = name;
        }
    }

}


text:
<?php echo lang('form_checkout'); ?>

            <?php if (validation_errors()): ?>

                    ×
                    <?php echo validation_errors(); ?>

            <?php endif; ?>

            <?php include('order_details.php'); ?>

            <?php echo form_open('checkout/step_2', 'style = "padding-left: 60px;"'); ?>

<?php echo lang('shipping_method'); ?>

                        <?php
                        foreach ($shipping_methods as $key => $val):
                            $ship_encoded = md5(json_encode(array($key, $val)));

                            if ($ship_encoded == $shipping_code) {
                                $checked = true;
                            } else {
                                $checked = false;
                            }
                            ?>

                                    <?php echo form_radio('shipping_method', $ship_encoded, set_radio('shipping_method', $ship_encoded, $checked), 'id="s' . $ship_encoded . '"'); ?>

                                <td onclick="toggle_shipping('s<?php echo $ship_encoded; ?>');"><?php echo $key; ?>
                                <td onclick="toggle_shipping('s<?php echo $ship_encoded; ?>');">
                                    <?php echo $val['str']; ?>

                        <?php endforeach; ?>

<?php echo lang('shipping_instructions') ?>

                    <?php echo form_textarea(array('name' => 'shipping_notes', 'value' => set_value('shipping_notes', $this->go_cart->get_additional_detail('shipping_notes')), 'class' => 'span6', 'style' => 'height:75px;')); ?>

            <input class="btn btn-block btn-large btn-primary" type="submit"
                   value="<?php echo lang('form_continue'); ?>"/>
            </form>


text:
package io.beanmother.grpc;

public final class GrpcBuilderClass {

	private String attr1;

	public static BuilderPC newBuilder() {
		return new BuilderPC();
	}

	public static final class BuilderPC {

		private static GrpcBuilderClass pbc;

		private BuilderPC() {
			pbc = new GrpcBuilderClass();
		}

		public BuilderPC setAttr1(String value) {
			pbc.attr1 = value;
			return this;
		}

		public GrpcBuilderClass build() {
			return pbc;
		}
	}

	private GrpcBuilderClass() {
		attr1 = "";
	}

	public String getAttr1() {
		return attr1;
	}

	public static void main(String[] args) {
		GrpcBuilderClass pbc = GrpcBuilderClass.newBuilder().setAttr1("attr1").build();
		System.out.println(pbc.getAttr1());
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Il2CppDumper
{
    [AttributeUsage(AttributeTargets.Field)]
    class ArrayLengthAttribute : Attribute
    {
        public int Length { get; set; }
    }
}


text:
var readable = require('readable-stream')
  , add = require('add-event-listener')
  , test = require('tape')
  , ever = require('ever')

var events = require('./index.js')

test('test preventDefault option / boolean', function(assert) {
  var el = setup()
    , out = sink()
    , emitter

  events(el, 'click', {preventDefault: true})
    .pipe(out)

  emitter = ever(el)

  emitter.emit('click', {cancelable: true})

  assert.equal(out.received.length, 1, 'received one event')
  assert.ok(out.received[0].defaultPrevented, 'default should be prevented')
  assert.end()
})

test('test stopPropagation option / boolean', function(assert) {
  var el = setup()
    , out = sink()
    , emitter
    , evs

  events(el, 'click', {stopPropagation: true, maxPendingEvents: 1})

  evs = events(document.body, 'click')

  evs.pipe(out)

  add(document.body, 'click', failOnEvent)

  emitter = ever(el)
  emitter.emit('click', {cancelable: true, canBubble: true})

  assert.equal(out.received.length, 0, 'received zero events')
  add.removeEventListener(document.body, 'click', failOnEvent)
  evs.close()

  assert.end()

  function failOnEvent(ev) {
    assert.ok(!ev, 'should not see this event')
  }
})

test('test useCapture works', function(assert) {
  if(!document.addEventListener) {
    assert.ok(true, '(unsupported)')

    return assert.end()
  }

  var el = setup()
    , out = sink()
    , order = []
    , emitter
    , outer
    , inner

  outer = events(document.body, 'click', {useCapture: true})

  outer.on('data', function() {
    order.push(outer.element.tagName)
  })

  inner = events(el, 'click')
  inner.on('data', function() {
    order.push(inner.element.tagName)
  })

  emitter = ever(el)
  emitter.emit('click', {cancelable: true, canBubble: true})

  assert.deepEqual(order, ['BODY', 'A'])

  outer.close()
  inner.close()
  assert.end()
})

test('test .close() cancels future events', function(assert) {
  var el = setup()
    , out = sink()
    , order = []
    , emitter
    , stream

  stream = events(el, 'click')

  stream.pipe(out)

  emitter = ever(el)
  emitter.emit('click', {cancelable: true, canBubble: true})

  assert.equal(out.received.length, 1)
  stream.close()

  emitter.emit('click', {cancelable: true, canBubble: true})
  assert.equal(out.received.length, 1)

  assert.end()
})

test('test multiple instances work in tandem', function(assert) {
  assert.end()
})

function setup() {
  var element = document.createElement('a')

  element.href = '#test'
  document.body.appendChild(element)

  return element
}

function sink() {
  var stream = new readable.Writable({objectMode: true})
    , accum = []

  stream._write = function(chunk, enc, ready) {
    accum.push(chunk)
    ready()
  }

  stream.received = accum

  return stream
}


text:
class AutomaticValidationController < ApplicationController
  around_filter :validate_schemas!
  before_filter :sanitize_params!

  # GET /automatic_validation/basic_get.json
  def_action_schema :basic_get do |s|
    s.documentation <<-EOS.strip_heredoc
      A title.

      A description.
      EOS
    s.request do |r|
      r.query_parameters do |s|
        s.doc <<-EOS.strip_heredoc
          A parameter

          An important parameter that should be equal to 42.
          Yes really!.
          EOS
        s.integer "param1", equal_to: 42
      end
    end
    s.response_for do |status|
      status.ok do |r|
        r.body do |s|
          s.integer "id", equal_to: 42
        end
      end
    end
  end

  def basic_get
    unless params['param1'] == 42
      raise "should never be raised since the validator has raised one when checking parameters."
    end
    respond_to do |format|
      format.json do
        result = { id: 42 }
        render json: result
      end
    end
  end

  # GET /automatic_validation/no_schema.json
  def no_schema_at_all
    respond_to do |format|
      format.json do
        render json: {}
      end
    end
  end

  def_action_schema :no_request_schema do |s|
    s.response_for do |status|
      status.ok do |r|
        r.body do |s|
          s.integer "id", equal_to: 42
        end
      end
    end
  end

  def no_request_schema
    respond_to do |format|
      format.json do
        result = { id: params[:returned_id] }
        render json: result, status: 200
      end
    end
  end

  # Route constraints prevent this endpoint to raise any validation error.
  def_action_schema :route_constraints do |s|
    s.request do |r|
      r.query_parameters do |s|
        s.string "param1", equal_to: "42"
      end
    end
  end

  def route_constraints
    unless params['param1'] == "42"
      raise "should never be rasised since the route has a constraint on this parameter value."
    end
    respond_to do |format|
      format.json do
        result = { id: 42 }
        render json: result
      end
    end
  end

  # Composite custom types like Circle and Point are expected in the parameters of this request.
  def_action_schema :composite_custom_types do |s|
    s.request do |r|
      r.query_parameters do |s|
        s.circle "circle"
        s.rgba "color"
      end
    end
  end

  def composite_custom_types
    expected_circle = Circle.new(Point.new(1.0, 2.0), 5.0)
    circle = params[:circle]
    unless circle == expected_circle
      raise "parameter circle '#{circle.inspect}' is not equal to '#{expected_circle.inspect}'"
    end
    expected_color = Rgba.new(0.0, 0.1, 0.2, 0.3)
    color = params[:color]
    unless color == expected_color
      raise "parameter color '#{color.inspect}' is not equal to '#{expected_color.inspect}'"
    end
    respond_to do |format|
      format.json do
        render json: true, status: :ok
      end
    end
  end

  def dump_uri_helpers
    result = {
      respect_path: respect_path,
      respect: {
        doc_path: respect.doc_path,
        root_path: respect.root_path,
      }
    }
    respond_to do |format|
      format.json do
        render json: result, status: :ok
      end
    end
  end

  def_action_schema :request_contextual_error do |s|
    s.request do |r|
      r.query_parameters do |s|
        s.hash "o1" do |s|
          s.hash "o2" do |s|
            s.integer "i", equal_to: 42
          end
        end
      end
    end
  end

  def request_contextual_error
    raise "Error should be raised before me!!"
  end

  def_action_schema :response_contextual_error do |s|
    s.response_for do |status|
      status.is 200 do |r|
        r.body do |s|
          s.hash "o1" do |s|
            s.hash "o2" do |s|
              s.integer "i", equal_to: 51
            end
          end
        end
      end
    end
  end

  def response_contextual_error
    respond_to do |format|
      format.json do
        result = { o1: { o2: { i: 42 } } }
        render json: result, status: :ok
      end
    end
  end

  def_action_schema :request_format do |s|
    s.request do |r|
      r.query_parameters do |s|
        s.integer "id", required: false
      end
    end
    s.response_for do |status|
      status.is :ok do |r|
        r.body do |s|
          s.integer "id", equal_to: 42
        end
      end
    end
  end

  def request_format
    respond_to do |format|
      format.json do
        render json: { id: 42 }, status: :ok
      end
      format.html # request_format.html.erb
      format.pdf do
        render pdf: "foo", status: :ok
      end
    end
  end

  # POST /automatic_validation/basic_post.json
  def_action_schema :basic_post do |s|
    s.request do |r|
      r.path_parameters do |s|
        s.integer "path_param", equal_to: 42
      end
      r.body_parameters do |s|
        s.integer "body_param", equal_to: 42
      end
    end
    s.response_for do |status|
      status.ok do |r|
        r.body do |s|
          s.integer "id", equal_to: 42
        end
      end
    end
  end

  def basic_post
    unless params['path_param'] == 42
      raise "should never be raised since the validator has raised one before when checking path_param"
    end
    unless params['body_param'] == 42
      raise "should never be raised since the validator has raised one before when checking body_param"
    end
    respond_to do |format|
      format.json do
        result = { id: request.request_parameters['response_param'] }
        render json: result
      end
    end
  end

  def_action_schema :check_request_headers do |s|
    s.request do |r|
      r.headers do |h|
        h["X-Test-Header"] = "value"
      end
    end
  end

  def check_request_headers
    unless request.headers["X-Test-Header"] == "value"
      raise "should never be raised since the validator has raised one before when checking headers"
    end
    respond_to do |format|
      format.json do
        render json: {}
      end
    end
  end

  def_action_schema :check_response_headers do |s|
    s.response_for do |status|
      status.ok do |r|
        r.headers do |h|
          h["X-Test-Header"] = "good"
        end
      end
    end
  end

  def check_response_headers
    headers["X-Test-Header"] = params["response_header_value"]
    respond_to do |format|
      format.json do
        render json: {}
      end
    end
  end

  def_action_schema :only_documentation do |s|
    s.documentation <<-EOS.strip_heredoc
      Request with no schema but a documentation.

      It should be documented even if it does not have any schema defined.
    EOS
  end

  def only_documentation
    respond_to do |format|
      format.json do
        render json: {}
      end
    end
  end

  def raise_no_method_error_schema
    raise NoMethodError, "user has raised NoMethodError"
  end

  def raise_name_error_schema
    raise NameError, "user has raised a NameError"
  end

end