text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.android.xml;

import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Ordering;
import com.google.devtools.build.android.AndroidDataWritingVisitor;
import com.google.devtools.build.android.AndroidDataWritingVisitor.StartTag;
import com.google.devtools.build.android.AndroidDataWritingVisitor.ValuesResourceDefinition;
import com.google.devtools.build.android.FullyQualifiedName;
import com.google.devtools.build.android.XmlResourceValue;
import com.google.devtools.build.android.XmlResourceValues;
import com.google.devtools.build.android.proto.SerializeFormat;
import com.google.protobuf.InvalidProtocolBufferException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;

import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

/**
 * Represents an Android Resource custom attribute.
 *
 *
Attribute are the most complicated Android resource, and therefore the least documented. Most
 * of the information about them is found by reading the android compatibility library source. An
 * Attribute defines a parameter that can be passed into a view class -- as such you can think of
 * attributes as creating slots for other resources to fit into. Each slot will have at least one
 * format, and can have multiples. Simple attributes (color, boolean, reference, dimension, float,
 * integer, string, and fraction) are defined as <attr name="name" format=
 * "format" /> while the complex ones, flag and enum, have sub parentTags: <attr
 * name= "name" &gt<flag name="name" value="value"> </attr>.
 *
 *
Attributes also have a double duty as defining validation logic for layout resources -- each
 * layout attribute *must* have a corresponding attribute which will be used to validate the
 * value/resource reference defined in it.
 *
 *
AttrXmlValue, due to the multiple types of attributes is actually a composite class that
 * contains multiple {@link XmlResourceValue} instances for each resource.
 */
@Immutable
public class AttrXmlResourceValue implements XmlResourceValue {

  private static final String FRACTION = "fraction";
  private static final String STRING = "string";
  private static final String INTEGER = "integer";
  private static final String FLOAT = "float";
  private static final String DIMENSION = "dimension";
  private static final String BOOLEAN = "boolean";
  private static final String COLOR = "color";
  private static final String REFERENCE = "reference";
  private static final String ENUM = "enum";
  private static final String FLAGS = "flags";
  private static final QName TAG_ENUM = QName.valueOf(ENUM);
  private static final QName TAG_FLAG = QName.valueOf("flag");
  private final ImmutableMap<String, ResourceXmlAttrValue> formats;

  private AttrXmlResourceValue(ImmutableMap<String, ResourceXmlAttrValue> formats) {
    this.formats = formats;
  }

  private static Map<String, String> readSubValues(XMLEventReader reader, QName subTagType)
      throws XMLStreamException {
    Builder<String, String> builder = ImmutableMap.builder();
    while (reader.hasNext()
        && XmlResourceValues.isTag(XmlResourceValues.peekNextTag(reader), subTagType)) {
      StartElement element = reader.nextEvent().asStartElement();
      builder.put(
          XmlResourceValues.getElementName(element), XmlResourceValues.getElementValue(element));
      XMLEvent endTag = reader.nextEvent();
      if (!XmlResourceValues.isEndTag(endTag, subTagType)) {
        throw new XMLStreamException(
            String.format("Unexpected [%s]; Expected %s", endTag, "</enum>"), endTag.getLocation());
      }
    }
    return builder.build();
  }

  private static void endAttrElement(XMLEventReader reader) throws XMLStreamException {
    XMLEvent endTag = reader.nextTag();
    if (!endTag.isEndElement() || !QName.valueOf("attr").equals(endTag.asEndElement().getName())) {
      throw new XMLStreamException("Unexpected ParentTag:" + endTag, endTag.getLocation());
    }
  }

  @VisibleForTesting
  private static final class BuilderEntry implements Entry<String, ResourceXmlAttrValue> {
    private final String name;
    private final ResourceXmlAttrValue value;

    BuilderEntry(String name, ResourceXmlAttrValue value) {
      this.name = name;
      this.value = value;
    }

    @Override
    public String getKey() {
      return name;
    }

    @Override
    public ResourceXmlAttrValue getValue() {
      return value;
    }

    @Override
    public ResourceXmlAttrValue setValue(ResourceXmlAttrValue value) {
      throw new UnsupportedOperationException();
    }
  }

  @SafeVarargs
  @VisibleForTesting
  public static XmlResourceValue fromFormatEntries(Entry<String, ResourceXmlAttrValue>... entries) {
    return of(ImmutableMap.copyOf(Arrays.asList(entries)));
  }

  @SuppressWarnings("deprecation")
  public static XmlResourceValue from(SerializeFormat.DataValueXml proto)
      throws InvalidProtocolBufferException {
    Builder<String, ResourceXmlAttrValue> formats =
        ImmutableMap.<String, AttrXmlResourceValue.ResourceXmlAttrValue>builder();
    for (Entry<String, SerializeFormat.DataValueXml> entry : proto.getMappedXmlValue().entrySet()) {
      switch (entry.getKey()) {
        case FLAGS:
          formats.put(
              entry.getKey(), FlagResourceXmlAttrValue.of(entry.getValue().getMappedStringValue()));
          break;
        case ENUM:
          formats.put(
              entry.getKey(), EnumResourceXmlAttrValue.of(entry.getValue().getMappedStringValue()));
          break;
        case REFERENCE:
          formats.put(entry.getKey(), ReferenceResourceXmlAttrValue.of());
          break;
        case COLOR:
          formats.put(entry.getKey(), ColorResourceXmlAttrValue.of());
          break;
        case BOOLEAN:
          formats.put(entry.getKey(), BooleanResourceXmlAttrValue.of());
          break;
        case DIMENSION:
          formats.put(entry.getKey(), DimensionResourceXmlAttrValue.of());
          break;
        case FLOAT:
          formats.put(entry.getKey(), FloatResourceXmlAttrValue.of());
          break;
        case INTEGER:
          formats.put(entry.getKey(), IntegerResourceXmlAttrValue.of());
          break;
        case STRING:
          formats.put(entry.getKey(), StringResourceXmlAttrValue.of());
          break;
        case FRACTION:
          formats.put(entry.getKey(), FractionResourceXmlAttrValue.of());
          break;
        default:
          throw new InvalidProtocolBufferException("Unexpected format: " + entry.getKey());
      }
    }
    return of(formats.build());
  }

  /**
   * Creates a new {@link AttrXmlResourceValue}. Returns null if there are no formats.
   */
  @Nullable
  public static XmlResourceValue from(
      StartElement attr, @Nullable String format, XMLEventReader eventReader)
      throws XMLStreamException {
    Set<String> formatNames = new HashSet<>();
    if (format != null) {
      Collections.addAll(formatNames, format.split("\\|"));
    }
    XMLEvent nextTag = XmlResourceValues.peekNextTag(eventReader);
    if (nextTag != null && nextTag.isStartElement()) {
      QName tagName = nextTag.asStartElement().getName();
      if (TAG_FLAG.equals(tagName)) {
        formatNames.add(FLAGS);
      } else {
        formatNames.add(tagName.getLocalPart().toLowerCase());
      }
    }

    Builder<String, ResourceXmlAttrValue> formats = ImmutableMap.builder();
    for (String formatName : formatNames) {
      switch (formatName) {
        case FLAGS:
          Map<String, String> flags = readSubValues(eventReader, TAG_FLAG);
          endAttrElement(eventReader);
          formats.put(formatName, FlagResourceXmlAttrValue.of(flags));
          break;
        case ENUM:
          Map<String, String> enums = readSubValues(eventReader, TAG_ENUM);
          endAttrElement(eventReader);
          formats.put(formatName, EnumResourceXmlAttrValue.of(enums));
          break;
        case REFERENCE:
          formats.put(formatName, ReferenceResourceXmlAttrValue.of());
          break;
        case COLOR:
          formats.put(formatName, ColorResourceXmlAttrValue.of());
          break;
        case BOOLEAN:
          formats.put(formatName, BooleanResourceXmlAttrValue.of());
          break;
        case DIMENSION:
          formats.put(formatName, DimensionResourceXmlAttrValue.of());
          break;
        case FLOAT:
          formats.put(formatName, FloatResourceXmlAttrValue.of());
          break;
        case INTEGER:
          formats.put(formatName, IntegerResourceXmlAttrValue.of());
          break;
        case STRING:
          formats.put(formatName, StringResourceXmlAttrValue.of());
          break;
        case FRACTION:
          formats.put(formatName, FractionResourceXmlAttrValue.of());
          break;
        default:
          throw new XMLStreamException(
              String.format("Unexpected attr format: %S", formatName), attr.getLocation());
      }
    }
    return of(formats.build());
  }

  public static XmlResourceValue of(ImmutableMap<String, ResourceXmlAttrValue> formats) {
    return new AttrXmlResourceValue(formats);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    AttrXmlResourceValue other = (AttrXmlResourceValue) o;
    return Objects.equals(formats, other.formats);
  }

  @Override
  public int hashCode() {
    return formats.hashCode();
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this).add("formats", formats).toString();
  }

  @Override
  public void write(
      FullyQualifiedName key, Path source, AndroidDataWritingVisitor mergedDataWriter) {

    if (formats.isEmpty()) {
      mergedDataWriter
          .define(key)
          .derivedFrom(source)
          .startTag("attr")
          .named(key)
          .closeUnaryTag()
          .save();
    } else {
      ImmutableList<String> formatKeys =
          FluentIterable.from(formats.keySet())
              .filter(not(equalTo(FLAGS)))
              .filter(not(equalTo(ENUM)))
              .toSortedList(Ordering.natural());
      StartTag startTag =
          mergedDataWriter
              .define(key)
              .derivedFrom(source)
              .startTag("attr")
              .named(key)
              .optional()
              .attribute("format")
              .setFrom(formatKeys)
              .joinedBy("|");
      ValuesResourceDefinition definition;
      if (formats.keySet().contains(FLAGS) || formats.keySet().contains(ENUM)) {
        definition = startTag.closeTag();
        for (ResourceXmlAttrValue value : formats.values()) {
          definition = value.writeTo(definition);
        }
        definition = definition.addCharactersOf("\n").endTag();
      } else {
        definition = startTag.closeUnaryTag();
      }
      definition.save();
    }
  }

  @SuppressWarnings("deprecation")
  @Override
  public int serializeTo(Path source, OutputStream output) throws IOException {
    SerializeFormat.DataValue.Builder builder =
        XmlResourceValues.newSerializableDataValueBuilder(source);
    SerializeFormat.DataValueXml.Builder xmlValueBuilder =
        SerializeFormat.DataValueXml.newBuilder();
    xmlValueBuilder.setType(SerializeFormat.DataValueXml.XmlType.ATTR);
    for (Entry<String, ResourceXmlAttrValue> entry : formats.entrySet()) {
      xmlValueBuilder
          .getMutableMappedXmlValue()
          .put(entry.getKey(), entry.getValue().appendTo(builder.getXmlValueBuilder()));
    }
    builder.setXmlValue(xmlValueBuilder);
    return XmlResourceValues.serializeProtoDataValue(output, builder);
  }

  @Override
  public XmlResourceValue combineWith(XmlResourceValue value) {
    throw new IllegalArgumentException(this + " is not a combinable resource.");
  }

  @CheckReturnValue
  interface ResourceXmlAttrValue {

    ValuesResourceDefinition writeTo(ValuesResourceDefinition writer);

    SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder);
  }

  // TODO(corysmith): The ResourceXmlAttrValue implementors, other than enum and flag, share a
  // lot of boilerplate. Determine how to reduce it.
  /** Represents an Android Enum Attribute resource. */
  @VisibleForTesting
  public static class EnumResourceXmlAttrValue implements ResourceXmlAttrValue {

    private Map<String, String> values;

    private EnumResourceXmlAttrValue(Map<String, String> values) {
      this.values = values;
    }

    @VisibleForTesting
    public static Entry<String, ResourceXmlAttrValue> asEntryOf(String... keyThenValue) {
      Preconditions.checkArgument(keyThenValue.length > 0);
      Preconditions.checkArgument(keyThenValue.length % 2 == 0);
      Builder<String, String> builder = ImmutableMap.builder();
      for (int i = 0; i < keyThenValue.length; i += 2) {
        builder.put(keyThenValue[i], keyThenValue[i + 1]);
      }
      return new BuilderEntry(ENUM, of(builder.build()));
    }

    public static ResourceXmlAttrValue of(Map<String, String> values) {
      return new EnumResourceXmlAttrValue(values);
    }

    @Override
    public int hashCode() {
      return values.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
      if (!(obj instanceof EnumResourceXmlAttrValue)) {
        return false;
      }
      EnumResourceXmlAttrValue other = (EnumResourceXmlAttrValue) obj;
      return Objects.equals(values, other.values);
    }

    @Override
    public String toString() {
      return MoreObjects.toStringHelper(getClass()).add("values", values).toString();
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.putAllMappedStringValue(values).build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      for (Entry<String, String> entry : values.entrySet()) {
        writer =
            writer
                .startTag("enum")
                .attribute("name")
                .setTo(entry.getKey())
                .attribute("value")
                .setTo(entry.getValue())
                .closeUnaryTag()
                .addCharactersOf("\n");
      }
      return writer;
    }
  }

  /** Represents an Android Flag Attribute resource. */
  @VisibleForTesting
  public static class FlagResourceXmlAttrValue implements ResourceXmlAttrValue {

    private Map<String, String> values;

    private FlagResourceXmlAttrValue(Map<String, String> values) {
      this.values = values;
    }

    public static ResourceXmlAttrValue of(Map<String, String> values) {
      // ImmutableMap guarantees a stable order.
      return new FlagResourceXmlAttrValue(ImmutableMap.copyOf(values));
    }

    @VisibleForTesting
    public static Entry<String, ResourceXmlAttrValue> asEntryOf(String... keyThenValue) {
      Builder<String, String> builder = ImmutableMap.builder();
      Preconditions.checkArgument(keyThenValue.length > 0);
      Preconditions.checkArgument(keyThenValue.length % 2 == 0);
      for (int i = 0; i < keyThenValue.length; i += 2) {
        builder.put(keyThenValue[i], keyThenValue[i + 1]);
      }
      return new BuilderEntry(FLAGS, of(builder.build()));
    }

    @Override
    public int hashCode() {
      return values.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
      if (!(obj instanceof FlagResourceXmlAttrValue)) {
        return false;
      }
      FlagResourceXmlAttrValue other = (FlagResourceXmlAttrValue) obj;
      return Objects.equals(values, other.values);
    }

    @Override
    public String toString() {
      return MoreObjects.toStringHelper(getClass()).add("values", values).toString();
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.putAllMappedStringValue(values).build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      for (Entry<String, String> entry : values.entrySet()) {
        writer =
            writer
                .startTag("flag")
                .attribute("name")
                .setTo(entry.getKey())
                .attribute("value")
                .setTo(entry.getValue())
                .closeUnaryTag();
      }
      return writer;
    }
  }

  /** Represents an Android Reference Attribute resource. */
  @VisibleForTesting
  public static class ReferenceResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final ReferenceResourceXmlAttrValue INSTANCE =
        new ReferenceResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(REFERENCE, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android Color Attribute resource. */
  @VisibleForTesting
  public static class ColorResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final ColorResourceXmlAttrValue INSTANCE = new ColorResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(COLOR, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android Boolean Attribute resource. */
  @VisibleForTesting
  public static class BooleanResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final BooleanResourceXmlAttrValue INSTANCE = new BooleanResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(BOOLEAN, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android Float Attribute resource. */
  @VisibleForTesting
  public static class FloatResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final FloatResourceXmlAttrValue INSTANCE = new FloatResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(FLOAT, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android Dimension Attribute resource. */
  @VisibleForTesting
  public static class DimensionResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final DimensionResourceXmlAttrValue INSTANCE =
        new DimensionResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(DIMENSION, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android Integer Attribute resource. */
  @VisibleForTesting
  public static class IntegerResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final IntegerResourceXmlAttrValue INSTANCE = new IntegerResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(INTEGER, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android String Attribute resource. */
  @VisibleForTesting
  public static class StringResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final StringResourceXmlAttrValue INSTANCE = new StringResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(STRING, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }

  /** Represents an Android Fraction Attribute resource. */
  @VisibleForTesting
  public static class FractionResourceXmlAttrValue implements ResourceXmlAttrValue {
    private static final FractionResourceXmlAttrValue INSTANCE = new FractionResourceXmlAttrValue();

    public static ResourceXmlAttrValue of() {
      return INSTANCE;
    }

    @VisibleForTesting
    public static BuilderEntry asEntry() {
      return new BuilderEntry(FRACTION, of());
    }

    @Override
    public SerializeFormat.DataValueXml appendTo(SerializeFormat.DataValueXml.Builder builder) {
      return builder.build();
    }

    @Override
    public ValuesResourceDefinition writeTo(ValuesResourceDefinition writer) {
      return writer;
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>sg.edu.cs2103aug2015_w13_2j.ui</title>
<meta name="date" content="2015-11-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

sg.edu.cs2103aug2015_w13_2j.ui

Interfaces

UIInterface

Classes

FeedbackMessage

FXCategoryAccordion

FXUI

TextPane

TextUI

UIStub

Enums

FeedbackMessage.FeedbackType

redpajama_set_name: RedPajamaGithub


text:
/*
 * This software is licensed under the Apache License, Version 2.0
 * (the "License") agreement; 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.force66.beantester.testbeans;

import java.io.Serializable;
import java.util.GregorianCalendar;

import javax.xml.datatype.XMLGregorianCalendar;

import org.force66.beantester.CallingRegistry;

public class DateBean extends BaseBean implements Serializable {

	private static final long serialVersionUID = -6175954579083249160L;

	private java.util.Date			utilDateValue;
	private java.sql.Date			sqlDateValue;
	private java.sql.Time			sqlTimeValue;
	private java.sql.Timestamp  	sqlTimestampValue;
	private GregorianCalendar		gregorianCalendarValue;
	private XMLGregorianCalendar	xmlGregorianCalendarValue;
	public java.util.Date getUtilDateValue() {
		CallingRegistry.addCall("getUtilDateValue");
		return utilDateValue;
	}
	public void setUtilDateValue(java.util.Date utilDateValue) {
		CallingRegistry.addCall("setUtilDateValue");
		this.utilDateValue = utilDateValue;
	}
	public java.sql.Date getSqlDateValue() {
		CallingRegistry.addCall("getSqlDateValue");
		return sqlDateValue;
	}
	public void setSqlDateValue(java.sql.Date sqlDateValue) {
		CallingRegistry.addCall("setSqlDateValue");
		this.sqlDateValue = sqlDateValue;
	}
	public java.sql.Time getSqlTimeValue() {
		CallingRegistry.addCall("getSqlTimeValue");
		return sqlTimeValue;
	}
	public void setSqlTimeValue(java.sql.Time sqlTimeValue) {
		CallingRegistry.addCall("setSqlTimeValue");
		this.sqlTimeValue = sqlTimeValue;
	}
	public java.sql.Timestamp getSqlTimestampValue() {
		CallingRegistry.addCall("getSqlTimestampValue");
		return sqlTimestampValue;
	}
	public void setSqlTimestampValue(java.sql.Timestamp sqlTimestampValue) {
		CallingRegistry.addCall("setSqlTimestampValue");
		this.sqlTimestampValue = sqlTimestampValue;
	}
	public GregorianCalendar getGregorianCalendarValue() {
		CallingRegistry.addCall("getGregorianCalendarValue");
		return gregorianCalendarValue;
	}
	public void setGregorianCalendarValue(GregorianCalendar gregorianCalendarValue) {
		CallingRegistry.addCall("setGregorianCalendarValue");
		this.gregorianCalendarValue = gregorianCalendarValue;
	}
	public XMLGregorianCalendar getXmlGregorianCalendarValue() {
		CallingRegistry.addCall("getXmlGregorianCalendarValue");
		return xmlGregorianCalendarValue;
	}
	public void setXmlGregorianCalendarValue(
			XMLGregorianCalendar xmlGregorianCalendarValue) {
		CallingRegistry.addCall("setXmlGregorianCalendarValue");
		this.xmlGregorianCalendarValue = xmlGregorianCalendarValue;
	}

}


text:
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace JexusManager.Features.Caching
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Reactive.Disposables;
    using System.Reactive.Linq;
    using System.Windows.Forms;

    using Microsoft.Web.Administration;
    using Microsoft.Web.Management.Client.Win32;

    internal partial class CachingSettingsDialog : DialogForm
    {
        public CachingSettingsDialog(IServiceProvider serviceProvider, ConfigurationElement element)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbUser.Checked = (bool)element["enabled"];
            cbKernel.Checked = (bool)element["enableKernelCache"];
            txtSize.Text = element["maxResponseSize"].ToString();
            var limit = (uint)element["maxCacheSize"];
            cbLimit.Checked = limit != 0;
            if (cbLimit.Checked)
            {
                txtLimit.Text = limit.ToString();
            }

            var container = new CompositeDisposable();
            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern<EventArgs>(btnOK, "Click")
                .Subscribe(evt =>
                {
                    element["enableKernelCache"] = cbKernel.Checked;
                    element["enabled"] = cbUser.Checked;
                    element["maxResponseSize"] = uint.Parse(txtSize.Text);
                    if (!cbLimit.Checked)
                    {
                        element["maxCacheSize"] = 0U;
                    }
                    else
                    {
                        element["maxCacheSize"] = uint.Parse(txtLimit.Text);
                    }

                    DialogResult = DialogResult.OK;
                }));
        }

        private void PermissionsDialogHelpButtonClicked(object sender, CancelEventArgs e)
        {
            DialogHelper.ProcessStart("http://go.microsoft.com/fwlink/?LinkId=210522");
        }
    }
}


text:
Test for bug 62320:
Emit an error event when a request to enter full-screen is rejected.

Tests that the document is still messaged if the element requesting full screen is removed before the event is generated.


text: module.exports = require('./src/lumberjack');


text:
CREATE TABLE ren_cms_SettingStores2Locales (
		id INT IDENTITY(1,1) NOT NULL
		, langLine VARCHAR (250) NOT NULL
		, stid INT NOT NULL
)


text:
<?php

namespace Base\ModusPonens;

trait Morgan3Trait
{
	/**
	 * These parameters should be accessible from $this->context array
	 *
	 * $this->context['p']
	 * $this->context['q']
	 * $this->context['r']
	 */
	public function printTestMorganAssocOr() {
		// TODO implement this
		//throw new \Exception('Implement this action for rule: deMorganAssocOr.');
	}
	/**
	 * These parameters should be accessible from $this->context array
	 *
	 * $this->context['p']
	 * $this->context['q']
	 * $this->context['r']
	 */
	public function printTestMorganAssocAnd() {
		// TODO implement this
		//throw new \Exception('Implement this action for rule: deMorganAssocAnd.');
	}
	/**
	 * These parameters should be accessible from $this->context array
	 *
	 * $this->context['p']
	 * $this->context['q']
	 * $this->context['r']
	 */
	public function printTestMorganDistAnd() {
		// TODO implement this
		//throw new \Exception('Implement this action for rule: deMorganDistAnd.');
	}
	/**
	 * These parameters should be accessible from $this->context array
	 *
	 * $this->context['p']
	 * $this->context['q']
	 * $this->context['r']
	 */
	public function printTestMorganDistOr() {
		// TODO implement this
		//throw new \Exception('Implement this action for rule: deMorganDistOr.');
	}
}


text:
package org.springframework.transaction.config;

import org.w3c.dom.Element;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.ClassUtils;

/**
 * Parser for the <tx:jta-transaction-manager/> element,
 * autodetecting BEA WebLogic, IBM WebSphere and Oracle OC4J.
 *
 * @author Juergen Hoeller
 * @author Christian Dupuis
 * @since 2.5
 */
public class JtaTransactionManagerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser  {

	private static final String WEBLOGIC_JTA_TRANSACTION_MANAGER_CLASS_NAME =
			"org.springframework.transaction.jta.WebLogicJtaTransactionManager";

	private static final String WEBSPHERE_TRANSACTION_MANAGER_CLASS_NAME =
			"org.springframework.transaction.jta.WebSphereUowTransactionManager";

	private static final String OC4J_TRANSACTION_MANAGER_CLASS_NAME =
			"org.springframework.transaction.jta.OC4JJtaTransactionManager";

	private static final String JTA_TRANSACTION_MANAGER_CLASS_NAME =
			"org.springframework.transaction.jta.JtaTransactionManager";

	public static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME =
			AnnotationDrivenBeanDefinitionParser.DEFAULT_TRANSACTION_MANAGER_BEAN_NAME;

	private static final boolean weblogicPresent = ClassUtils.isPresent(
			"weblogic.transaction.UserTransaction", JtaTransactionManagerBeanDefinitionParser.class.getClassLoader());

	private static final boolean webspherePresent = ClassUtils.isPresent(
			"com.ibm.wsspi.uow.UOWManager", JtaTransactionManagerBeanDefinitionParser.class.getClassLoader());

	private static final boolean oc4jPresent = ClassUtils.isPresent(
			"oracle.j2ee.transaction.OC4JTransactionManager", JtaTransactionManagerBeanDefinitionParser.class.getClassLoader());

	protected String getBeanClassName(Element element) {
		if (weblogicPresent) {
			return WEBLOGIC_JTA_TRANSACTION_MANAGER_CLASS_NAME;
		}
		else if (webspherePresent) {
			return WEBSPHERE_TRANSACTION_MANAGER_CLASS_NAME;
		}
		else if (oc4jPresent) {
			return OC4J_TRANSACTION_MANAGER_CLASS_NAME;
		}
		else {
			return JTA_TRANSACTION_MANAGER_CLASS_NAME;
		}
	}

	protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) {
		return DEFAULT_TRANSACTION_MANAGER_BEAN_NAME;
	}

}


text:
/** A "variable" defined in the CONST section. It has a value
 *  defined at compile time and an associated type.
 */
public class Constant extends Variable {
	public Constant(String name) {
		super(name);
	}
}


text:
require 'twilio-ruby'

# Get your Account SID and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'

# Initialize Twilio Client
client = Twilio::REST::Client.new account_sid, auth_token

session = client.preview
                .proxy
                .services('KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                .sessions
                .create(unique_name: 'MyFirstSession')

puts session.sid


text:
class JSONValue
  def self.numeric?(val)
    !Float(val).nil? rescue false
  end

  def self.integral?(val)
    !Integer(val).nil? rescue false
  end

  def self.boolean?(val)
    val == boolean_string_true || val == boolean_string_false
  end

  def self.value(val)
    if integral?(val)
      Integer(val)
    elsif numeric?(val)
      Float(val)
    elsif boolean?(val)
      val == boolean_string_true
    else
      val
    end
  end

  def self.boolean_string_true
    'true'
  end

  def self.boolean_string_false
    'false'
  end

end


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Service\Converter;

use ApiPlatform\Core\Api\IdentifiersExtractor;
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\OperationType;
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
use ApiPlatform\Core\Api\UrlGeneratorInterface;
use ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameResolverInterface;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\OperationDataProviderTrait;
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Exception\InvalidIdentifierException;
use ApiPlatform\Core\Exception\ItemNotFoundException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Identifier\CompositeIdentifierParser;
use ApiPlatform\Core\Identifier\IdentifierConverterInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Util\AttributesExtractor;
use ApiPlatform\Core\Util\ResourceClassInfoTrait;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;
use Symfony\Component\Routing\RouterInterface;

/**
 * Copied from src/Bridge/Symfony/Routing/IriConverter.php to add getIriFromItemInSection method
 */
final class IriConverter implements IriConverterInterface
{
    use OperationDataProviderTrait;
    use ResourceClassInfoTrait;

    private $routeNameResolver;
    private $router;
    private $identifiersExtractor;

    public function __construct(
        PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
        PropertyMetadataFactoryInterface $propertyMetadataFactory,
        ItemDataProviderInterface $itemDataProvider,
        RouteNameResolverInterface $routeNameResolver,
        RouterInterface $router,
        PropertyAccessorInterface $propertyAccessor = null,
        IdentifiersExtractorInterface $identifiersExtractor = null,
        SubresourceDataProviderInterface $subresourceDataProvider = null,
        IdentifierConverterInterface $identifierConverter = null,
        ResourceClassResolverInterface $resourceClassResolver = null,
        ResourceMetadataFactoryInterface $resourceMetadataFactory = null
    ) {
        $this->itemDataProvider = $itemDataProvider;
        $this->routeNameResolver = $routeNameResolver;
        $this->router = $router;
        $this->subresourceDataProvider = $subresourceDataProvider;
        $this->identifierConverter = $identifierConverter;
        $this->resourceClassResolver = $resourceClassResolver;
        $this->identifiersExtractor = $identifiersExtractor ?: new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor ?? PropertyAccess::createPropertyAccessor());
        $this->resourceMetadataFactory = $resourceMetadataFactory;
    }

    /**
     * {@inheritdoc}
     *
     * @return object
     */
    public function getItemFromIri(string $iri, array $context = [])
    {
        try {
            $parameters = $this->router->match($iri);
        } catch (RoutingExceptionInterface $e) {
            throw new InvalidArgumentException(sprintf('No route matches "%s".', $iri), $e->getCode(), $e);
        }

        if (!isset($parameters['_api_resource_class'])) {
            throw new InvalidArgumentException(sprintf('No resource associated to "%s".', $iri));
        }

        if (isset($parameters['_api_collection_operation_name'])) {
            throw new InvalidArgumentException(sprintf('The iri "%s" references a collection not an item.', $iri));
        }

        $attributes = AttributesExtractor::extractAttributes($parameters);

        try {
            $identifiers = $this->extractIdentifiers($parameters, $attributes);
        } catch (InvalidIdentifierException $e) {
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
        }

        if ($this->identifierConverter) {
            $context[IdentifierConverterInterface::HAS_IDENTIFIER_CONVERTER] = true;
        }

        if (isset($attributes['subresource_operation_name'])) {
            if (($item = $this->getSubresourceData($identifiers, $attributes, $context)) && !\is_array($item)) {
                return $item;
            }

            throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
        }

        if ($item = $this->getItemData($identifiers, $attributes, $context)) {
            return $item;
        }

        throw new ItemNotFoundException(sprintf('Item not found for "%s".', $iri));
    }

    /**
     * {@inheritdoc}
     */
    public function getIriFromItem($item, int $referenceType = null): string
    {
        $resourceClass = $this->getResourceClass($item, true);

        try {
            $identifiers = $this->identifiersExtractor->getIdentifiersFromItem($item);
        } catch (RuntimeException $e) {
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for the item of type "%s"', $resourceClass), $e->getCode(), $e);
        }

        return $this->getItemIriFromResourceClass(
            $resourceClass,
            $identifiers,
            $this->getReferenceType($resourceClass, $referenceType)
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getIriFromItemInSection($item, string $section, int $referenceType = null): string
    {
        $resourceClass = $this->getResourceClass($item, true);

        try {
            $identifiers = $this->identifiersExtractor->getIdentifiersFromItem($item);
        } catch (RuntimeException $e) {
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for the item of type "%s"', $resourceClass), $e->getCode(), $e);
        }

        return $this->getItemIriFromResourceClass(
            $resourceClass,
            $identifiers,
            $this->getReferenceType($resourceClass, $referenceType),
            $section
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getIriFromResourceClass(string $resourceClass, int $referenceType = null): string
    {
        try {
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $this->getReferenceType($resourceClass, $referenceType));
        } catch (RoutingExceptionInterface $e) {
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = null, string $section = null): string
    {
        $routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM, $section ? ['section' => $section] : []);
        $metadata = $this->resourceMetadataFactory->create($resourceClass);

        if (\count($identifiers) > 1 && true === $metadata->getAttribute('composite_identifier', true)) {
            $identifiers = ['id' => CompositeIdentifierParser::stringify($identifiers)];
        }

        try {
            return $this->router->generate($routeName, $identifiers, $this->getReferenceType($resourceClass, $referenceType));
        } catch (RoutingExceptionInterface $e) {
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = null): string
    {
        try {
            return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $this->getReferenceType($resourceClass, $referenceType));
        } catch (RoutingExceptionInterface $e) {
            throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
        }
    }

    private function getReferenceType(string $resourceClass, ?int $referenceType): ?int
    {
        if (null === $referenceType && null !== $this->resourceMetadataFactory) {
            $metadata = $this->resourceMetadataFactory->create($resourceClass);
            $referenceType = $metadata->getAttribute('url_generation_strategy');
        }

        return $referenceType ?? UrlGeneratorInterface::ABS_PATH;
    }
}


text:
#!/bin/bash
set -e

SOURCE_BRANCH="master"
TARGET_BRANCH="gh-pages"

function doCompile {
mkdir -p out/centos7
docker build --rm=true -t local/zabbix-module-compilation -f dockerfiles/centos/Dockerfile .
docker run --rm -v $PWD/out/centos7:/tmp local/zabbix-module-compilation cp /root/zabbix/src/modules/zabbix_module_stress/zabbix_module_stress.so /tmp/zabbix_module_stress.so
docker rmi -f local/zabbix-module-compilation
cd out/centos7
md5sum zabbix_module_stress.so > md5sum.txt
sha1sum zabbix_module_stress.so > sha1sum.txt
sha256sum zabbix_module_stress.so > sha256sum.txt
cd ../..

mkdir -p out/debian8
docker build --rm=true -t local/zabbix-module-compilation -f dockerfiles/debian/Dockerfile .
docker run --rm -v $PWD/out/debian8:/tmp local/zabbix-module-compilation cp /root/zabbix/src/modules/zabbix_module_stress/zabbix_module_stress.so /tmp/zabbix_module_stress.so
docker rmi -f local/zabbix-module-compilation
cd out/debian8
md5sum zabbix_module_stress.so > md5sum.txt
sha1sum zabbix_module_stress.so > sha1sum.txt
sha256sum zabbix_module_stress.so > sha256sum.txt
cd ../..

mkdir -p out/ubuntu14
docker build --rm=true -t local/zabbix-module-compilation -f dockerfiles/ubuntu/Dockerfile .
docker run --rm -v $PWD/out/ubuntu14:/tmp local/zabbix-module-compilation cp /root/zabbix/src/modules/zabbix_module_stress/zabbix_module_stress.so /tmp/zabbix_module_stress.so
docker rmi -f local/zabbix-module-compilation
cd out/ubuntu14
md5sum zabbix_module_stress.so > md5sum.txt
sha1sum zabbix_module_stress.so > sha1sum.txt
sha256sum zabbix_module_stress.so > sha256sum.txt
cd ../..
}

# Pull requests and commits to other branches shouldn't try to deploy, just build to verify
if [ "$TRAVIS_PULL_REQUEST" != "false" -o "$TRAVIS_BRANCH" != "$SOURCE_BRANCH" ]; then
    echo "Skipping deploy; just doing a build."
    doCompile
    exit 0
fi

# Save some useful information
REPO=`git config remote.origin.url`
SSH_REPO=${REPO/https:\/\/github.com\//git@github.com:}
SHA=`git rev-parse --verify HEAD`

# Clone the existing gh-pages for this repo into out/
# Create a new empty branch if h-pages doesn't exist yet (should only happen on first deply)
git clone $REPO out
cd out
git checkout $TARGET_BRANCH || git checkout --orphan $TARGET_BRANCH
cd ..

# Clean out existing contents
rm -rf out/**/* || exit 0

# Run our compile script
doCompile

# Now let's go have some fun with the cloned repo
cd out
git config user.name "Travis CI"
git config user.email "$COMMIT_AUTHOR_EMAIL"

# If there are no changes to the compiled out (e.g. this is a README update) then just bail.
if [ -z `git diff --exit-code` ]; then
    echo "No changes to the output on this push; exiting."
    exit 0
fi

# Commit the "changes", i.e. the new version.
# The delta will show diffs between new and old versions.
git add centos7
git add debian8
git add ubuntu14
git commit -m "Deploy to GitHub Pages: ${SHA}"

# Get the deploy key by using Travis's stored variables to decrypt deploy_key.enc
ENCRYPTED_KEY_VAR="encrypted_${ENCRYPTION_LABEL}_key"
ENCRYPTED_IV_VAR="encrypted_${ENCRYPTION_LABEL}_iv"
ENCRYPTED_KEY=${!ENCRYPTED_KEY_VAR}
ENCRYPTED_IV=${!ENCRYPTED_IV_VAR}
openssl aes-256-cbc -K $ENCRYPTED_KEY -iv $ENCRYPTED_IV -in ../artifacts/deploy_key.enc -out deploy_key -d
chmod 600 deploy_key
eval `ssh-agent -s`
ssh-add deploy_key

# Now that we're all set up, we can push.
git push $SSH_REPO $TARGET_BRANCH


text:
package org.netbeans.modules.liberty.main;

import javax.enterprise.deploy.spi.DeploymentManager;
import org.netbeans.modules.j2ee.deployment.plugins.spi.J2eePlatformFactory;
import org.netbeans.modules.j2ee.deployment.plugins.spi.J2eePlatformImpl;

public class LibertyJ2eePlatformFactory extends J2eePlatformFactory {
    @Override
    public J2eePlatformImpl getJ2eePlatformImpl(DeploymentManager dm) {
        return new LibertyJ2eePlatformImpl();
    }
}


text:
<?php
ob_start();

$menu__area="experiments_my";
$title="my experiments";
include("header.php");

	experiment__current_experiment_summary($expadmindata['adminname'],"n");

	experiment__current_experiment_summary($expadmindata['adminname'],"y");

include("footer.php");

?>


text:
import { ensureSafeComponent } from '@embroider/util';
import ModelsTableCellEditToggleComponent from '../../themes/default/cell-edit-toggle';
import { getPaperButton } from '../../../../utils/emt/themes/ep';

export default class CellEditToggle extends ModelsTableCellEditToggleComponent {
  get PaperButton(): unknown {
    return ensureSafeComponent(getPaperButton(), this);
  }
}


text:
<?php
class WPBakeryShortCode_VC_Gmaps extends WPBakeryShortCode {
}


text:
package org.ovirt.engine.api.restapi.resource;

import java.util.Set;

import org.ovirt.engine.api.model.Disk;
import org.ovirt.engine.api.model.Disks;
import org.ovirt.engine.api.resource.StorageDomainContentDiskResource;
import org.ovirt.engine.api.resource.StorageDomainContentDisksResource;
import org.ovirt.engine.core.compat.Guid;

public class BackendExportDomainDisksResource
        extends AbstractBackendCollectionResource<Disk, org.ovirt.engine.core.common.businessentities.storage.Disk>
        implements StorageDomainContentDisksResource {

    AbstractBackendStorageDomainContentResource parent;

    public BackendExportDomainDisksResource(AbstractBackendStorageDomainContentResource parent) {
        super(Disk.class, org.ovirt.engine.core.common.businessentities.storage.Disk.class);
        this.parent = parent;
    }

    @Override
    public Disks list() {
        Disks disks = new Disks();
        for (Guid diskImageId : getDiskIds()) {
            disks.getDisks().add(addLinks(map(getDisk(diskImageId))));
        }
        return disks;
    }

    protected Set<Guid> getDiskIds() {
        return parent.getDiskMap().keySet();
    }

    protected org.ovirt.engine.core.common.businessentities.storage.Disk getDisk(Guid id) {
        java.util.Map<Guid, org.ovirt.engine.core.common.businessentities.storage.Disk> map = parent.getDiskMap();
        return map.get(id);
    }

    public AbstractBackendStorageDomainContentResource getParent() {
        return parent;
    }

    @Override
    public StorageDomainContentDiskResource getDiskResource(String id) {
        return inject(new BackendExportDomainDiskResource(id, this));
    }
}


text:
module Surveyable
  class Engine < ::Rails::Engine
    require 'jquery-rails'
    require 'jquery-ui-rails'

    config.generators do |g|
      g.test_framework :rspec, view_specs: false
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
首界面GridView的每个Item的布局文件
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"

>

    <ImageView
        android:id="@+id/goods_image"
        android:layout_width="300dp"
        android:layout_height="200dp"

        />
    <TextView
        android:id="@+id/goods_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/goods_image"
        android:maxEms="6"
        android:singleLine="true"
        android:textSize="15sp"/>
    <TextView
        android:id="@+id/goods_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/goods_image"
        android:layout_alignRight="@+id/goods_image"
        android:textColor="#FF3030"
        android:textSize="15sp" />

    <ImageView
        android:id="@+id/hengxian"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/goods_name"
        android:layout_alignLeft="@+id/goods_image"
        android:layout_alignRight="@+id/goods_image"
        android:src="@drawable/henxian"/>

    <TextView
        android:id="@+id/goods_attention"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/hengxian"
        android:layout_alignLeft="@+id/hengxian"
        android:layout_alignRight="@+id/hengxian"
        android:textSize="13sp"
        android:lines="2"
        android:text="这是我今年九月份才买的,只用了几天..."/>

    <TextView
        android:id="@+id/goods_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/goods_attention"
        android:layout_alignRight="@+id/goods_image"
        android:textSize="13sp"
        android:text="三天前"/>

</RelativeLayout>


text:
<!-- Generated template for the FeedComponent component -->
<ion-content fullscreen>
  <ion-refresher *ngIf="addRefresher" (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>

  <spinner [isVisible]="isFetching && !content.length"></spinner>
  <ion-list>
    <tweet *ngFor="let data of content;trackBy: trackById" [data]="data"></tweet>
  </ion-list>

  <ng-content></ng-content>

  <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
    <ion-infinite-scroll-content></ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>


text:
/* eslint-env mocha */
'use strict'

const { getDescribe, getIt, expect } = require('../utils/mocha')

/** @typedef { import("ipfsd-ctl/src/factory") } Factory */
/**
 * @param {Factory} common
 * @param {Object} options
 */
module.exports = (common, options) => {
  const describe = getDescribe(options)
  const it = getIt(options)

  describe('.bootstrap.list', function () {
    this.timeout(100 * 1000)

    let ipfs

    before(async () => { ipfs = (await common.spawn()).api })

    after(() => common.clean())

    it('should return a list of peers', async () => {
      const res = await ipfs.bootstrap.list()

      const peers = res.Peers
      expect(peers).to.exist()
    })
  })
}


text:
describe Idobata::Hook::Bitbucket, type: :hook do
  describe '#process_payload' do
    subject { hook.process_payload }

    let(:payload) { fixture_payload("bitbucket/#{event_type.sub(/:/, '_')}.json") }

    before do
      post payload, 'Content-Type' => 'application/json', 'X-Event-Key' => event_type
    end

    describe 'POST hook' do
      describe 'push event' do
        let(:event_type) { 'repo:push' }

        its([:source]) { should == <<-HTML.strip_heredoc }
          hibariya
          pushed to
          hibariya/test

              <tt>725b0f6</tt>
              Improve README

        HTML
      end

      describe 'fork event' do
        let(:event_type) { 'repo:fork' }

        its([:source]) { should == <<-HTML.strip_heredoc }
          masumiya
          forked from
          masumiya/test
          to
          forked_usertest/test
        HTML
      end

      describe 'commit comment created event' do
        let(:event_type) { 'repo:commit_comment_created' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            Yuichi Masumiya
            created commit comment to
            masumiya/test#17

Comment text

        HTML
      end
    end

    describe 'Pull Request POST hook' do

      describe 'pullrequest:created event' do
        let(:event_type) { 'pullrequest:created' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            Keita Urashima
            created pull request to
            hibariya/test#1
            This is ursm

hi

        HTML
      end

      describe 'pullrequest:fulfilled event' do
        let(:event_type) { 'pullrequest:fulfilled' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            hibariya
            merged pull request
            hibariya/test#2

        HTML
      end

      describe 'pullrequest:rejected event' do
        let(:event_type) { 'pullrequest:rejected' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            hibariya
            declined pull request
            hibariya/test#1

        HTML
      end

      describe 'pullrequest comment created event' do
        let(:event_type) { 'pullrequest:comment_created' }

        its([:source]) { should == <<-HTML.strip_heredoc }

          hibariya
          commented on pull request
          hibariya/test#1

That is ursm!

        HTML
      end

      describe 'pullrequest approve event' do
        let(:event_type) { 'pullrequest:approved' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            hibariya
            approved pull request
            hibariya/test#1

        HTML
      end

      describe 'pullrequest unapprove event' do
        let(:event_type) { 'pullrequest:unapproved' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            masumiya
            unapproved pull request
            masumiya/test#1

        HTML
      end
    end

    describe 'Issue POST hook' do
      context 'created' do
        let(:event_type) { 'issue:created' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            Yuichi Masumiya
            created issue to
            masumiya/test#1
            issue test

Issue description

        HTML
      end

      context 'updated' do
        let(:event_type) { 'issue:updated' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            Yuichi Masumiya
            updated issue to
            masumiya/test#1
            issue test

        HTML
      end

      context 'comment created' do
        let(:event_type) { 'issue:comment_created' }

        its([:source]) { should == <<-HTML.strip_heredoc }

            Yuichi Masumiya
            created issue comment to
            masumiya/test#17

Comment text

        HTML
      end
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 6(1): 59 (1908)

#### Original name
Rhabdospora fragariae G.F. Atk.

### Remarks
null


text:
@interface VIMNetworkTask : VIMTask <VIMNetworkTaskSessionManagerDelegate>

@property (nonatomic, strong, nullable) VIMNetworkTaskSessionManager *sessionManager;

@property (nonatomic, assign) NSUInteger backgroundTaskIdentifier;

- (void)taskDidComplete;

@end


text:
namespace RobotsFactory.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    public class ManufacturerExpense
    {
        [Key]
        public int ExpenseId { get; set; }

        public DateTime ReportDate { get; set; }

        public decimal Expense { get; set; }

        [ForeignKey("Manufacturer")]
        public int ManufacturerId { get; set; }

        public virtual Manufacturer Manufacturer { get; set; }
    }
}


text:
package org.n52.iceland.ds;

import org.n52.iceland.component.Component;
import org.n52.iceland.exception.ows.OwsExceptionReport;
import org.n52.iceland.ogc.ows.OwsOperation;
import org.n52.iceland.service.ConformanceClass;

/**
 * Interface for all operation Handlers.
 *
 * In 52N SOS version 4.x called OperationDAO
 *
 * @since 1.0.0
 */
public interface OperationHandler extends ConformanceClass, Component<OperationHandlerKey> {

    /**
     * TODO check if necessary in feature
     *
     * Get the operation name this Handler supports
     *
     * @return The supported operation name
     */
    String getOperationName();

    /**
     * Get the OperationsMetadata of the supported SOS operation for the
     * capabilities
     *
     * @param service
     *            OGC service identifier
     * @param version
     *            Service version
     * @return OperationsMetadata for the operation
     *
     * @throws OwsExceptionReport
     *             If an error occurs.
     */
    OwsOperation getOperationsMetadata(String service, String version) throws OwsExceptionReport;

}


text:
<?php

declare(strict_types=1);

namespace DummyEntity\Test\Factories;

use DummyEntity\Test\Entities\C;
use DummyEntity\TestFactory;
use Faker\Factory;

class CTestFactory extends TestFactory
{
    public static function create(array $values = null): C
    {
        $class = C::class;

        $faker = Factory::create();
        $constructor = [
            $faker->randomNumber(),
            $faker->optional()->name,
        ];

        return parent::createFromClass($class, $constructor, $values);
    }
}


text:
<?php

class Bootphp_KodocTest extends PHPUnit_Framework_TestCase
{
    public function provider_parse_basic()
    {
        return array(
            array(
                <<<'COMMENT'
/**
 * Description
 */
COMMENT
                ,
                array("
Description
\n", []),
            ),
            array(
                <<<'COMMENT'
/**
 * Description spanning
 * multiple lines
 */
COMMENT
                ,
                array("
Description spanning\nmultiple lines
\n", []),
            ),
            array(
                <<<'COMMENT'
/**
 * Description including
 *
 *     a code block
 */
COMMENT
                ,
                array("
Description including
\n\n
a code block\n
\n", []),
            ),
            array(
                <<<'COMMENT'
	/**
	 * Indented
	 */
COMMENT
                ,
                array("
Indented
\n", []),
            ),
            array(
                <<<'COMMENT'
/**
 * @tag Content
 */
COMMENT
                ,
                array('', array('tag' => array('Content'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @tag Multiple
 * @tag Tags
 */
COMMENT
                ,
                array('', array('tag' => array('Multiple', 'Tags'))),
            ),
            array(
                <<<'COMMENT'
/**
 * Description with tag
 * @tag Content
 */
COMMENT
                ,
                array(
                    "
Description with tag
\n",
                    array('tag' => array('Content')),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @trailingspace
 */
COMMENT
                ,
                array('', array('trailingspace' => array(''))),
            ),
            array(
                <<<'COMMENT'
/**
 * @tag Content that spans
 * multiple lines
 */
COMMENT
                ,
                array(
                    '',
                    array('tag' => array("Content that spans\nmultiple lines")),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @tag Content that spans
 *    multiple lines indented
 */
COMMENT
                ,
                array(
                    '',
                    array('tag' => array("Content that spans\n   multiple lines indented")),
                ),
            ),
        );
    }

    /**
     * @covers  Bootphp_Kodoc::parse
     *
     * @dataProvider    provider_parse_basic
     *
     * @param   string  $comment    Argument to the method
     * @param   array   $expected   Expected result
     */
    public function test_parse_basic($comment, $expected)
    {
        $this->assertSame($expected, Kodoc::parse($comment));
    }

    public function provider_parse_tags()
    {
        $route_api = Route::get('docs/api');

        return array(
            array(
                <<<'COMMENT'
/**
 * @access public
 */
COMMENT
                ,
                array('', []),
            ),
            array(
                <<<'COMMENT'
/**
 * @copyright Some plain text
 */
COMMENT
                ,
                array('', array('copyright' => array('Some plain text'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @copyright   (C) 2013-2017 Kilofox Studio
 */
COMMENT
                ,
                array('', array('copyright' => array('© 2008-2013 Bootphp Team'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @license Bootphp
 */
COMMENT
                ,
                array('', array('license' => array('Bootphp'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @license http://kilofox.net/license
 */
COMMENT
                ,
                array('', array('license' => array('http://kilofox.net/license'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @link http://kilofox.net
 */
COMMENT
                ,
                array('', array('link' => array('http://kilofox.net'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @link http://kilofox.net Description
 */
COMMENT
                ,
                array('', array('link' => array('Description'))),
            ),
            array(
                <<<'COMMENT'
/**
 * @see MyClass
 */
COMMENT
                ,
                array(
                    '',
                    array(
                        'see' => array(
                            'uri(array('class' => 'MyClass'))
                            ) . '">MyClass',
                        ),
                    ),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @see MyClass::method()
 */
COMMENT
                ,
                array(
                    '',
                    array(
                        'see' => array(
                            'uri(array('class' => 'MyClass')) . '#method'
                            ) . '">MyClass::method()',
                        ),
                    ),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @throws Exception
 */
COMMENT
                ,
                array(
                    '',
                    array(
                        'throws' => array(
                            'uri(array('class' => 'Exception'))
                            ) . '">Exception',
                        ),
                    ),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @throws Exception During failure
 */
COMMENT
                ,
                array(
                    '',
                    array(
                        'throws' => array(
                            'uri(array('class' => 'Exception'))
                            ) . '">Exception During failure',
                        ),
                    ),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @uses    MyClass
 */
COMMENT
                ,
                array(
                    '',
                    array(
                        'uses' => array(
                            'uri(array('class' => 'MyClass'))
                            ) . '">MyClass',
                        ),
                    ),
                ),
            ),
            array(
                <<<'COMMENT'
/**
 * @uses    MyClass::method()
 */
COMMENT
                ,
                array(
                    '',
                    array(
                        'uses' => array(
                            'uri(array('class' => 'MyClass')) . '#method'
                            ) . '">MyClass::method()',
                        ),
                    ),
                ),
            ),
        );
    }

    /**
     * @covers  Bootphp_Kodoc::format_tag
     * @covers  Bootphp_Kodoc::parse
     *
     * @dataProvider    provider_parse_tags
     *
     * @param   string  $comment    Argument to the method
     * @param   array   $expected   Expected result
     */
    public function test_parse_tags($comment, $expected)
    {
        $this->assertSame($expected, Kodoc::parse($comment));
    }

    /**
     * Provides test data for test_transparent_classes
     * @return array
     */
    public function provider_transparent_classes()
    {
        return array(
            // Bootphp_Core is a special case
            array('Bootphp', 'Bootphp_Core', null),
            array('Controller_Template', 'Bootphp_Controller_Template', null),
            array('Controller_Template', 'Bootphp_Controller_Template',
                array('Bootphp_Controller_Template' => 'Bootphp_Controller_Template',
                    'Controller_Template' => 'Controller_Template')
            ),
            array(false, 'Bootphp_Controller_Template',
                array('Bootphp_Controller_Template' => 'Bootphp_Controller_Template')),
            array(false, 'Controller_Template', null),
        );
    }

    /**
     * Tests Kodoc::is_transparent
     *
     * Checks that a selection of transparent and non-transparent classes give expected results
     *
     * @group bootphp.userguide.3529-configurable-transparent-classes
     * @dataProvider provider_transparent_classes
     * @param mixed $expected
     * @param string $class
     * @param array $classes
     */
    public function test_transparent_classes($expected, $class, $classes)
    {
        $result = Kodoc::is_transparent($class, $classes);
        $this->assertSame($expected, $result);
    }

}


text:
''' Provide the Auto property.

'''

#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Bokeh imports
from .enum import Enum

#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------

__all__ = (
    'Auto',
)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

class Auto(Enum):
    ''' Accepts only the string "auto".

    Useful for properties that can be configured to behave "automatically".

    Example:

        This property is often most useful in conjunction with the
        :class:`~bokeh.core.properties.Either` property.

        .. code-block:: python

            >>> class AutoModel(HasProps):
            ...     prop = Either(Float, Auto)
            ...

            >>> m = AutoModel()

            >>> m.prop = 10.2

            >>> m.prop = "auto"

            >>> m.prop = "foo"      # ValueError !!

            >>> m.prop = [1, 2, 3]  # ValueError !!

    '''
    def __init__(self):
        super().__init__("auto")

    def __str__(self):
        return self.__class__.__name__

    def _sphinx_type(self):
        return self._sphinx_prop_link()

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------


text:
package io.fabric8.partition.internal;

import io.fabric8.partition.TaskContext;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import io.fabric8.api.jcip.ThreadSafe;
import io.fabric8.api.scr.AbstractComponent;
import io.fabric8.partition.WorkItem;
import io.fabric8.partition.Worker;
import org.apache.mina.util.ConcurrentHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

@ThreadSafe
@Component(name = "io.fabric8.partition.worker.logging", label = "Fabric8 Logging Partition Worker", immediate = true, metatype = false)
@Service(Worker.class)
@org.apache.felix.scr.annotations.Properties(
        @Property(name = "type", value = LoggingWorker.TYPE)
)
public final class LoggingWorker extends AbstractComponent implements Worker {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingWorker.class);
    public static final String TYPE = "logging";

    @Activate
    void activate() {
        activateComponent();
    }

    @Deactivate
    void deactivate() {
        deactivateComponent();
    }

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void assign(TaskContext context, Set<WorkItem> workItems) {
        assertValid();
        for (WorkItem workItem : workItems) {
            LOGGER.info("Start taskId: {}, partition: {}.", context.getId(), workItem.getId());
        }
    }

    @Override
    public void release(TaskContext context, Set<WorkItem> workItems) {
        assertValid();
        for (WorkItem workItem : workItems) {
            LOGGER.info("Stop taskId: {}, partition: {}.", context.getId(), workItem.getId());
        }
    }

    @Override
    public void stop(TaskContext context) {
    }

    @Override
    public void stopAll() {
    }
}


text:
package Paws::CodeDeploy::DeleteDeploymentGroupOutput;
  use Moose;
  has HooksNotCleanedUp => (is => 'ro', isa => 'ArrayRef[Paws::CodeDeploy::AutoScalingGroup]', traits => ['NameInRequest'], request_name => 'hooksNotCleanedUp' );

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::CodeDeploy::DeleteDeploymentGroupOutput

=head1 ATTRIBUTES

=head2 HooksNotCleanedUp => ArrayRef[L<Paws::CodeDeploy::AutoScalingGroup>]

If the output contains no data, and the corresponding deployment group
contained at least one Auto Scaling group, AWS CodeDeploy successfully
removed all corresponding Auto Scaling lifecycle event hooks from the
Amazon EC2 instances in the Auto Scaling group. If the output contains
data, AWS CodeDeploy could not remove some Auto Scaling lifecycle event
hooks from the Amazon EC2 instances in the Auto Scaling group.

=head2 _request_id => Str

=cut

1;


text:
<?php
/**
 * Created by PhpStorm.
 * User: lagman
 * Date: 18.11.13
 * Time: 10:25
 */

class UnsavedFormWidget extends CWidget
{
    /** @var string */
    public $message;
    /** @var CActiveForm */
    public $form;

    public function init()
    {
        if (empty($this->message)) {
            throw new CException('Empty message');
        }

        if (!$this->form instanceof CActiveForm) {
            throw new CException('Wrong form model');
        }
    }

    public function run()
    {
        /** @var CClientScript $cs */
        $cs = Yii::app()->clientScript;
        $cs->registerScript('UnsavedForm', '
            var unsavedFormWarning = false;
            $(window).on("beforeunload", function(){
                if (unsavedFormWarning)
                    return "'.CHtml::encode($this->message).'";
            });
            $("#'.$this->form->id.' :input").change(function(){
                unsavedFormWarning = true;
            });

            $("#'.$this->form->id.' :input").keyup(function(){
                unsavedFormWarning = true;
            });

            $("#'.$this->form->id.'").submit(function(){
                unsavedFormWarning = false;
            });

        ', CClientScript::POS_READY);
    }
}


text:
package net.smart_eapp.catalog;

import java.io.InputStream;

import net.smart_eapp.BookStarter;
import net.smart_eapp.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class BookTop extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.book_top);

		TextView titleText = (TextView) findViewById(R.id_book_top.title_bar);
		titleText.setText(BookStarter.getBook().getBookTitle());
		ImageView topImage = (ImageView) findViewById(R.id_book_top.top);

		InputStream is;
		try {
			is = BookStarter.getBook().getTopFileStream();
			Bitmap bm = BitmapFactory.decodeStream(is);
			topImage.setImageBitmap(bm);
		} catch (Exception e) {
			e.printStackTrace();
		}
		topImage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = null;
				intent = new Intent(BookTop.this, net.smart_eapp.catalog.PageListActivity.class);
				startActivity(intent);
			}
		});
	}
}


text:
describe("Hooks", function() {

	var Absurd = require('../../index.js');

	it("Adding hook (add method)", function(done) {
		Absurd(function(api) {
			api.hook("add", function(rules, stylesheet) {
				expect(rules).toBeDefined();
				expect(stylesheet).not.toBeDefined();
				expect(rules.body).toBeDefined();
				expect(rules.body.fontSize).toBeDefined();
				expect(rules.body.fontSize).toBe("20px");
			}).add({
				body: {
					fontSize: "20px"
				}
			}).compile(function(err, css) {
				expect(css).toBe("body {\n  font-size: 20px;\n}\n");
				done();
			})
		});
	});

	it("Prevent default", function(done) {
		Absurd(function(api) {
			api.hook("add", function(rules, stylesheet) {
				return true;
			}).add({
				body: {
					fontSize: "20px"
				}
			}).compile(function(err, css) {
				expect(css).toBe("");
				done();
			})
		});
	});

	it("Adding hook (import method)", function(done) {
		Absurd(function(api) {
			api.hook("import", function(file) {
				if(file === "body-styles.bla") {
					api.add({
						body: {
							fontSize: "11.5px"
						}
					});
				}
			}).add({
				body: {
					fontSize: "20px"
				}
			}).import("body-styles.bla").compile(function(err, css) {
				expect(css).toBe("body {\n  font-size: 11.5px;\n}\n");
				done();
			})
		});
	});

	it("Adding hook (compile method)", function(done) {
		Absurd(function(api) {
			api.hook("compile", function(callback, options) {
				callback(null, "AbsurdJS is awesome!")
				return true;
			}).add({
				body: {
					fontSize: "20px"
				}
			}).import("body-styles.bla").compile(function(err, css) {
				expect(css).toBe("AbsurdJS is awesome!");
				done();
			})
		});
	});

});


text:
package com.flipkart.foxtrot.core.querystore.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.foxtrot.common.Document;
import com.flipkart.foxtrot.common.FieldType;
import com.flipkart.foxtrot.common.FieldTypeMapping;
import com.flipkart.foxtrot.common.TableFieldMapping;
import com.flipkart.foxtrot.core.MockElasticsearchServer;
import com.flipkart.foxtrot.core.TestUtils;
import com.flipkart.foxtrot.core.datastore.DataStore;
import com.flipkart.foxtrot.core.querystore.DocumentTranslator;
import com.flipkart.foxtrot.core.querystore.QueryExecutor;
import com.flipkart.foxtrot.core.querystore.QueryStoreException;
import com.flipkart.foxtrot.core.table.TableMetadataManager;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsLoader;
import com.google.common.collect.ImmutableList;
import com.shash.hbase.ds.RowKeyDistributorByHashPrefix;
import org.elasticsearch.action.get.GetResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

/**
 * Created by rishabh.goyal on 16/04/14.
 */
public class ElasticsearchQueryStoreTest {
    private MockElasticsearchServer elasticsearchServer;
    private DataStore dataStore;
    private ElasticsearchQueryStore queryStore;
    private ObjectMapper mapper;
    private TableMetadataManager tableMetadataManager;
    private final DocumentTranslator translator = new DocumentTranslator(new RowKeyDistributorByHashPrefix(
            new RowKeyDistributorByHashPrefix.OneByteSimpleHash(32)));

    @Before
    public void setUp() throws Exception {
        mapper = new ObjectMapper();
        ElasticsearchUtils.setMapper(mapper);
        dataStore = TestUtils.getDataStore();

        elasticsearchServer = new MockElasticsearchServer(UUID.randomUUID().toString());
        ElasticsearchConnection elasticsearchConnection = Mockito.mock(ElasticsearchConnection.class);
        when(elasticsearchConnection.getClient()).thenReturn(elasticsearchServer.getClient());
        ElasticsearchUtils.initializeMappings(elasticsearchConnection.getClient());
        tableMetadataManager = Mockito.mock(TableMetadataManager.class);
        when(tableMetadataManager.exists(TestUtils.TEST_TABLE_NAME)).thenReturn(true);
        when(tableMetadataManager.get(anyString())).thenReturn(TestUtils.TEST_TABLE);
        AnalyticsLoader analyticsLoader = new AnalyticsLoader(tableMetadataManager, dataStore, queryStore, elasticsearchConnection);
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        QueryExecutor queryExecutor = new QueryExecutor(analyticsLoader, executorService);
        queryStore = new ElasticsearchQueryStore(tableMetadataManager, elasticsearchConnection, dataStore);
    }

    @After
    public void tearDown() throws Exception {
        elasticsearchServer.shutdown();
    }

    @Test
    public void testSaveSingle() throws Exception {
        Document originalDocument = new Document();
        originalDocument.setId(UUID.randomUUID().toString());
        originalDocument.setTimestamp(System.currentTimeMillis());
        JsonNode data = mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"));
        originalDocument.setData(data);
        queryStore.save(TestUtils.TEST_TABLE_NAME, originalDocument);
        final Document translatedDocuemnt = translator.translate(tableMetadataManager.get(TestUtils.TEST_TABLE_NAME), originalDocument);
        GetResponse getResponse = elasticsearchServer
                        .getClient()
                        .prepareGet(ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE_NAME, originalDocument.getTimestamp()),
                                ElasticsearchUtils.DOCUMENT_TYPE_NAME,
                                translatedDocuemnt.getId())
                        .setFields("_timestamp").execute().actionGet();
        assertTrue("Id should exist in ES", getResponse.isExists());
        assertEquals("Id should match requestId", translatedDocuemnt.getId(), getResponse.getId());
        assertEquals("Timestamp should match request timestamp", translatedDocuemnt.getTimestamp(), getResponse.getField("_timestamp").getValue());
    }

    @Test
    public void testSaveSingleInvalidTable() throws Exception {
        Document expectedDocument = new Document();
        expectedDocument.setId(UUID.randomUUID().toString());
        expectedDocument.setTimestamp(System.currentTimeMillis());
        JsonNode data = mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"));
        expectedDocument.setData(data);
        try {
            queryStore.save(TestUtils.TEST_TABLE + "-missing", expectedDocument);
            fail();
        } catch (QueryStoreException qse) {
            assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, qse.getErrorCode());
        }
    }

    @Test
    public void testSaveBulk() throws Exception {
        List<Document> documents = new Vector<Document>();
        for (int i = 0; i < 10; i++) {
            documents.add(new Document(UUID.randomUUID().toString(),
                    System.currentTimeMillis(),
                    mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"))));
        }
        queryStore.save(TestUtils.TEST_TABLE_NAME, documents);
        final List<Document> translatedDocuemtns = translator.translate(tableMetadataManager.get(TestUtils.TEST_TABLE_NAME), documents);
        for (Document document : translatedDocuemtns) {
            GetResponse getResponse = elasticsearchServer
                    .getClient()
                    .prepareGet(ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE_NAME, document.getTimestamp()),
                            ElasticsearchUtils.DOCUMENT_TYPE_NAME,
                            document.getId())
                    .setFields("_timestamp").execute().actionGet();
            assertTrue("Id should exist in ES", getResponse.isExists());
            assertEquals("Id should match requestId", document.getId(), getResponse.getId());
            assertEquals("Timestamp should match request timestamp", document.getTimestamp(), getResponse.getField("_timestamp").getValue());
        }
    }

    @Test
    public void testSaveBulkNullList() throws Exception {
        List<Document> list = null;
        try {
            queryStore.save(TestUtils.TEST_TABLE_NAME, list);
            fail();
        } catch (QueryStoreException ex) {
            assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getErrorCode());
        }
    }

    @Test
    public void testSaveBulkEmptyList() throws Exception {
        List<Document> list = new Vector<Document>();
        try {
            queryStore.save(TestUtils.TEST_TABLE_NAME, list);
            fail();
        } catch (QueryStoreException ex) {
            assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getErrorCode());
        }
    }

    @Test
    public void testSaveBulkInvalidTable() throws Exception {
        List<Document> documents = new Vector<Document>();
        for (int i = 0; i < 10; i++) {
            documents.add(new Document(UUID.randomUUID().toString(),
                    System.currentTimeMillis(),
                    mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"))));
        }
        try {
            queryStore.save(TestUtils.TEST_TABLE + "-missing", documents);
            fail();
        } catch (QueryStoreException qse) {
            assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, qse.getErrorCode());
        }
    }

    @Test
    public void testGetSingle() throws Exception {
        String id = UUID.randomUUID().toString();
        long timestamp = System.currentTimeMillis();
        JsonNode data = mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"));
        Document document = new Document(id, System.currentTimeMillis(), data);
        document.setTimestamp(timestamp);
        queryStore.save(TestUtils.TEST_TABLE_NAME, document);
        elasticsearchServer.refresh(ElasticsearchUtils.getIndices(TestUtils.TEST_TABLE_NAME));
        Document responseDocument = queryStore.get(TestUtils.TEST_TABLE_NAME, id);
        assertNotNull(responseDocument);
        assertEquals(id, responseDocument.getId());
        assertEquals("Timestamp should match request timestamp", document.getTimestamp(), responseDocument.getTimestamp());
    }

    @Test
    public void testGetSingleInvalidId() throws Exception {
        try {
            queryStore.get(TestUtils.TEST_TABLE_NAME, UUID.randomUUID().toString());
        } catch (QueryStoreException qse) {
            assertEquals(QueryStoreException.ErrorCode.DOCUMENT_NOT_FOUND, qse.getErrorCode());
        }
    }

    @Test
    public void testGetBulk() throws Exception {
        Map<String, Document> idValues = new HashMap<String, Document>();
        List<String> ids = new Vector<String>();
        for (int i = 0; i < 10; i++) {
            String id = UUID.randomUUID().toString();
            ids.add(id);
            idValues.put(id,
                    new Document(id,
                            System.currentTimeMillis(),
                            mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"))));
            idValues.get(id).setTimestamp(System.currentTimeMillis());
        }
        queryStore.save(TestUtils.TEST_TABLE_NAME, ImmutableList.copyOf(idValues.values()));
        elasticsearchServer.refresh(ElasticsearchUtils.getIndices(TestUtils.TEST_TABLE_NAME));
        List<Document> responseDocuments = queryStore.getAll(TestUtils.TEST_TABLE_NAME, ids);
        HashMap<String, Document> responseIdValues = new HashMap<String, Document>();
        for (Document doc : responseDocuments) {
            responseIdValues.put(doc.getId(), doc);
        }
        assertNotNull("List of returned Documents should not be null", responseDocuments);
        for (String id : ids) {
            assertTrue("Requested Id should be present in response", responseIdValues.containsKey(id));
            assertNotNull(responseIdValues.get(id));
            assertEquals(id, responseIdValues.get(id).getId());
            assertEquals("Timestamp should match request timestamp", idValues.get(id).getTimestamp(), responseIdValues.get(id).getTimestamp());
            System.out.println("OK: " + id);
        }
    }

    @Test
    public void testGetBulkInvalidIds() throws Exception {
        try {
            queryStore.getAll(TestUtils.TEST_TABLE_NAME, Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()));
            fail();
        } catch (QueryStoreException qse) {
            assertEquals(QueryStoreException.ErrorCode.DOCUMENT_NOT_FOUND, qse.getErrorCode());
        }
    }

    @Test
    public void testGetFieldMappings() throws QueryStoreException, InterruptedException {
        queryStore.save(TestUtils.TEST_TABLE_NAME, TestUtils.getMappingDocuments(mapper));
        Thread.sleep(500);

        Set<FieldTypeMapping> mappings = new HashSet<FieldTypeMapping>();
        mappings.add(new FieldTypeMapping("word", FieldType.STRING));
        mappings.add(new FieldTypeMapping("data.data", FieldType.STRING));
        mappings.add(new FieldTypeMapping("header.hello", FieldType.STRING));
        mappings.add(new FieldTypeMapping("head.hello", FieldType.LONG));

        TableFieldMapping tableFieldMapping = new TableFieldMapping(TestUtils.TEST_TABLE_NAME, mappings);
        TableFieldMapping responseMapping = queryStore.getFieldMappings(TestUtils.TEST_TABLE_NAME);

        assertEquals(tableFieldMapping.getTable(), responseMapping.getTable());
        assertTrue(tableFieldMapping.getMappings().equals(responseMapping.getMappings()));
    }

    @Test
    public void testGetFieldMappingsNonExistingTable() throws QueryStoreException {
        try {
            queryStore.getFieldMappings(TestUtils.TEST_TABLE + "-test");
            fail();
        } catch (QueryStoreException qse) {
            assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, qse.getErrorCode());
        }
    }

    @Test
    public void testGetFieldMappingsNoDocumentsInTable() throws QueryStoreException {
        TableFieldMapping request = new TableFieldMapping(TestUtils.TEST_TABLE_NAME, new HashSet<FieldTypeMapping>());
        TableFieldMapping response = queryStore.getFieldMappings(TestUtils.TEST_TABLE_NAME);

        assertEquals(request.getTable(), response.getTable());
        assertTrue(request.getMappings().equals(response.getMappings()));
    }
}


text:
@implementation NSDate (Extend)

const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

-(NSString*)sinceNow
{
    NSTimeInterval delta = [[NSDate date] timeIntervalSinceNow] - [self timeIntervalSinceNow];

    if(delta < 0)
        return FUTURE;
    if(delta < 1 * MINUTE)
        return delta == 1 ? SECOND_AGO :  [NSString stringWithFormat:SECONDS_AGO, delta];
    if(delta < 2 * MINUTE)
        return MINUTE_AGO;
    if(delta < 45 * MINUTE)
        return [NSString stringWithFormat:MINUTES_AGO, delta / MINUTE];
    if(delta < 90 * MINUTE)
        return HOUR_AGO;
    if(delta < 24 * HOUR)
        return [NSString stringWithFormat:HOURS_AGO, delta / HOUR];
    if(delta < 48 * HOUR)
        return DAY_AGO;
    if(delta < 30 * DAY)
        return [NSString stringWithFormat:DAYS_AGO, delta / DAY];
    if(delta < 12 * MONTH)
    {
        float months = delta / DAY / 30;
        return months <= 1 ? MONTH_AGO : [NSString stringWithFormat:MONTHS_AGO, months];
    }
    else
    {
        float years = delta / DAY / 365;
        return years <= 1 ? YEAR_AGO : [NSString stringWithFormat:YEARS_AGO];
    }
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Globalization.Fonts;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Text;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;

namespace SDKTemplate
{
    class LocalFontInfo
    {
        private FontFamily fontFamily;
        private FontWeight fontWeight;
        private FontStyle fontStyle;
        private FontStretch fontStretch;

        public void Set(TextBlock textBlock)
        {
            this.fontFamily = textBlock.FontFamily;
            this.fontWeight = textBlock.FontWeight;
            this.fontStyle = textBlock.FontStyle;
            this.fontStretch = textBlock.FontStretch;
        }

        public void Reset(TextBlock textBlock)
        {
            textBlock.FontFamily = this.fontFamily;
            textBlock.FontWeight = this.fontWeight;
            textBlock.FontStyle = this.fontStyle;
            textBlock.FontStretch = this.fontStretch;
        }
    }
}


text:
Meteor.startup(function() {
    Projects.remove({demo:true, userId:null});
    Meteor.call('newProject', 'Demo Project', 'This is a demo project.', true);
});

/**
 * Define the ACLs for each model.
 */
Projects.allow({
    update: function(userId, doc, fields, modifier) {
        return doc.userId === userId;
    },
    remove: function(userId, doc) {
        return doc.userId === userId;
    },
    fetch: ['userId']
});

/**
 * Publish the collections of the models, to the connected client.
 */
Meteor.publish('Projects', function() {
    return Projects.find({
        $or: [{
            userId: this.userId
        }, {
            demo: true
        }]
    })
});

Meteor.publish('Events', function() {
    return Events.find({
        userId: this.userId
    }, {});
});

/**
 * Register the 'public' methods available to the client
 */
Meteor.methods({
    newProject: function(name, description, demo) {
        return newProject(name, description, demo);
    },
    updateProject: function(projectId, concern, alpha, newStatePointer) {
        return updateProject(projectId, concern, alpha, newStatePointer);
    },
    log: function(projectId, who, what) {
        return log(projectId, who, what);
    },
    getLog: function(projectId) {
        return getLog(projectId);
    }
});


text:
/* View license at project root. */

package com.gen.cube;
import java.awt.Color;
import java.awt.Graphics;

/* Part of the larger cube */
public class SubCube implements Comparable{

    	private Face[] face;				// 6 faces of the subcube
    	private VirtualVect vect;			// the virtual space the subcube is associated with
    	private Point[] point;				// 8 points of the subcube
    	private Point center;				// center of subcube
    	private int rotateSide;				// indeicates if subcube is rotating

	public static final double third = 1.0/3.0;

	/* Set points into a standard cube position */
    	public SubCube(Color[] colors,VirtualVect vv,double len1,double len2,double len3){

        	rotateSide = -1;
        	vect = vv;
        	point = new Point[8];

        	point[0] = new Point(vect,len1      ,len2      ,len3);
        	point[1] = new Point(vect,len1+third,len2      ,len3);
        	point[2] = new Point(vect,len1+third,len2+third,len3);
        	point[3] = new Point(vect,len1      ,len2+third,len3);

        	point[4] = new Point(vect,len1      ,len2      ,len3+third);
        	point[5] = new Point(vect,len1+third,len2      ,len3+third);
        	point[6] = new Point(vect,len1+third,len2+third,len3+third);
        	point[7] = new Point(vect,len1      ,len2+third,len3+third);

        	center = point[0].midPoint(point[6]);

        	face = new Face[6];

        	face[Cube.bottom] = new Face(colors[0],point[0],point[1],point[2],point[3]); 	// bottom
        	face[Cube.top]    = new Face(colors[1],point[4],point[5],point[6],point[7]); 	// top

        	face[Cube.back]   = new Face(colors[2],point[0],point[1],point[5],point[4]); 	// front
        	face[Cube.front]  = new Face(colors[3],point[2],point[3],point[7],point[6]); 	// back

        	face[Cube.left]   = new Face(colors[4],point[1],point[2],point[6],point[5]); 	// right
        	face[Cube.right]  = new Face(colors[5],point[3],point[0],point[4],point[7]); 	// left
    	}

	/* Set is rotating */
    	public void setRot(int rot){
		rotateSide = rot;
	}

	/* Get rotating */
	public int getRot(){
		return rotateSide;
	}

	/* Sorted by how far forward subcubes are, rotation taken into account */
    	public int compareTo(Object oth){

        	SubCube other = (SubCube) oth;

        	if(rotateSide>-1 && other.getRot()==-1){
            		if(displaysBlack())
            			return -1;
            		return 1;
        	}

        	if(rotateSide==-1 && other.getRot()>-1){

            		if(other.displaysBlack())
            			return 1;
            		return -1;
        	}

        	if(center.compareTo(other.getCent()) > 0)
        		return 1;

		return -1;
    	}

	/* Checks if it shouldn't appear and should be black */
    	private boolean displaysBlack(){

        	if(rotateSide==Cube.top    && face[Cube.bottom].compareTo(face[Cube.top])>0 ) return true; 	// bottom > top
        	if(rotateSide==Cube.bottom && face[Cube.bottom].compareTo(face[Cube.top])<0 ) return true;

        	if(rotateSide==Cube.front && face[Cube.front].compareTo(face[Cube.back])<0 ) return true; 	// front > back
        	if(rotateSide==Cube.back  && face[Cube.front].compareTo(face[Cube.back])>0 ) return true;

        	if(rotateSide==Cube.right && face[Cube.right].compareTo(face[Cube.left])<0 ) return true; 	// right > left
        	if(rotateSide==Cube.left  && face[Cube.right].compareTo(face[Cube.left])>0 ) return true;

        	return false;
    	}

	/* get Center */
    	public Point getCent(){
     		return center;
    	}

	/* Get point */
   	public Point getPoint(int i){
       		return point[i];
    	}

	/* Get face */
    	public Face getFace(int i){
        	return face[i];
    	}

	/* Paint subcube */
    	public void paint(Graphics g){

        	if(face[Cube.bottom].compareTo(face[Cube.top])>0) face[Cube.bottom].paint(g); 	// bottom > top
        	else                                              face[Cube.top].paint(g);
        	if(face[Cube.front].compareTo(face[Cube.back])>0) face[Cube.front].paint(g); 	// front > back
        	else                                              face[Cube.back].paint(g);
        	if(face[Cube.right].compareTo(face[Cube.left])>0) face[Cube.right].paint(g); 	// right > left
        	else                                              face[Cube.left].paint(g);
    	}
}