text: export { default } from 'ivy-notifier/services/notifier';

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using CoreEngine;

namespace CoreEditor
{
	[ExtendedInspectorDrawer( typeof( NonNullAttribute ) )]
	public sealed class NonNullDrawerAttribute : Attribute, IDrawer
	{
		public NonNullDrawerAttribute( NonNullAttribute attribute )
		{
		}

		public bool DisplayProperty( SerializedProperty property, FieldInfo field, GUIContent label )
		{
			object value = null;

			if ( property.propertyType == SerializedPropertyType.String )
				value = property.stringValue;
			else if ( property.propertyType == SerializedPropertyType.ObjectReference )
				value = property.objectReferenceValue;

			return ExtendedInspectorDrawerAttribute.DrawProperty(IsValid(value),label, ()=> EditorGUILayout.PropertyField (property, label), GetError( value ) );
		}

		public bool IsValid( object value )
		{
			return ( value == null || value.Equals( null ) ) == false;
		}

		public string GetError( object value){ return "Value is null."; }

		public string Tooltip
		{
			get {
				return "NonNull";
			}
		}
	}
}


text:
using System;

namespace EPPlus.Core.Extensions.Exceptions
{
    public class ExcelValidationException : ExcelException
    {
        public ExcelValidationException(string message)
            : base(message)
        {
        }

        public ExcelValidationException(string message, Exception inner)
            : base(message, inner)
        {
        }
    }
}


text:
fabricator: true
---

Components

    Fully self-contained and re-usable components that can be utilised to build templates.

{{#each materials.components.items}}

  {{> f-item this}}

{{/each}}


text:
package org.apache.solr.core;

import org.apache.lucene.util.Version;
import org.apache.solr.common.SolrException;
import org.apache.solr.util.DOMUtil;
import org.apache.solr.util.SystemIdResolver;
import org.apache.solr.common.util.XMLErrorLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.apache.commons.io.IOUtils;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 */
public class Config {
  public static final Logger log = LoggerFactory.getLogger(Config.class);
  private static final XMLErrorLogger xmllog = new XMLErrorLogger(log);

  static final XPathFactory xpathFactory = XPathFactory.newInstance();

  private final Document doc;
  private final Document origDoc; // with unsubstituted properties
  private final String prefix;
  private final String name;
  private final SolrResourceLoader loader;

  /**
   * Builds a config from a resource name with no xpath prefix.
   */
  public Config(SolrResourceLoader loader, String name) throws ParserConfigurationException, IOException, SAXException
  {
    this( loader, name, null, null );
  }

  public Config(SolrResourceLoader loader, String name, InputSource is, String prefix) throws ParserConfigurationException, IOException, SAXException
  {
    this(loader, name, is, prefix, true);
  }
  /**
   * Builds a config:
   *

   * Note that the 'name' parameter is used to obtain a valid input stream if no valid one is provided through 'is'.
   * If no valid stream is provided, a valid SolrResourceLoader instance should be provided through 'loader' so
   * the resource can be opened (@see SolrResourceLoader#openResource); if no SolrResourceLoader instance is provided, a default one
   * will be created.
   *

   *

   * Consider passing a non-null 'name' parameter in all use-cases since it is used for logging & exception reporting.
   *

   * @param loader the resource loader used to obtain an input stream if 'is' is null
   * @param name the resource name used if the input stream 'is' is null
   * @param is the resource as a SAX InputSource
   * @param prefix an optional prefix that will be preprended to all non-absolute xpath expressions
   */
  public Config(SolrResourceLoader loader, String name, InputSource is, String prefix, boolean subProps) throws ParserConfigurationException, IOException, SAXException
  {
    if( loader == null ) {
      loader = new SolrResourceLoader( null );
    }
    this.loader = loader;
    this.name = name;
    this.prefix = (prefix != null && !prefix.endsWith("/"))? prefix + '/' : prefix;
    try {
      javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      if (is == null) {
        is = new InputSource(loader.openConfig(name));
        is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(name));
      }

      // only enable xinclude, if a SystemId is available
      if (is.getSystemId() != null) {
        try {
          dbf.setXIncludeAware(true);
          dbf.setNamespaceAware(true);
        } catch(UnsupportedOperationException e) {
          log.warn(name + " XML parser doesn't support XInclude option");
        }
      }

      final DocumentBuilder db = dbf.newDocumentBuilder();
      db.setEntityResolver(new SystemIdResolver(loader));
      db.setErrorHandler(xmllog);
      try {
        doc = db.parse(is);
        origDoc = copyDoc(doc);
      } finally {
        // some XML parsers are broken and don't close the byte stream (but they should according to spec)
        IOUtils.closeQuietly(is.getByteStream());
      }
      if (subProps) {
        DOMUtil.substituteProperties(doc, loader.getCoreProperties());
      }
    } catch (ParserConfigurationException e)  {
      SolrException.log(log, "Exception during parsing file: " + name, e);
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    } catch (SAXException e)  {
      SolrException.log(log, "Exception during parsing file: " + name, e);
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    } catch (TransformerException e) {
      SolrException.log(log, "Exception during parsing file: " + name, e);
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    }
  }

  public Config(SolrResourceLoader loader, String name, Document doc) {
    this.prefix = null;
    this.doc = doc;
    try {
      this.origDoc = copyDoc(doc);
    } catch (TransformerException e) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    }
    this.name = name;
    this.loader = loader;
  }

  private static Document copyDoc(Document doc) throws TransformerException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer tx = tfactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    DOMResult result = new DOMResult();
    tx.transform(source, result);
    return (Document) result.getNode();
  }

  /**
   * @since solr 1.3
   */
  public SolrResourceLoader getResourceLoader()
  {
    return loader;
  }

  /**
   * @since solr 1.3
   */
  public String getResourceName() {
    return name;
  }

  public String getName() {
    return name;
  }

  public Document getDocument() {
    return doc;
  }

  public XPath getXPath() {
    return xpathFactory.newXPath();
  }

  private String normalize(String path) {
    return (prefix==null || path.startsWith("/")) ? path : prefix+path;
  }

  public void substituteProperties() {
    DOMUtil.substituteProperties(doc, loader.getCoreProperties());
  }

  public Object evaluate(String path, QName type) {
    XPath xpath = xpathFactory.newXPath();
    try {
      String xstr=normalize(path);

      // TODO: instead of prepending /prefix/, we could do the search rooted at /prefix...
      Object o = xpath.evaluate(xstr, doc, type);
      return o;

    } catch (XPathExpressionException e) {
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Error in xpath:" + path +" for " + name,e);
    }
  }

  public Node getNode(String path, boolean errifMissing) {
    return getNode(path, doc, errifMissing);
  }

  public Node getUnsubstitutedNode(String path, boolean errIfMissing) {
    return getNode(path, origDoc, errIfMissing);
  }

  public Node getNode(String path, Document doc, boolean errIfMissing) {
    XPath xpath = xpathFactory.newXPath();
    String xstr = normalize(path);

    try {
      NodeList nodes = (NodeList)xpath.evaluate(xstr, doc,
                                                XPathConstants.NODESET);
      if (nodes==null || 0 == nodes.getLength() ) {
        if (errIfMissing) {
          throw new RuntimeException(name + " missing "+path);
        } else {
          log.debug(name + " missing optional " + path);
          return null;
        }
      }
      if ( 1 < nodes.getLength() ) {
        throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,
                                 name + " contains more than one value for config path: " + path);
      }
      Node nd = nodes.item(0);
      log.trace(name + ":" + path + "=" + nd);
      return nd;

    } catch (XPathExpressionException e) {
      SolrException.log(log,"Error in xpath",e);
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Error in xpath:" + xstr + " for " + name,e);
    } catch (SolrException e) {
      throw(e);
    } catch (Exception e) {
      SolrException.log(log,"Error in xpath",e);
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Error in xpath:" + xstr+ " for " + name,e);
    }
  }

  public NodeList getNodeList(String path, boolean errIfMissing) {
    XPath xpath = xpathFactory.newXPath();
    String xstr = normalize(path);

    try {
      NodeList nodeList = (NodeList)xpath.evaluate(xstr, doc, XPathConstants.NODESET);

      if (null == nodeList) {
        if (errIfMissing) {
          throw new RuntimeException(name + " missing "+path);
        } else {
          log.debug(name + " missing optional " + path);
          return null;
        }
      }

      log.trace(name + ":" + path + "=" + nodeList);
      return nodeList;

    } catch (XPathExpressionException e) {
      SolrException.log(log,"Error in xpath",e);
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Error in xpath:" + xstr + " for " + name,e);
    } catch (SolrException e) {
      throw(e);
    } catch (Exception e) {
      SolrException.log(log,"Error in xpath",e);
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Error in xpath:" + xstr+ " for " + name,e);
    }
  }

  /**
   * Returns the set of attributes on the given element that are not among the given knownAttributes,
   * or null if all attributes are known.
   */
  public Set<String> getUnknownAttributes(Element element, String... knownAttributes) {
    Set<String> knownAttributeSet = new HashSet<>(Arrays.asList(knownAttributes));
    Set<String> unknownAttributeSet = null;
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0 ; i < attributes.getLength() ; ++i) {
      final String attributeName = attributes.item(i).getNodeName();
      if ( ! knownAttributeSet.contains(attributeName)) {
        if (null == unknownAttributeSet) {
          unknownAttributeSet = new HashSet<>();
        }
        unknownAttributeSet.add(attributeName);
      }
    }
    return unknownAttributeSet;
  }

  /**
   * Logs an error and throws an exception if any of the element(s) at the given elementXpath
   * contains an attribute name that is not among knownAttributes.
   */
  public void complainAboutUnknownAttributes(String elementXpath, String... knownAttributes) {
    SortedMap<String,SortedSet<String>> problems = new TreeMap<>();
    NodeList nodeList = getNodeList(elementXpath, false);
    for (int i = 0 ; i < nodeList.getLength() ; ++i) {
      Element element = (Element)nodeList.item(i);
      Set<String> unknownAttributes = getUnknownAttributes(element, knownAttributes);
      if (null != unknownAttributes) {
        String elementName = element.getNodeName();
        SortedSet<String> allUnknownAttributes = problems.get(elementName);
        if (null == allUnknownAttributes) {
          allUnknownAttributes = new TreeSet<>();
          problems.put(elementName, allUnknownAttributes);
        }
        allUnknownAttributes.addAll(unknownAttributes);
      }
    }
    if (problems.size() > 0) {
      StringBuilder message = new StringBuilder();
      for (Map.Entry<String,SortedSet<String>> entry : problems.entrySet()) {
        if (message.length() > 0) {
          message.append(", ");
        }
        message.append('<');
        message.append(entry.getKey());
        for (String attributeName : entry.getValue()) {
          message.append(' ');
          message.append(attributeName);
          message.append("=\"...\"");
        }
        message.append('>');
      }
      message.insert(0, "Unknown attribute(s) on element(s): ");
      String msg = message.toString();
      SolrException.log(log, msg);
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);
    }
  }

  public String getVal(String path, boolean errIfMissing) {
    Node nd = getNode(path,errIfMissing);
    if (nd==null) return null;

    String txt = DOMUtil.getText(nd);

    log.debug(name + ' '+path+'='+txt);
    return txt;

    /******
    short typ = nd.getNodeType();
    if (typ==Node.ATTRIBUTE_NODE || typ==Node.TEXT_NODE) {
      return nd.getNodeValue();
    }
    return nd.getTextContent();
    ******/
  }

  public String get(String path) {
    return getVal(path,true);
  }

  public String get(String path, String def) {
    String val = getVal(path, false);
    if (val == null || val.length() == 0) {
      return def;
    }
    return val;
  }

  public int getInt(String path) {
    return Integer.parseInt(getVal(path, true));
  }

  public int getInt(String path, int def) {
    String val = getVal(path, false);
    return val!=null ? Integer.parseInt(val) : def;
  }

  public boolean getBool(String path) {
    return Boolean.parseBoolean(getVal(path, true));
  }

  public boolean getBool(String path, boolean def) {
    String val = getVal(path, false);
    return val!=null ? Boolean.parseBoolean(val) : def;
  }

  public float getFloat(String path) {
    return Float.parseFloat(getVal(path, true));
  }

  public float getFloat(String path, float def) {
    String val = getVal(path, false);
    return val!=null ? Float.parseFloat(val) : def;
  }

  public double getDouble(String path){
     return Double.parseDouble(getVal(path, true));
   }

   public double getDouble(String path, double def) {
     String val = getVal(path, false);
     return val!=null ? Double.parseDouble(val) : def;
   }

   public Version getLuceneVersion(String path) {
     return parseLuceneVersionString(getVal(path, true));
   }

   public Version getLuceneVersion(String path, Version def) {
     String val = getVal(path, false);
     return val!=null ? parseLuceneVersionString(val) : def;
   }

  private static final AtomicBoolean versionWarningAlreadyLogged = new AtomicBoolean(false);

  public static final Version parseLuceneVersionString(final String matchVersion) {
    final Version version;
    try {
      version = Version.parseLeniently(matchVersion);
    } catch (IllegalArgumentException iae) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
        "Invalid luceneMatchVersion '" + matchVersion +
        "', valid values are: " + Arrays.toString(Version.values()) +
        " or a string in format 'V.V'", iae);
    }

    if (version == Version.LUCENE_CURRENT && !versionWarningAlreadyLogged.getAndSet(true)) {
      log.warn(
        "You should not use LUCENE_CURRENT as luceneMatchVersion property: "+
        "if you use this setting, and then Solr upgrades to a newer release of Lucene, "+
        "sizable changes may happen. If precise back compatibility is important "+
        "then you should instead explicitly specify an actual Lucene version."
      );
    }

    return version;
  }

  public Config getOriginalConfig() {
    return new Config(loader, null, origDoc);
  }

}


text:
<?xml version="1.0"?>
<mapping>
	<dbms product="IBM_DB2" id="ibmdb2_id" label="Mapping IBMDB2"
		default="true">
		<dbTypes>
				<dbType type="BIGINT" ignoreLen="true" ignorePre="true"/>
				<dbType type="BLOB" defaultLength="10" ignorePre="true"/>
				<dbType type="CHARACTER" defaultLength="50" ignorePre="true"/>
				<dbType type="CHAR" defaultLength="50" ignorePre="true"/>
				<dbType type="CLOB" ignorePre="true"/>
				<dbType type="DATE" ignoreLen="true" ignorePre="true"/>
				<dbType type="DECIMAL" defaultLength="20" defaultPrecision="10"/>
				<dbType type="DOUBLE" ignoreLen="true" ignorePre="true"/>
				<dbType type="FLOAT" ignoreLen="true" ignorePre="true" />
				<dbType type="GRAPHIC" defaultLength="20" ignoreLen="true" ignorePre="true"/>
				<dbType type="INTEGER" ignoreLen="true" ignorePre="true"/>
				<dbType type="LONG VARCHAR" ignoreLen="true" ignorePre="true"/>
				<dbType type="NUMERIC" defaultLength="20" defaultPrecision="10"/>
				<dbType type="SMALLINT" ignoreLen="true" ignorePre="true"/>
				<dbType type="TIME" ignoreLen="true" ignorePre="true"/>
				<dbType type="TIMESTAMP" ignoreLen="true" ignorePre="true"/>
				<dbType type="VARCHAR" default="true" defaultLength="200" ignorePre="true"/>
				<dbType type="VARGRAPHIC" defaultLength="20" ignorePre="true"/>
				<dbType type="XML" ignoreLen="true" ignorePre="true"/>
		</dbTypes>

		<language name="java">
			<talendToDbTypes><!-- Adviced mappings  -->
				<talendType type="id_List"/>
				<talendType type="id_Boolean">
					<dbType type="CHAR" default="true"/>
					<dbType type="INTEGER" />
				</talendType>
				<talendType type="id_Byte">
				</talendType>
				<talendType type="id_byte[]">
				</talendType>
				<talendType type="id_Character">
					<dbType type="CHARACTER" default="true"/>
					<dbType type="VARCHAR"/>
					<dbType type="LONG VARCHAR"/>
					<dbType type="CHAR"/>

				</talendType>
				<talendType type="id_Date">
					<dbType type="DATE"/>
					<dbType type="TIME"/>
					<dbType type="TIMESTAMP" default="true"/>
				</talendType>
				<talendType type="id_BigDecimal">
					<dbType type="DECIMAL" default="true"/>
					<dbType type="NUMERIC"/>
				</talendType>
				<talendType type="id_Double">
				    <dbType type="DOUBLE" default="true"/>
					<dbType type="DECIMAL"/>
					<dbType type="FLOAT"/>
					<dbType type="NUMERIC"/>
				</talendType>
				<talendType type="id_Float">
					<dbType type="FLOAT" default="true"/>
					<dbType type="DECIMAL"/>
					<dbType type="DOUBLE"/>
					<dbType type="NUMERIC"/>
				</talendType>
				<talendType type="id_Integer">
					<dbType type="INTEGER" default="true"/>
				</talendType>
				<talendType type="id_Long">
					<dbType type="BIGINT" default="true"/>
					<dbType type="INTEGER"/>
					<dbType type="SMALLINT"/>
				</talendType>
				<talendType type="id_Object">
					<dbType type="BLOB" default="true"/>
					<dbType type="CLOB"/>
					<dbType type="DECIMAL"/>
					<dbType type="GRAPHIC"/>
					<dbType type="VARGRAPHIC"/>
					<dbType type="XML"/>
				</talendType>
				<talendType type="id_Short">
					<dbType type="SMALLINT" default="true"/>
					<dbType type="INTEGER"/>
					<dbType type="BIGINT"/>
				</talendType>
				<talendType type="id_String">
					<dbType type="VARCHAR" default="true"/>
					<dbType type="LONG VARCHAR"/>
				</talendType>
			</talendToDbTypes>
			<dbToTalendTypes><!-- Adviced mappings  -->
				<dbType type="BIGINT">
					<talendType type="id_Long" default="true" />
					<talendType type="id_Short"/>
					<talendType type="id_Integer"/>
				</dbType>
				<dbType type="BLOB">
					<talendType type="id_Object" default="true" />
				</dbType>
				<dbType type="CHARACTER">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="CHAR">
					<talendType type="id_String" default="true" />
					<talendType type="id_Boolean"  />
				</dbType>
				<dbType type="CLOB">
					<talendType type="id_Object" default="true" />
				</dbType>
				<dbType type="DATE">
					<talendType type="id_Date" default="true" />
				</dbType>
				<dbType type="DECIMAL">
					<talendType type="id_Float"/>
					<talendType type="id_BigDecimal" default="true"/>
					<talendType type="id_Double"/>
				</dbType>
				<dbType type="DOUBLE">
					<talendType type="id_Double" default="true" />
					<talendType type="id_BigDecimal"/>
					<talendType type="id_Float"/>
				</dbType>
				<dbType type="FLOAT">
					<talendType type="id_Float" default="true" />
					<talendType type="id_BigDecimal"/>
					<talendType type="id_Double"/>
				</dbType>
				<dbType type="GRAPHIC">
					<talendType type="id_Object" default="true" />
				</dbType>
				<dbType type="INTEGER">
					<talendType type="id_Integer" default="true" />
					<talendType type="id_Long"/>
					<talendType type="id_Short"/>
				</dbType>
				<dbType type="LONG VARCHAR">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="NUMERIC">
					<talendType type="id_Float"/>
					<talendType type="id_BigDecimal" default="true"/>
					<talendType type="id_Double"/>
				</dbType>
				<dbType type="SMALLINT">
					<talendType type="id_Short" default="true" />
					<talendType type="id_Integer"/>
					<talendType type="id_Long"/>
				</dbType>
				<dbType type="TIME">
					<talendType type="id_Date" default="true" />
				</dbType>
				<dbType type="TIMESTAMP">
					<talendType type="id_Date" default="true" />
				</dbType>
				<dbType type="VARCHAR">
					<talendType type="id_String" default="true" />
				</dbType>
				<dbType type="VARGRAPHIC">
					<talendType type="id_Object" default="true" />
				</dbType>
				<dbType type="XML">
					<talendType type="id_Object" default="true" />
				</dbType>
			</dbToTalendTypes>
		</language>
	</dbms>

</mapping>


text:
var typeOf = require('precise-typeof');

// Public API
module.exports = hasValue;

/**
 * Checks if provided variable has value,
 * consider empty only if it's a string and has zero length, or it's NaN,
 * or it's `undefined` value, everything else consider a legit value
 *
 * @param   {mixed} value - string to check
 * @returns {boolean} - true is string is not empty, false otherwise
 */
function hasValue(value)
{
  if (typeOf(value) === 'string') {
    return value.length > 0;
  } else {
    return typeOf(value) !== 'undefined' && typeOf(value) !== 'nan';
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2013, Apptentive, Inc. All Rights Reserved.
  ~ Please refer to the LICENSE file for the terms and conditions
  ~ under which redistribution and use of this file is permitted.
  -->

<resources>
    <dimen name="apptentive_activity_side_padding">228dp</dimen>
    <dimen name="apptentive_activity_vertical_padding">0dp</dimen>
    <dimen name="apptentive_dialog_side_padding">274dp</dimen>
    <dimen name="apptentive_dialog_vertical_padding">0dp</dimen>
</resources>


text:
package com.sksamuel.scapegoat.inspections.collections

import com.sksamuel.scapegoat.PluginRunner
import org.scalatest.{ FreeSpec, Matchers, OneInstancePerTest }

/** @author Stephen Samuel */
class DuplicateMapKeyTest extends FreeSpec with Matchers with PluginRunner with OneInstancePerTest {

  override val inspections = Seq(new DuplicateMapKey)

  "DuplicateMapKey" - {
    "should report warning" in {
      val code = """object Test {
                      Map("name" -> "sam", "location" -> "aylesbury", "name" -> "bob")
                    } """.stripMargin

      compileCodeSnippet(code)
      compiler.scapegoat.feedback.warnings.size shouldBe 1
    }
    "should not report warning" - {
      "for duplicated strings" in {
        val code = """object Test {
                      Map("name" -> "sam", "location" -> "aylesbury", "name2" -> "bob")
                    } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 0
      }
      "for var args" in {
        val code = """object Test {
                          val tuples = List((1,2), (3,4))
                          Map(tuples : _ *)
                      } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 0
      }
      "for duplicated tuples using unicode" in {

        val code = """object Test {
                     |        Map(
                     |          "hp" → "HP",
                     |          "x" → "x",
                     |          "xp" → "XP",
                     |          "ie" → "IE",
                     |          "gb" → "GB",
                     |          "mb" → "MB",
                     |          "kb" → "KB",
                     |          "sp" → "SP",
                     |          "nt" → "NT")
                    } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 0
      }
    }
  }
}


text:
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta

"""Abstract class for tests of DGAs.

"""
class TestDGA(object):
  __metaclass__ = ABCMeta

  """Checks that couldUseDomain returns True for correct domains.

  """
  @abstractmethod
  def testCouldUseDomain(self):
    pass

  """Checks the lifetime value of domains for each DGA.

  """
  @abstractmethod
  def testDomainLifetime(self):
    pass

  """Checks that each DGA returns the expected number of domains for the current day.

  """
  @abstractmethod
  def testNbDomains(self):
    pass

  """Checks the presence of a few known domains for a given date.

  """
  @abstractmethod
  def testDomains(self):
    pass

  """Subroutine to check that a given DGA generates certain domains on a given date.

  The DGA must at least generate the expected domains but can generate more of them.

  Args:
    dga: Domain generation algorithm.
    samples: Array with a date and an array of domains generated on that date.

  Returns:
    True if the DGA generates the expected domains.
  """
  def checkDomains(self, dga, samples):
    date = datetime.strptime(samples[0], "%d/%m/%Y")
    domains = dga.domainsFor(date)
    return set(samples[1]).issubset(set(domains))


text:
package com.bellini.recipecatalog.exception.publication;

import com.bellini.recipecatalog.model.v1.Publication;

public class DuplicatePublicationException extends RuntimeException {

    private static final long serialVersionUID = -2458702761165927200L;
    private Publication pub;

    public DuplicatePublicationException(Publication pub) {
        super();
        if (pub == null) {
            throw new NullPointerException();
        }
        this.pub = pub;
    }

    @Override
    public String getMessage() {
        return "A record with volume " + pub.getVolume() + " and year " + pub.getYear() + " already exists";
    }
}


text:
package com.twitter.scrooge.java_generator

import com.twitter.scrooge.ast._
import com.twitter.scrooge.ast.Service

class ServiceController(service: Service, generator: ApacheJavaGenerator, ns: Option[Identifier])
  extends TypeController(service, generator, ns) {
  val extends_iface = service.parent match {
    case Some(parent) => Map("name" -> generator.qualifyNamedType(parent.sid, parent.filename).fullName)
    case None => false
  }
  val functions = service.functions map { f => new FunctionController(f, generator, ns) }
}


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkGraphAlgorithmWrap.h"
#include "vtkVertexDegreeWrap.h"
#include "vtkObjectBaseWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkVertexDegreeWrap::ptpl;

VtkVertexDegreeWrap::VtkVertexDegreeWrap()
{ }

VtkVertexDegreeWrap::VtkVertexDegreeWrap(vtkSmartPointer<vtkVertexDegree> _native)
{ native = _native; }

VtkVertexDegreeWrap::~VtkVertexDegreeWrap()
{ }

void VtkVertexDegreeWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkVertexDegree").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("VertexDegree").ToLocalChecked(), ConstructorGetter);
}

void VtkVertexDegreeWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkVertexDegreeWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkGraphAlgorithmWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkGraphAlgorithmWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkVertexDegreeWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetOutputArrayName", SetOutputArrayName);
	Nan::SetPrototypeMethod(tpl, "setOutputArrayName", SetOutputArrayName);

#ifdef VTK_NODE_PLUS_VTKVERTEXDEGREEWRAP_INITPTPL
	VTK_NODE_PLUS_VTKVERTEXDEGREEWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkVertexDegreeWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		vtkSmartPointer<vtkVertexDegree> native = vtkSmartPointer<vtkVertexDegree>::New();
		VtkVertexDegreeWrap* obj = new VtkVertexDegreeWrap(native);
		obj->Wrap(info.This());
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkVertexDegreeWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkVertexDegreeWrap *wrapper = ObjectWrap::Unwrap<VtkVertexDegreeWrap>(info.Holder());
	vtkVertexDegree *native = (vtkVertexDegree *)wrapper->native.GetPointer();
	vtkVertexDegree * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkVertexDegreeWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkVertexDegreeWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkVertexDegreeWrap *w = new VtkVertexDegreeWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkVertexDegreeWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkVertexDegreeWrap *wrapper = ObjectWrap::Unwrap<VtkVertexDegreeWrap>(info.Holder());
	vtkVertexDegree *native = (vtkVertexDegree *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
		vtkVertexDegree * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObjectBase *) a0->native.GetPointer()
		);
		VtkVertexDegreeWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkVertexDegreeWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkVertexDegreeWrap *w = new VtkVertexDegreeWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkVertexDegreeWrap::SetOutputArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkVertexDegreeWrap *wrapper = ObjectWrap::Unwrap<VtkVertexDegreeWrap>(info.Holder());
	vtkVertexDegree *native = (vtkVertexDegree *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetOutputArrayName(
			*a0
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
from ..rest import Resource
from ..describe import Description, autoDescribeRoute
from girder.api import access
from girder.constants import TokenScope
from girder.models.token import Token as TokenModel

class Token(Resource):
    """API Endpoint for non-user tokens in the system."""

    def __init__(self):
        super().__init__()
        self.resourceName = 'token'
        self._model = TokenModel()

        self.route('DELETE', ('session',), self.deleteSession)
        self.route('GET', ('session',), self.getSession)
        self.route('GET', ('current',), self.currentSession)
        self.route('GET', ('scopes',), self.listScopes)

    @access.public
    @autoDescribeRoute(
        Description('Retrieve the current session information.')
        .responseClass('Token')
    )
    def currentSession(self):
        return self.getCurrentToken()

    @access.public
    @autoDescribeRoute(
        Description('Get an anonymous session token for the system.')
        .notes('If you are logged in, this will return a token associated with that login.')
        .responseClass('Token')
    )
    def getSession(self):
        token = self.getCurrentToken()

        # Only create and send new cookie if token isn't valid or will expire soon
        if not token:
            token = self.sendAuthTokenCookie(None, scope=TokenScope.ANONYMOUS_SESSION)

        return {
            'token': token['_id'],
            'expires': token['expires']
        }

    @access.token
    @autoDescribeRoute(
        Description('Remove a session from the system.')
        .responseClass('Token')
        .notes('Attempts to delete your authentication cookie.')
    )
    def deleteSession(self):
        token = self.getCurrentToken()
        if token:
            self._model.remove(token)
        self.deleteAuthTokenCookie()
        return {'message': 'Session deleted.'}

    @access.public
    @autoDescribeRoute(
        Description('List all token scopes available in the system.')
    )
    def listScopes(self):
        return TokenScope.listScopes()


text:
import json
import os
import subprocess
import tempfile

from oslo_log import log

logger = log.getLogger('os-collect-config')

PROC_MOUNTS_PATH = '/proc/mounts'

class BlockDevice(object):

    devname = None

    type = None

    label = None

    mountpoint = None

    unmount = False

    ATTR_MAP = {
        'DEVNAME': 'devname',
        'TYPE': 'type',
        'LABEL': 'label'
    }

    @staticmethod
    def parse_shell_var(line):
        # parse shell-style KEY=value
        try:
            ieq = line.index('=')
        except (ValueError, AttributeError):
            return None, None
        value = line[ieq + 1:]
        # unescape backslash escaped spaces
        value = value.replace('\\ ', ' ')
        return line[:ieq], value

    @classmethod
    def from_blkid_export(cls, export_str):
        '''Construct BlockDevice from export formatted blkid output.'''
        bd = cls()
        for line in export_str.splitlines():
            var, value = cls.parse_shell_var(line)
            if var in cls.ATTR_MAP:
                setattr(bd, cls.ATTR_MAP[var], value)
        return bd

    def config_drive_candidate(self):
        '''Whether this block device is a v2 config-drive.'''
        return self.label == 'config-2' and self.type in (
            'vfat', 'iso9660')

    def ensure_mounted(self):
        '''Finds an existing mountpoint or mounts to a temp directory.'''
        self.unmount = False
        # check if already mounted, if so use that
        with open(PROC_MOUNTS_PATH, 'r') as f:
            for line in f.read().splitlines():
                values = line.split()
                if values[0] == self.devname:
                    self.mountpoint = values[1]
                    logger.debug('Found existing mounted config-drive: %s' %
                                 self.mountpoint)
                    return

        # otherwise mount readonly to a temp directory
        self.mountpoint = tempfile.mkdtemp(prefix='config-2-')
        cmd = ['mount', self.devname, self.mountpoint, '-o', 'ro']
        logger.debug('Mounting %s at : %s' % (self.devname, self.mountpoint))
        try:
            subprocess.check_output(cmd)
        except subprocess.CalledProcessError as e:
            logger.error('Problem running "%s": %s', ' '.join(cmd), e)
            os.rmdir(self.mountpoint)
            self.mountpoint = None
        else:
            self.unmount = True

    def cleanup(self):
        '''Unmounts device if mounted by ensure_mounted.'''
        if not self.unmount:
            self.mountpoint = None
            return
        if not self.mountpoint:
            self.unmount = False
            return

        cmd = ['umount', '-l', self.mountpoint]
        logger.debug('Unmounting: %s' % self.mountpoint)
        try:
            subprocess.check_output(cmd)
        except subprocess.CalledProcessError as e:
            logger.error('Problem running "%s": %s', ' '.join(cmd), e)
        else:
            os.rmdir(self.mountpoint)
            self.mountpoint = None
            self.unmount = False

    def get_metadata(self):
        '''Load and return ec2/latest/meta-data.json from config drive.'''
        try:
            self.ensure_mounted()
            if not self.mountpoint:
                return {}

            md_path = os.path.join(self.mountpoint,
                                   'ec2', 'latest', 'meta-data.json')
            if not os.path.isfile(md_path):
                logger.warn('No expected file at path: %s' % md_path)
                return {}
            with open(md_path, 'r') as f:
                return json.load(f)
        except Exception as e:
            logger.error('Problem getting metadata: %s', e)
            return {}
        finally:
            self.cleanup()

    def __repr__(self):
        return '%s: TYPE="%s" LABEL="%s"' % (self.devname,
                                             self.type,
                                             self.label)

def all_block_devices():
    '''Run blkid and yield a BlockDevice for all devices.'''
    try:
        cmd = ['blkid', '-o', 'export']
        out = subprocess.check_output(cmd, universal_newlines=True)
    except Exception as e:
        logger.error('Problem running "%s": %s', ' '.join(cmd), e)
    else:
        # with -o export, devices are separated by a blank line
        for device in out.split('\n\n'):
            yield BlockDevice.from_blkid_export(device)

def config_drive():
    """Return the first device expected to contain a v2 config drive.

    Disk needs to be:
    * either vfat or iso9660 formated
    * labeled with 'config-2'
    """
    for bd in all_block_devices():
        if bd.config_drive_candidate():
            return bd

def get_metadata():
    """Return discovered config drive metadata, or an empty dict."""
    bd = config_drive()
    if bd:
        return bd.get_metadata()
    return {}


text:
Feel free to [open issues](https://github.com/ChrisZieba/dodgercms/issues) and send pull requests on GitHub! When sending a pull request, please create a new topic/feature branch, and send your pull request from that branch. Please do *not* send pull requests from your `master` branch because this tends to lead to merge conflicts.

## Building

DodgerCMS uses [Grunt](http://gruntjs.com/), a JavaScript task runner that runs on [Node.js](https://nodejs.org/), for building and testing. You'll need Node.js and Grunt installed to work on DodgerCMS. Once installed, clone the `dodgermcs` repo (either the main repo or your fork) and install the plugins via npm:

```shell
$ git clone git://github.com/ChrisZieba/dodgercms.git
$ cd dodgercms/
$ npm install
```

Building DodgerCMS is easy, run `grunt`:

```shell
$ grunt
```

**Note:** To save your fingers from The Developer Konami Code: ⌘⇥ ↑ ⏎ run the `grunt watch` task with will continuously test and build DodgerCMS anytime a file changes:

```shell
$ grunt watch
```

## Testing

Before sending pull requests, please ensure that you open the test HTML files in these environments. If you don't have access to all these environments, list the ones that you have tested in on the pull request description. That way, we know what's missing, and can help you out.

[Grunt]: http://gruntjs.com/
[Node.js]: http://nodejs.org/

## Style Guide

DodgerCMS has adopted the [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) for writing JavaScript.


text:
#include "config.h"
#include "EditorClientWx.h"

#include "EditCommand.h"
#include "Editor.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "FrameView.h"
#include "HostWindow.h"
#include "KeyboardEvent.h"
#include "NotImplemented.h"
#include "Page.h"
#include "PlatformKeyboardEvent.h"
#include "WebFrame.h"
#include "WebFramePrivate.h"
#include "WebView.h"
#include "WebViewPrivate.h"
#include "WindowsKeyboardCodes.h"
#include <wtf/text/WTFString.h>

#include <stdio.h>

using namespace WebKit;

namespace WebCore {

static const unsigned CtrlKey = 1 << 0;
static const unsigned AltKey = 1 << 1;
static const unsigned ShiftKey = 1 << 2;

struct KeyDownEntry {
    unsigned virtualKey;
    unsigned modifiers;
    const char* name;
};

struct KeyPressEntry {
    unsigned charCode;
    unsigned modifiers;
    const char* name;
};

static const KeyDownEntry keyDownEntries[] = {
    { VK_LEFT,   0,                  "MoveLeft"                                    },
    { VK_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"                  },
    { VK_LEFT,   CtrlKey,            "MoveWordLeft"                                },
    { VK_LEFT,   CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection"              },
    { VK_RIGHT,  0,                  "MoveRight"                                   },
    { VK_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"                 },
    { VK_RIGHT,  CtrlKey,            "MoveWordRight"                               },
    { VK_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"             },
    { VK_UP,     0,                  "MoveUp"                                      },
    { VK_UP,     ShiftKey,           "MoveUpAndModifySelection"                    },
    { VK_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"                },
    { VK_DOWN,   0,                  "MoveDown"                                    },
    { VK_DOWN,   ShiftKey,           "MoveDownAndModifySelection"                  },
    { VK_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"              },
    { VK_PRIOR,  0,                  "MovePageUp"                                  },
    { VK_NEXT,   0,                  "MovePageDown"                                },
    { VK_HOME,   0,                  "MoveToBeginningOfLine"                       },
    { VK_HOME,   ShiftKey,           "MoveToBeginningOfLineAndModifySelection"     },
    { VK_HOME,   CtrlKey,            "MoveToBeginningOfDocument"                   },
    { VK_HOME,   CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },

    { VK_END,    0,                  "MoveToEndOfLine"                             },
    { VK_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"           },
    { VK_END,    CtrlKey,            "MoveToEndOfDocument"                         },
    { VK_END,    CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection"       },

    { VK_BACK,   0,                  "DeleteBackward"                              },
    { VK_BACK,   ShiftKey,           "DeleteBackward"                              },
    { VK_DELETE, 0,                  "DeleteForward"                               },
    { VK_BACK,   CtrlKey,            "DeleteWordBackward"                          },
    { VK_DELETE, CtrlKey,            "DeleteWordForward"                           },

    { 'B',       CtrlKey,            "ToggleBold"                                  },
    { 'I',       CtrlKey,            "ToggleItalic"                                },

    { VK_ESCAPE, 0,                  "Cancel"                                      },
    //FIXME: this'll never happen. We can trash it or make it a normal period
    { VK_OEM_PERIOD, CtrlKey,        "Cancel"                                      },
    { VK_TAB,    0,                  "InsertTab"                                   },
    { VK_TAB,    ShiftKey,           "InsertBacktab"                               },
    { VK_RETURN, 0,                  "InsertNewline"                               },
    { VK_RETURN, CtrlKey,            "InsertNewline"                               },
    { VK_RETURN, AltKey,             "InsertNewline"                               },
    { VK_RETURN, ShiftKey,           "InsertLineBreak"                               },
    { 'A',       CtrlKey,            "SelectAll"                                   },
    { 'Z',       CtrlKey,            "Undo"                                        },
    { 'Z',       CtrlKey | ShiftKey, "Redo"                                        },
};

static const KeyPressEntry keyPressEntries[] = {
    { '\t',   0,                  "InsertTab"                                   },
    { '\t',   ShiftKey,           "InsertBacktab"                               },
    { '\r',   0,                  "InsertNewline"                               },
    { '\r',   CtrlKey,            "InsertNewline"                               },
    { '\r',   AltKey,             "InsertNewline"                               },
    { '\r',   AltKey | ShiftKey,  "InsertNewline"                               },
};

EditorClientWx::~EditorClientWx()
{
    m_page = NULL;
}

void EditorClientWx::setPage(Page* page)
{
    m_page = page;
}

void EditorClientWx::pageDestroyed()
{
    delete this;
}

bool EditorClientWx::shouldDeleteRange(Range*)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldShowDeleteInterface(HTMLElement*)
{
    notImplemented();
    return false;
}

bool EditorClientWx::smartInsertDeleteEnabled()
{
    notImplemented();
    return false;
}

bool EditorClientWx::isSelectTrailingWhitespaceEnabled()
{
    notImplemented();
    return false;
}

bool EditorClientWx::isContinuousSpellCheckingEnabled()
{
    notImplemented();
    return false;
}

void EditorClientWx::toggleContinuousSpellChecking()
{
    notImplemented();
}

bool EditorClientWx::isGrammarCheckingEnabled()
{
    notImplemented();
    return false;
}

void EditorClientWx::toggleGrammarChecking()
{
    notImplemented();
}

int EditorClientWx::spellCheckerDocumentTag()
{
    notImplemented();
    return 0;
}

bool EditorClientWx::selectWordBeforeMenuEvent()
{
    notImplemented();
    return false;
}

bool EditorClientWx::shouldBeginEditing(Range*)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldEndEditing(Range*)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldInsertNode(Node*, Range*,
                                       EditorInsertAction)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldInsertText(const String&, Range*,
                                       EditorInsertAction)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldApplyStyle(StylePropertySet*,
                                       Range*)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldMoveRangeAfterDelete(Range*, Range*)
{
    notImplemented();
    return true;
}

bool EditorClientWx::shouldChangeSelectedRange(Range* fromRange, Range* toRange,
                                EAffinity, bool stillSelecting)
{
    notImplemented();
    return true;
}

void EditorClientWx::didBeginEditing()
{
    notImplemented();
}

void EditorClientWx::respondToChangedContents()
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin) {
            WebKit::WebViewContentsChangedEvent wkEvent(webKitWin);
            webKitWin->GetEventHandler()->ProcessEvent(wkEvent);
        }
    }
}

void EditorClientWx::didEndEditing()
{
    notImplemented();
}

void EditorClientWx::didWriteSelectionToPasteboard()
{
    notImplemented();
}

void EditorClientWx::didSetSelectionTypesForPasteboard()
{
    notImplemented();
}

void EditorClientWx::registerUndoStep(PassRefPtr<UndoStep> step)
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebView* webKitWin = dynamic_cast<WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin)
            webKitWin->m_impl->undoStack.append(step);
    }
}

void EditorClientWx::registerRedoStep(PassRefPtr<UndoStep> step)
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebView* webKitWin = dynamic_cast<WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin)
            webKitWin->m_impl->redoStack.append(step);
    }
}

void EditorClientWx::clearUndoRedoOperations()
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin) {
            webKitWin->m_impl->redoStack.clear();
            webKitWin->m_impl->undoStack.clear();
        }
    }
}

bool EditorClientWx::canCopyCut(Frame*, bool defaultValue) const
{
    return defaultValue;
}

bool EditorClientWx::canPaste(Frame*, bool defaultValue) const
{
    return defaultValue;
}

bool EditorClientWx::canUndo() const
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin) {
            return webKitWin->m_impl->undoStack.size() != 0;
        }
    }
    return false;
}

bool EditorClientWx::canRedo() const
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin && webKitWin) {
            return webKitWin->m_impl->redoStack.size() != 0;
        }
    }
    return false;
}

void EditorClientWx::undo()
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin) {
            webKitWin->m_impl->undoStack.last()->unapply();
            webKitWin->m_impl->undoStack.remove(--webKitWin->m_impl->undoStack.end());
        }
    }
}

void EditorClientWx::redo()
{
    Frame* frame = m_page->focusController()->focusedOrMainFrame();

    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin) {
            webKitWin->m_impl->redoStack.last()->reapply();
            webKitWin->m_impl->redoStack.remove(--webKitWin->m_impl->redoStack.end());
        }
    }
}

bool EditorClientWx::handleEditingKeyboardEvent(KeyboardEvent* event)
{
    Node* node = event->target()->toNode();
    ASSERT(node);
    Frame* frame = node->document()->frame();
    ASSERT(frame);

    const PlatformKeyboardEvent* keyEvent = event->keyEvent();

    //NB: this is what windows does, but they also have a keypress event for Alt+Enter which clearly won't get hit with this
    if (!keyEvent || keyEvent->altKey())  // do not treat this as text input if Alt is down
        return false;

    Editor::Command command = frame->editor()->command(interpretKeyEvent(event));

    if (keyEvent->type() == PlatformEvent::RawKeyDown) {
        // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
        // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or if not to let a CHAR event be generated
        // (e.g. Tab that inserts a Tab character, or Enter).
        return !command.isTextInsertion() && command.execute(event);
    }

     if (command.execute(event))
        return true;

    // Don't insert null or control characters as they can result in unexpected behaviour
    if (event->charCode() < ' ')
        return false;

    return frame->editor()->insertText(event->keyEvent()->text(), event);
}

const char* EditorClientWx::interpretKeyEvent(const KeyboardEvent* evt)
{
    ASSERT(evt->keyEvent()->type() == PlatformEvent::RawKeyDown || evt->keyEvent()->type() == PlatformEvent::Char);

    static HashMap<int, const char*>* keyDownCommandsMap = 0;
    static HashMap<int, const char*>* keyPressCommandsMap = 0;

    if (!keyDownCommandsMap) {
        keyDownCommandsMap = new HashMap<int, const char*>;
        keyPressCommandsMap = new HashMap<int, const char*>;

        for (unsigned i = 0; i < WXSIZEOF(keyDownEntries); i++)
            keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);

        for (unsigned i = 0; i < WXSIZEOF(keyPressEntries); i++)
            keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
    }

    unsigned modifiers = 0;
    if (evt->shiftKey())
        modifiers |= ShiftKey;
    if (evt->altKey())
        modifiers |= AltKey;
    if (evt->ctrlKey())
        modifiers |= CtrlKey;

    if (evt->keyEvent()->type() == PlatformEvent::RawKeyDown) {
        int mapKey = modifiers << 16 | evt->keyCode();
        return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
    }

    int mapKey = modifiers << 16 | evt->charCode();
    return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
}

void EditorClientWx::handleInputMethodKeydown(KeyboardEvent* event)
{
// NOTE: we don't currently need to handle this. When key events occur,
// both this method and handleKeyboardEvent get a chance at handling them.
// We might use this method later on for IME-specific handling.
}

void EditorClientWx::handleKeyboardEvent(KeyboardEvent* event)
{
    if (handleEditingKeyboardEvent(event))
        event->setDefaultHandled();
}

void EditorClientWx::textFieldDidBeginEditing(Element*)
{
    notImplemented();
}

void EditorClientWx::textFieldDidEndEditing(Element*)
{
    notImplemented();
}

void EditorClientWx::textDidChangeInTextField(Element*)
{
    notImplemented();
}

bool EditorClientWx::doTextFieldCommandFromEvent(Element*, KeyboardEvent*)
{
    notImplemented();
    return false;
}

void EditorClientWx::textWillBeDeletedInTextField(Element*)
{
    notImplemented();
}

void EditorClientWx::textDidChangeInTextArea(Element*)
{
    notImplemented();
}

void EditorClientWx::respondToChangedSelection(Frame* frame)
{
    if (frame) {
        WebKit::WebView* webKitWin = dynamic_cast<WebKit::WebView*>(frame->view()->hostWindow()->platformPageClient());
        if (webKitWin) {
            WebKit::WebViewSelectionChangedEvent wkEvent(webKitWin);
            webKitWin->GetEventHandler()->ProcessEvent(wkEvent);
        }
    }
}

bool EditorClientWx::shouldEraseMarkersAfterChangeSelection(TextCheckingType) const
{
    return true;
}

void EditorClientWx::ignoreWordInSpellDocument(const String&)
{
    notImplemented();
}

void EditorClientWx::learnWord(const String&)
{
    notImplemented();
}

void EditorClientWx::checkSpellingOfString(const UChar*, int length, int* misspellingLocation, int* misspellingLength)
{
    notImplemented();
}

void EditorClientWx::checkGrammarOfString(const UChar*, int length, Vector<GrammarDetail>&, int* badGrammarLocation, int* badGrammarLength)
{
    notImplemented();
}

void EditorClientWx::updateSpellingUIWithGrammarString(const String&, const GrammarDetail& detail)
{
    notImplemented();
}

void EditorClientWx::updateSpellingUIWithMisspelledWord(const String&)
{
    notImplemented();
}

void EditorClientWx::showSpellingUI(bool show)
{
    notImplemented();
}

bool EditorClientWx::spellingUIIsShowing()
{
    notImplemented();
    return false;
}

void EditorClientWx::getGuessesForWord(const String& word, const String& context, Vector<String>& guesses)
{
    notImplemented();
}

String EditorClientWx::getAutoCorrectSuggestionForMisspelledWord(const WTF::String&)
{
    notImplemented();
    return String();
}

void EditorClientWx::willSetInputMethodState()
{
    notImplemented();
}

void EditorClientWx::setInputMethodState(bool enabled)
{
    notImplemented();
}

}


text:
set -u

dynamic_dir=$(echo $0 | awk -F"dynamic" '{ print "dynamic_"$2 }' | sed 's/.bash//g')

if [ "$dynamic_dir" == "" ]; then
    echo "autodetect of exp name failed, set dynamic dir manyally"
    exit
fi

#######################################
#
# Cluster Setup
#
#######################################

# MacroBenchmark: Big Clusters

set -x

# Setup differs depending on where I launch this from
machine_name=$(uname -n)
if [ "$machine_name" == "wlloyds-macbook-pro.local" ]; then
    # # Local MBP

    # #!! server should be cmdline option
    # server=localhost

    # #location specific config
    # cops_dir="/Users/wlloyd/Documents/widekv/cassandra2"
    # kill_all_cmd="${cops_dir}/kill_all_cassandra.bash"
    # stress_killer="${cops_dir}/experiments/kill_stress_local_mbp.bash"

    # cluster_start_cmd() {
    # 	cd ${cops_dir};
    # 	./kill_all_cassandra.bash;
    # 	sleep 1;
    # 	./cassandra_dc_launcher.bash 1 1 wait;
    # 	cd -;
    # }
    echo "todo"
    exit
elif [ "$machine_name" == "node2.princeton.vicci.org" ]; then
    # VICCI, run from Princeton 1

    if [ $# -ne 2 ]; then
	echo "$0: [dcl_config] [client_config]"
	exit
    fi

    #location specific config
    cops_dir="/home/princeton_cops/cops2"
    exp_dir="${cops_dir}/experiments"
    stress_dir="${cops_dir}/tools/stress"
    output_dir_base="${exp_dir}/${dynamic_dir}"
    exp_uid=$(date +%s)
    output_dir="${output_dir_base}/${exp_uid}"
    mkdir -p ${output_dir}
    rm $output_dir_base/latest
    ln -s $output_dir $output_dir_base/latest

    dcl_config=$1
    dcl_config_full="${cops_dir}/vicci_dcl_config/${dcl_config}"

    all_servers=($(cat $dcl_config_full | grep cassandra_ips | awk -F"=" '{ print $2 }' | xargs))
    all_servers=$(echo "echo ${all_servers[@]}" | bash)
    num_dcs=$(cat $dcl_config_full | grep num_dcs | awk -F"=" '{ print $2 }')

    strategy_properties="DC0:1"
    for i in $(seq 1 $((num_dcs-1))); do
	strategy_properties=$(echo ${strategy_properties}",DC${i}:1")
    done

    num_servers=$(echo $all_servers | wc -w)
    num_servers_per_dc=$((num_servers / num_dcs))

    for dc in $(seq 0 $((num_dcs-1))); do
	this_dc_servers=$(echo $all_servers | sed 's/ /\n/g' | head -n $((num_servers_per_dc * (dc+1))) | tail -n $num_servers_per_dc | xargs)
	servers_by_dc[$dc]=${this_dc_servers}
    done
    echo ${servers_by_dc[@]}

    client_config=$2
    client_config_full="${cops_dir}/vicci_dcl_config/${client_config}"

    all_clients=$(cat $client_config_full | grep cassandra_ips | awk -F"=" '{ print $2 }' | xargs)
    all_clients=$(echo "echo ${all_clients[@]}" | bash)

    num_clients=$(echo $all_clients | wc -w)
    num_clients_per_dc=$((num_clients / num_dcs))

    for dc in $(seq 0 $((num_dcs-1))); do
	this_dc_clients=$(echo $all_clients | sed 's/ /\n/g' | head -n $((num_clients_per_dc * (dc+1))) | tail -n $num_clients_per_dc | xargs)
	clients_by_dc[$dc]=${this_dc_clients}
    done
    echo ${clients_by_dc[@]}

    kill_all_cmd="${cops_dir}/vicci_cassandra_killer.bash ${dcl_config_full}"
    stress_killer="${cops_dir}/kill_stress_vicci.bash"

    source dynamic_common

<<<<<<< HEAD

else
    echo "Unknown machine_name: ${machine_name}"
    exit
fi
=======
	    #write to ALL so the cluster is populated everywhere
	    ssh $client -o StrictHostKeyChecking=no "\
mkdir -p ~/${dynamic_dir}/${exp_uid}; \
$stress_killer; sleep 1; \
cd ${src_dir}/tools/stress; \
bin/stress \
--nodes=$first_dc_servers_csv \
--columns=$max_columns \
--column-size=$column_size \
--operation=${insert_cmd} \
--consistency-level=LOCAL_QUORUM \
--replication-strategy=NetworkTopologyStrategy \
--strategy-properties=$strategy_properties \
--num-different-keys=$keys_per_client \
--num-keys=$keys_per_client \
--stress-index=$index \
--stress-count=$num_clients \
> ~/${dynamic_dir}/${exp_uid}/populate.out" &

	done

	#wait for clients to finish
	for index in $(seq 0 $((num_clients - 1))); do
	    fg
	done

	set +m
    }

    cops_run_experiment() {
	internal_run_experiment $@ $cops_dir cops2
    }

    vanilla_run_experiment() {
	internal_run_experiment $@ $vanilla_dir vanilla
    }

    #all_servers is set above
    #num_clients is set above
    #all_clients is set above
    internal_run_experiment() {
	total_keys=$1
	column_size=$2
	cols_per_key_read=$3
	cols_per_key_write=$4
	keys_per_read=$5
	keys_per_write=$6
	write_frac=$7
	write_trans_frac=$8
	exp_time=$9
	variable=${10}
	trial=${11}
	src_dir=${12}
	cluster_type=${13}

	cli_output_dir="~/${dynamic_dir}/${exp_uid}/${cluster_type}/trial${trial}"
	data_file_name=$1_$2_$3_$4_$5_$6_$7_$8_$9+${10}+data

	#divide keys across all clients
	keys_per_client=$((total_keys / num_clients))

	set -m # need monitor mode to fg tasks

	#for dc in $(seq 0 $((num_dcs - 1))); do
	for dc in 0; do
	    local_servers_csv=$(echo ${servers_by_dc[$dc]} | sed 's/ /,/g')

	    for cli_index in $(seq 0 $((num_clients_per_dc - 1))); do
		client=$(echo ${clients_by_dc[$dc]} | sed 's/ /\n/g' | head -n $((cli_index+1)) | tail -n 1)

		ssh $client -o StrictHostKeyChecking=no "\
mkdir -p $cli_output_dir; \
cd ${src_dir}/tools/stress; \
((bin/stress \
--progress-interval=1 \
--nodes=$local_servers_csv \
--operation=DYNAMIC \
--consistency-level=LOCAL_QUORUM \
--replication-strategy=NetworkTopologyStrategy \
--strategy-properties=$strategy_properties \
--num-different-keys=$keys_per_client \
--stress-index=$cli_index \
--stress-count=$num_clients_per_dc \
--num-keys=2000000 \
--column-size=$column_size \
--columns-per-key-read=$cols_per_key_read \
--columns-per-key-write=$cols_per_key_write \
--keys-per-read=$keys_per_read \
--keys-per-write=$keys_per_write \
--write-fraction=$write_frac \
--write-transaction-fraction=$write_trans_frac \
--threads=16 \
| tee ${cli_output_dir}/${data_file_name}) &); sleep $((exp_time + 10)); ${exp_dir}/kill_stress_vicci.bash" &
	    done
	done
>>>>>>> 5cc13e9709b03d3ef9f09416a1bc5ec9e24f95d1

source dynamic_defaults

<<<<<<< HEAD
=======
    gather_results() {
	for dc in 0; do
            for cli_index in $(seq 0 $((num_clients_per_dc - 1))); do
		client_dir=${output_dir}/client${cli_index}
		client=$(echo ${clients_by_dc[$dc]} | sed 's/ /\n/g' | head -n $((cli_index+1)) | tail -n 1)
		rsync -az $client:${dynamic_dir}/${exp_uid}/* ${client_dir}
	    done
	done
    }
>>>>>>> 5cc13e9709b03d3ef9f09416a1bc5ec9e24f95d1

#######################################
#
# Actual Experiment
#
#######################################

# Test: Latency, Throughput of different operations
# Control: # of dependencies

<<<<<<< HEAD
# fixed parameters
run_length=40
trim=5

num_trials=2

for trial in $(seq 1 $num_trials); do
    for write_frac in 0.0 0.1 0.2 0.4 0.8 1.0; do
	variable=$write_frac
=======

#######################################
#
# Actual Experiment
#
#######################################

nservers=2
#be careful not to set total_keys too low, it creates pathological old version retention if we do that
total_keys=$((nservers*1000*1000))

value_size=1
cols_per_key_read=10
cols_per_key_write=10
keys_per_read=10
keys_per_write=10
write_frac=0.1
write_trans_frac=0.0
run_time=60
trial=1
>>>>>>> 5cc13e9709b03d3ef9f09416a1bc5ec9e24f95d1

    done
done

# Test: Latency, Throughput of different operations
# Control: # of dependencies

<<<<<<< HEAD
cops_cluster_start_cmd
cops_populate_cluster ${total_keys} ${cols_per_key_read} ${value_size}

#run_experiment keys cols_size cpkr cpkw kpr kpw wf wtf time var trial#
#run_experiment $((100*1000)) 1 1 1 1 1 .1 0.0 15 .1 1
cops_run_experiment $total_keys $value_size $cols_per_key_read $cols_per_key_write $keys_per_read $keys_per_write $write_frac $write_trans_frac $run_time $variable $trial

$kill_all_cmd

vanilla_cluster_start_cmd
vanilla_populate_cluster ${total_keys} ${cols_per_key_read} ${value_size}

#run_experiment keys cols_size cpkr cpkw kpr kpw wf wtf time var trial#
#run_experiment $((100*1000)) 1 1 1 1 1 .1 0.0 15 .1 1
vanilla_run_experiment $total_keys $value_size $cols_per_key_read $cols_per_key_write $keys_per_read $keys_per_write $write_frac $write_trans_frac $run_time $variable $trial

$kill_all_cmd

gather_results

=======
# fixed parameters
run_time=40
trim=5

num_trials=1
for trial in $(seq $num_trials); do
    for write_frac in 0.0 0.1 0.2 0.4 0.8 1.0; do
	variable=$write_frac
>>>>>>> 5cc13e9709b03d3ef9f09416a1bc5ec9e24f95d1

	cops_cluster_start_cmd
	cops_populate_cluster ${total_keys} ${cols_per_key_read} ${value_size} ${cols_per_key_write}

<<<<<<< HEAD

=======
        cops_run_experiment $total_keys $value_size $cols_per_key_read $cols_per_key_write $keys_per_read $keys_per_write $write_frac $write_trans_frac $run_time $variable $trial

	$kill_all_cmd
>>>>>>> 5cc13e9709b03d3ef9f09416a1bc5ec9e24f95d1

	vanilla_cluster_start_cmd
	vanilla_populate_cluster ${total_keys} ${cols_per_key_read} ${value_size} ${cols_per_key_write}

	vanilla_run_experiment $total_keys $value_size $cols_per_key_read $cols_per_key_write $keys_per_read $keys_per_write $write_frac $write_trans_frac $run_time $variable $trial

	$kill_all_cmd

	gather_results
    done
done

exit

#######################################
#
# Cleanup Experiment
#
#######################################
set +x
$kill_all_cmd
set -x

#######################################
#
# Process Output
#
#######################################
#${exp_dir}/dep_propagation_postprocess_full.bash ${exp_dir} $num_trials ${output_dir} ${run_time} ${trim}