text:
package com.google.api.codegen;

import com.google.api.tools.framework.model.Field;
import com.google.api.tools.framework.model.Interface;
import com.google.api.tools.framework.model.MessageType;
import com.google.api.tools.framework.model.Method;
import com.google.api.tools.framework.model.Model;
import com.google.api.tools.framework.model.ProtoFile;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type;
import java.util.HashSet;
import java.util.Set;

/**
 * A file-based view of model, consisting of a strategy for getting the protocol buffer files from
 * which the model was constructed.
 */
public class ProtoFileView implements InputElementView<ProtoFile> {

  /**
   * Gets the ProtoFile objects in which the fields of the reachable methods in the model are
   * defined.
   */
  @Override
  public Iterable<ProtoFile> getElementIterable(Model model) {
    Set<ProtoFile> files = new HashSet<>();
    for (Interface apiInterface : new InterfaceView().getElementIterable(model)) {
      for (Method method : apiInterface.getMethods()) {
        if (!method.isReachable()) {
          continue;
        }
        for (Field field : method.getInputType().getMessageType().getFields()) {
          files.addAll(protoFiles(field));
        }
        for (Field field : method.getOutputType().getMessageType().getFields()) {
          files.addAll(protoFiles(field));
        }
      }
    }
    return files;
  }

  private Set<ProtoFile> protoFiles(Field field) {
    Set<ProtoFile> fields = new HashSet<ProtoFile>();
    if (field.getType().getKind() != Type.TYPE_MESSAGE) {
      return fields;
    }
    MessageType messageType = field.getType().getMessageType();
    fields.add(messageType.getFile());
    for (Field f : messageType.getNonCyclicFields()) {
      fields.addAll(protoFiles(f));
    }
    return fields;
  }
}


text:
"""Utility modules for the VTK-Python wrappers."""

__all__ = ['algorithms', 'dataset_adapter']

redpajama_set_name: RedPajamaGithub


text:
class TButtonSet;

class DVAPI TButton : public TWidget, public TCommandSource
{
protected:
	bool m_pressed, m_active;
	int m_border;

	vector<TButtonSet *> *m_buttonSets;
	friend class TButtonSet;

public:
	TButton(TWidget *parent, string name = "button");
	~TButton();

	void repaint();
	void enter(const TPoint &p);
	void leave(const TPoint &p);
	void leftButtonDown(const TMouseEvent &);
	void leftButtonUp(const TMouseEvent &);

	virtual void setTitle(string title) { m_name = title; }
};

class DVAPI TIconButton : public TButton
{
	TRaster32P m_rasterUp, m_rasterDown;

public:
	TIconButton(TWidget *parent, TRaster32P raster, string name = "button");
	TIconButton(TWidget *parent, TRaster32P rasterUp, TRaster32P rasterDown, string name = "button");
	void repaint();
	void leftButtonDown(const TMouseEvent &);
	void leftButtonUp(const TMouseEvent &);
};

class DVAPI TIconToggle : public TButton
{
	TRaster32P m_up, m_down;

public:
	TIconToggle(TWidget *parent,
				TRaster32P up, TRaster32P down,
				string name = "button");
	void repaint();
	void setStatus(bool v);
	bool getStatus();
	void leftButtonDown(const TMouseEvent &e);
	void leftButtonUp(const TMouseEvent &e);
};

class TButtonSetAction
{
public:
	TButtonSetAction(){};
	virtual ~TButtonSetAction(){};
	virtual void sendCommand(string value) = 0;
};

template <class T>
class TButtonSetActionT : public TButtonSetAction
{
public:
	typedef void (T::*CommandMethod)(string);

	T *m_target;
	CommandMethod m_method;

	TButtonSetActionT<T>(T *target, CommandMethod method) : m_target(target), m_method(method){};
	void sendCommand(string value) { (m_target->*m_method)(value); };
};

class DVAPI TButtonSet
{
	std::map<TButton *, string> *m_buttons;
	string m_currentValue;
	TButtonSetAction *m_action;

public:
	TButtonSet();
	~TButtonSet();

private:
	// not implemented
	TButtonSet(const TButtonSet &);
	TButtonSet &operator=(const TButtonSet &);

public:
	void addButton(TButton *button, string value);
	void removeButton(TButton *button);
	void setValue(string value);
	void setValue(TButton *value);
	// Note: setValue fires the buttons actions as well as the buttonset action
	string getValue() { return m_currentValue; };

	void setAction(TButtonSetAction *action);

	void enable(bool on);
};

#endif


text:
from datetime import date

import calendars.calendars as cc

def main():
    my_date = date(2016, 4, 8)
    cal = cc.RegularDate(my_date)
    fy = cc.FiscalDate(my_date)
    r544 = cc.RetailDate(my_date)
    # TODO: ISO and lunar calendar

    fiscal_attr = [fy.year,
                   fy.year_string,
                   fy.year_dates_string,
                   fy.year_start_date,
                   fy.year_end_date,
                   fy.year_num_of_days,
                   fy.is_current_year,
                   fy.is_previous_year,
                   fy.quarter,
                   fy.quarter_string,
                   fy.quarter_dates_string,
                   fy.quarter_start_date,
                   fy.quarter_end_date,
                   fy.quarter_num_of_days,
                   ]

    r544_attr = [r544.year,
                 r544.year_string,
                 r544.year_dates_string,
                 r544.year_start_date,
                 r544.year_end_date,
                 r544.year_num_of_days,
                 r544.is_current_year,
                 r544.is_previous_year,
                 r544.quarter,
                 r544.quarter_string,
                 r544.quarter_dates_string,
                 r544.quarter_start_date,
                 r544.quarter_end_date,
                 r544.quarter_num_of_days,
                 ]

    regular_attr = [cal.year,
                   cal.year_string,
                   cal.year_dates_string,
                   cal.year_start_date,
                   cal.year_end_date,
                   cal.year_num_of_days,
                   cal.is_current_year,
                   cal.is_previous_year,
                   cal.quarter,
                   cal.quarter_string,
                   cal.quarter_dates_string,
                   cal.quarter_start_date,
                   cal.quarter_end_date,
                   cal.quarter_num_of_days,
                    ]

    print fiscal_attr
    print r544_attr
    print regular_attr

if __name__ == "__main__":
    main()


text:
<!DOCTYPE html>

	<?php

		require ("head.php");
		include('php/userProfile.class.php');
		include('php/userHome.class.php');
		include('php/users.class.php');

		$user = new users($_SESSION['ID']);  //initialize current user info (php/user.class.php)
		$home = new userHome(htmlspecialchars($_SESSION['ID'])); //generate user index.php page (userHome.class.php)
		$home->initializeHome(); //initialize user homepage

	?>

	<?php
		require ("menu_co.php");
	?>

		<?php include('disp_social.php'); //show all social networks of Kamevo
		?>
		  <?php

		  	$home->printPosts('home'); //display posts on home (userProfile.class.php)

			require ("disp_pub.php"); //load ad banner
			require("php/chat.php");
		  ?>

		<?php
			require ("disp_group_creation.php"); //load the module to create a group
		?>


text:
package ca.uhn.fhir.cql.common.provider;

import ca.uhn.fhir.rest.api.server.RequestDetails;
import org.opencds.cqf.cql.engine.data.DataProvider;
import org.opencds.cqf.cql.engine.terminology.TerminologyProvider;

// TODO: This interface is a partial duplicate of the provider factory interface
// in the cql service layer. We need another round of refactoring to consolidate that.
public interface EvaluationProviderFactory {
	DataProvider createDataProvider(String model, String version, RequestDetails theRequestDetails);

	DataProvider createDataProvider(String model, String version, String url, String user, String pass, RequestDetails theRequestDetails);

	DataProvider createDataProvider(String model, String version, TerminologyProvider terminologyProvider, RequestDetails theRequestDetails);

	TerminologyProvider createTerminologyProvider(String model, String version, String url, String user,
																 String pass);
}


text:
===============================
RasterRGB
===============================

.. image:: https://travis-ci.org/biracruz/rasterrgb.svg?branch=master
    :target: https://travis-ci.org/biracruz/rasterrgb

.. image:: https://readthedocs.org/projects/rasterrgb/badge/?version=latest
        :target: https://rasterrgb.readthedocs.io/en/latest/?badge=latest
        :alt: Documentation Status

Functions for processing tiff images.

* Free software: MIT license
* Documentation: https://rasterrgb.readthedocs.io.

Features
--------

* TODO

---------

This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.


text:
package java.sql;

import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * A Java representation of the SQL TIMESTAMP type. It provides the capability
 * to represent the SQL TIMESTAMP nanosecond value, in addition to the regular
 * date/time value which has millisecond resolution.
 *

 * The Timestamp class consists of a regular Date/Time value, where only the
 * integral seconds value is stored, plus a nanoseconds value where the
 * fractional seconds are stored.
 *

 * The addition of the nanosecond value field to the Timestamp object makes it
 * significantly different from the java.util.Date object which it extends.
 * Users should be cautious in their use of Timestamp objects and should not
 * assume that they are interchangeable with java.util.Date objects when used
 * outside the confines of the java.sql package.
 *
 */
public class Timestamp extends Date {

    private static final long serialVersionUID = 2745179027874758501L;

    // The nanoseconds time value of the Timestamp
    private int nanos;

    /**
     * Returns a Timestamp object corresponding to the time represented by a
     * supplied time value.
     *
     * @param theTime
     *            a time value in the format of milliseconds since the Epoch
     *            (January 1 1970 00:00:00.000 GMT)
     */
    public Timestamp(long theTime) {
        super(theTime);
        /*
         * Now set the time for this Timestamp object - which deals with the
         * nanosecond value as well as the base time
         */
        this.setTime(theTime);
    }

    /**
     * Returns true if this timestamp object is later than the supplied
     * timestamp, otherwise returns false.
     *
     * @param theTimestamp
     *            the timestamp to compare with this timestamp object
     * @return true if this timestamp object is later than the supplied
     *         timestamp, false otherwise
     */
    public boolean after(Timestamp theTimestamp) {
        long thisTime = this.getTime();
        long compareTime = theTimestamp.getTime();

        // If the time value is later, the timestamp is later
        if (thisTime > compareTime) {
            return true;
        }
        // If the time value is earlier, the timestamp is not later
        else if (thisTime < compareTime) {
            return false;
        }
        /*
         * Otherwise the time values are equal in which case the nanoseconds
         * value determines whether this timestamp is later...
         */
        else if (this.getNanos() > theTimestamp.getNanos()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Returns true if this timestamp object is earlier than the supplied
     * timestamp, otherwise returns false.
     *
     * @param theTimestamp
     *            the timestamp to compare with this timestamp object
     * @return true if this timestamp object is earlier than the supplied
     *         timestamp, false otherwise
     */
    public boolean before(Timestamp theTimestamp) {
        long thisTime = this.getTime();
        long compareTime = theTimestamp.getTime();

        // If the time value is later, the timestamp is later
        if (thisTime < compareTime) {
            return true;
        }
        // If the time value is earlier, the timestamp is not later
        else if (thisTime > compareTime) {
            return false;
        }
        /*
         * Otherwise the time values are equal in which case the nanoseconds
         * value determines whether this timestamp is later...
         */
        else if (this.getNanos() < theTimestamp.getNanos()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Compares this Timestamp object with a supplied Timestamp object
     *
     * @param theObject
     *            the timestamp to compare with this timestamp object, passed in
     *            as an Object
     * @return 0 if the two Timestamp objects are equal in time, a value <0 if
     *         this Timestamp object is before the supplied Timestamp and a
     *         value >0 if this Timestamp object is after the supplied Timestamp
     * @throws ClassCastException
     *             if the supplied object is not a Timestamp object
     */
    public int compareTo(Date theObject) throws ClassCastException {
        return this.compareTo((Timestamp) theObject);
    }

    /**
     * Compares this Timestamp object with a supplied Timestamp object
     *
     * @param theTimestamp
     *            the timestamp to compare with this timestamp object, passed in
     *            as a Timestamp
     * @return 0 if the two Timestamp objects are equal in time, a value <0 if
     *         this Timestamp object is before the supplied Timestamp and a
     *         value >0 if this Timestamp object is after the supplied Timestamp
     */
    public int compareTo(Timestamp theTimestamp) {
        int result = super.compareTo(theTimestamp);
        if (result == 0) {
            int thisNano = this.getNanos();
            int thatNano = theTimestamp.getNanos();
            if (thisNano > thatNano) {
                return 1;
            } else if (thisNano == thatNano) {
                return 0;
            } else {
                return -1;
            }
        }
        return result;
    }

    /**
     * Tests to see if this timestamp is equal to a supplied object.
     *
     * @param theObject
     * @return true if this Timestamp object is equal to the supplied Timestamp
     *         object false if the object is not a Timestamp object or if the
     *         object is a Timestamp but represents a different instant in time
     */
    public boolean equals(Object theObject) {
        if (theObject instanceof Timestamp) {
            return equals((Timestamp) theObject);
        }
        return false;
    }

    /**
     * Tests to see if this timestamp is equal to a supplied timestamp.
     *
     * @param theTimestamp
     *            the timestamp to compare with this timestamp object, passed in
     *            as an Object
     * @return true if this Timestamp object is equal to the supplied Timestamp
     *         object
     */
    public boolean equals(Timestamp theTimestamp) {
        if (theTimestamp == null) {
            return false;
        }
        return (this.getTime() == theTimestamp.getTime())
                && (this.getNanos() == theTimestamp.getNanos());
    }

    /**
     * Gets this Timestamp's nanosecond value
     *
     * @return The timestamp's nanosecond value, an integer between 0 and
     *         999,999,999
     */
    public int getNanos() {
        return nanos;
    }

    /**
     * Returns the time represented by this Timestamp object, as a long value
     * containing the number of milliseconds since the Epoch (January 1 1970,
     * 00:00:00.000 GMT)
     */
    public long getTime() {
        long theTime = super.getTime();
        theTime = theTime + (nanos / 1000000);
        return theTime;
    }

    /**
     * Sets the nanosecond value for this timestamp
     */
    public void setNanos(int n) throws IllegalArgumentException {
        if ((n < 0) || (n > 999999999)) {
            // sql.0=Value out of range
            throw new IllegalArgumentException("sql.0"); //$NON-NLS-1$
        }
        nanos = n;
    }

    /**
     * Sets the time represented by this Timestamp object to the supplied time,
     * defined as the number of milliseconds since the Epoch (January 1 1970,
     * 00:00:00.000 GMT)
     */
    public void setTime(long theTime) {
        /*
         * Deal with the nanoseconds value. The supplied time is in milliseconds -
         * so we must extract the milliseconds value and multiply by 1000000 to
         * get nanoseconds. Things are more complex if theTime value is
         * negative, since then the time value is the time before the Epoch but
         * the nanoseconds value of the Timestamp must be positive - so we must
         * take the "raw" milliseconds value and subtract it from 1000 to get to
         * the true nanoseconds value Simultaneously, recalculate the time value
         * to the exact nearest second and reset the Date time value
         */
        int milliseconds = (int) (theTime % 1000);
        theTime = theTime - milliseconds;
        if (milliseconds < 0) {
            theTime = theTime - 1000;
            milliseconds = 1000 + milliseconds;
        }
        super.setTime(theTime);
        setNanos(milliseconds * 1000000);
    }

    /**
     * Returns the timestamp formatted as a String in the JDBC Timestamp Escape
     * format, which is of the form "yyyy-mm-dd hh:mm:ss.nnnnnnnnn"
     *
     * @return A string representing the instant defined by the Timestamp, in
     *         JDBC Timestamp escape format
     */
    public String toString() {
        return "dummy string";
    }

    /*
     * Private method to format the time
     */
    private String format(int date, int digits) {
        StringBuffer dateStringBuffer = new StringBuffer(String.valueOf(date));
        while (dateStringBuffer.length() < digits) {
            dateStringBuffer = dateStringBuffer.insert(0, '0');
        }
        return dateStringBuffer.toString();
    }

    /*
     * Private method to strip trailing '0' characters from a string. @param
     * inputString the starting string @return a string with the trailing zeros
     * stripped - will leave a single 0 at the beginning of the string
     */
    private String stripTrailingZeros(String inputString) {
        String finalString;

        int i;
        for (i = inputString.length(); i > 0; i--) {
            if (inputString.charAt(i - 1) != '0') {
                break;
            }
            /*
             * If the string has a 0 as its first character, return a string
             * with a single '0'
             */
            if (i == 1) {
                return "0"; //$NON-NLS-1$
            }
        }

        finalString = inputString.substring(0, i);
        return finalString;
    }

    /**
     * Creates a Timestamp object with a time value equal to the time specified
     * by a supplied String holding the time in JDBC timestamp escape format,
     * which is of the form "yyyy-mm-dd hh:mm:ss.nnnnnnnnn"
     *
     * @param s
     *            the String containing a time in JDBC timestamp escape format
     * @return A timestamp object with time value as defined by the supplied
     *         String
     */
    public static Timestamp valueOf(String s) throws IllegalArgumentException {
        if (s == null) {
            // sql.3=Argument cannot be null
            throw new IllegalArgumentException("sql.3"); //$NON-NLS-1$
        }

        // omit trailing whitespaces
        s = s.trim();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$
        ParsePosition pp = new ParsePosition(0);

        /*
         * First parse out the yyyy-MM-dd HH:mm:ss component of the String into
         * a Date object using the SimpleDateFormat. This should stop after the
         * seconds value, according to the definition of SimpleDateFormat.parse,
         * with the ParsePosition indicating the index of the "." which should
         * precede the nanoseconds value
         */
        Date theDate;
        try {
            theDate = df.parse(s, pp);
        } catch (Exception e) {
            throw new IllegalArgumentException("sql.2"); //$NON-NLS-1$
        }

        if (theDate == null) {
            throw new IllegalArgumentException("sql.2"); //$NON-NLS-1$
        }

        /*
         * If we get here, the Date part of the string was OK - now for the
         * nanoseconds value. Strictly, this requires the remaining part of the
         * String to look like ".nnnnnnnnn". However, we accept anything with a
         * '.' followed by 1 to 9 digits - we also accept nothing (no fractions
         * of a second). Anything else is interpreted as incorrect format which
         * will generate an IllegalArgumentException
         */
        int position = pp.getIndex();
        int remaining = s.length() - position;
        int theNanos;

        if (remaining == 0) {
            // First, allow for the case where no fraction of a second is given:
            theNanos = 0;
        } else {
            /*
             * Case where fraction of a second is specified: Require 1 character
             * plus the "." in the remaining part of the string...
             */
            if ((s.length() - position) < ".n".length()) { //$NON-NLS-1$
                throw new IllegalArgumentException("sql.2"); //$NON-NLS-1$
            }

            /*
             * If we're strict, we should not allow any EXTRA characters after
             * the 9 digits
             */
            if ((s.length() - position) > ".nnnnnnnnn".length()) { //$NON-NLS-1$
                throw new IllegalArgumentException("sql.2"); //$NON-NLS-1$
            }

            // Require the next character to be a "."
            if (s.charAt(position) != '.') {
                // sql.4=Bad input string format: expected '.' not {0}
                throw new NumberFormatException("sql.4"); //$NON-NLS-1$
            }
            // Get the length of the number string - need to account for the '.'
            int nanoLength = s.length() - position - 1;

            // Get the 9 characters following the "." as an integer
            String theNanoString = s.substring(position + 1, position + 1
                    + nanoLength);
            /*
             * We must adjust for the cases where the nanos String was not 9
             * characters long by padding out with zeros
             */
            theNanoString = theNanoString + "000000000"; //$NON-NLS-1$
            theNanoString = theNanoString.substring(0, 9);

            try {
                theNanos = Integer.parseInt(theNanoString);
            } catch (Exception e) {
                // If we get here, the string was not a number
                throw new IllegalArgumentException("sql.2"); //$NON-NLS-1$
            }
        }

        if (theNanos < 0 || theNanos > 999999999) {
            throw new IllegalArgumentException("sql.2"); //$NON-NLS-1$
        }

        Timestamp theTimestamp = new Timestamp(theDate.getTime());
        theTimestamp.setNanos(theNanos);

        return theTimestamp;
    }
}


text:
layout: post
title: "A Post with Images"
description: "Examples and code for displaying images in posts."
category: photos
tags: [sample post, images, test]
image:
  feature: picture-15.jpg
comments: true
share: true
---

Here are some examples of what a post with images might look like. If you want to display two or three images next to each other responsively use `figure` with the appropriate `class`. Images are responsive and are opened in a Magnific Popup lightbox if you link a larger image to the entry. Also if you link a larger image, the image thumbs uses CSS3 transitions to turn B&W and change back to color on mouse-hover. Each instance of `figure` is auto-numbered and displayed in the caption.

## Figures (for images or video)

### One Up

A day at Disneyland, Tokyo.

### Two Up

Apply the `half` class like so to display two images side by side that share the same caption.

{% highlight html %}

Caption describing these two images.

{% endhighlight %}

And you'll get something that looks like this:

Two images.

### Three Up

Apply the `third` class like so to display three images side by side that share the same caption.

{% highlight html %}

Caption describing these three images.

{% endhighlight %}

And you'll get something that looks like this:

Three images.


text:
                 {{commandData.name}}
                 {{commandData.name}}

                {{commandData.date_long | date:'short'}}


text:
require 'test_helper'

class TrackbackTest < ActiveSupport::TestCase
	test "create trackback" do
		Trackback.create(
				:trackback_code_id => 1,
				:ip_address => "10.0.0.2",
				:origin => "development.musichristian.com",
				:action => "NEW",
				:viewed => ""
			)

		puts Trackback.all( :action => "NEW" ).inspect
	end
end


text:
package momijikawa.lacquer.KanColleMessage

import spray.http.HttpResponse

case class Slot_item(jsonString: String) extends KanColleMessage

object Slot_itemConverter extends KanColleMessageConverter {
  import org.json4s._
  implicit val formats = DefaultFormats

  val uriRegex = """kcsapi\/api_get_member\/slot_item"""

  def response2Message(response: HttpResponse): Slot_item = {
    Slot_item(getJsonString(response))
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/exclude_folder_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/exclude_folder_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/activity_margin">

        <com.simplemobiletools.commons.views.MyTextView
            android:id="@+id/exclude_folder_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/exclude_folder_description"
            android:textSize="@dimen/bigger_text_size"/>

        <com.simplemobiletools.commons.views.MyTextView
            android:id="@+id/exclude_folder_parent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_margin"
            android:text="@string/exclude_folder_parent"
            android:textSize="@dimen/normal_text_size"/>

        <RadioGroup
            android:id="@+id/exclude_folder_radio_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </RadioGroup>
    </LinearLayout>
</ScrollView>


text:
using System.IO;
using System.Text.Encodings.Web;

namespace HtmlBuilders {
  public static partial class HtmlTagExtensions {
    /// <summary>
    ///   Gets the HTML stripped content of this <see cref="HtmlTag"/>
    /// </summary>
    /// <param name="htmlTag">This <see cref="HtmlTag"/></param>
    /// <returns>The HTML stripped contents.</returns>
    public static string Text(this HtmlTag htmlTag) {
      if (htmlTag == null)
        return string.Empty;
      using (var writer = new StringWriter()) {
        Write(htmlTag, writer, HtmlEncoder.Default);
        return writer.ToString();
      }
    }

    private static void Write(HtmlTag htmlTag, TextWriter writer, HtmlEncoder encoder) {
      foreach (var content in htmlTag.Contents) {
        if (content is HtmlText text) {
          text.WriteTo(writer, encoder);
        }
        else if (content is HtmlTag tag) {
          Write(tag, writer, encoder);
        }
      }
    }
  }
}


text:
package springies;

import java.util.ArrayList;
import masses.Mass;
import springs.Spring;

/**
 * This class defines a spring-mass assembly
 * and provides methods for adding masses and springs.
 *
 * @author Thanh-Ha Nguyen & Dennis Park
 *
 */
public class Assembly {
    private ArrayList<Mass> mMasses;
    private ArrayList<Spring> mSprings;

    /**
     * Structure contains list of masses and list of springs.
     *
     */
    public Assembly () {
        mMasses = new ArrayList<Mass>();
        mSprings = new ArrayList<Spring>();
    }

    /**
     * Adds specified mass object to assembly's member mass list.
     * @param mass
     */
    public void add (Mass mass) {
        mMasses.add(mass);
    }

    /**
     * Adds specified spring object to assembly's member spring list.
     *
     * @param spring
     */
    public void add (Spring spring) {
        mSprings.add(spring);
    }

    /**
     * Getter for this Assembly object's member mass list.
     *
     * @return mMasses
     */
    public ArrayList<Mass> getMassList () {
        return this.mMasses;
    }

    /**
     * Getter for this Assembly object's member spring list.
     *
     * @return mSprings
     */
    public ArrayList<Spring> getSpringList () {
        return this.mSprings;
    }

    /**
     * Getter for Assembly object created.
     *
     * @return this
     */
    public Assembly getAssembly () {
        return this;
    }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Paypal_Model_Mysql4_Setup */

$installer->startSetup();

$installer->run("

-- DROP TABLE IF EXISTS {$this->getTable('paypaluk_api_debug')};

CREATE TABLE {$this->getTable('paypaluk_api_debug')} (
  `debug_id` int(10) unsigned NOT NULL auto_increment,
  `debug_at` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `request_body` text,
  `response_body` text,
  PRIMARY KEY  (`debug_id`),
  KEY `debug_at` (`debug_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    ");

$installer->endSetup();


text:
require 'spec_helper'

describe Locomotive::Concerns::Page::EditableElements do

  before(:each) do
    @site = FactoryGirl.create(:site)
    @home = @site.pages.root.first

    @home.update_attributes raw_template: "{% editable_text 'body' %}Lorem ipsum{% endeditable_text %}"

    @sub_page_1 = FactoryGirl.create(:page, slug: 'sub_page_1', parent: @home, raw_template: "{% extends 'parent' %}")
    @sub_page_2 = FactoryGirl.create(:page, slug: 'sub_page_2', parent: @home, raw_template: "{% extends 'parent' %}")

    @sub_page_1_el = @sub_page_1.editable_elements.first

    @sub_page_1_1 = FactoryGirl.create(:page, slug: 'sub_page_1_1', parent: @sub_page_1, raw_template: "{% extends 'parent' %}")
  end

  describe 'modification of an element within the home page' do

    before(:each) do
      @home = Locomotive::Page.find(@home._id)
    end

    it 'keeps the same number of editable elements in all the children' do
      @home.update_attributes raw_template: "{% editable_file 'body' %}/nowhere.pdf{% endeditable_file %}"
      expect(@sub_page_1.reload.editable_elements.size).to eq(1)
      expect(@sub_page_1_1.reload.editable_elements.size).to eq(1)
    end

    it 'changes the type of the element in all the children' do
      @home.update_attributes raw_template: "{% editable_file 'body' %}/nowhere.pdf{% endeditable_file %}"
      @sub_page_1.reload
      expect(@sub_page_1.editable_elements.first._type).to eq('Locomotive::EditableFile')
      @sub_page_1_1.reload
      expect(@sub_page_1_1.editable_elements.first._type).to eq('Locomotive::EditableFile')
    end

    it 'changes the hint of the element in all the children' do
      @home.update_attributes raw_template: "{% editable_text 'body', hint: 'My very useful hint' %}Lorem ipsum{% endeditable_text %}"
      @sub_page_1.reload
      expect(@sub_page_1.editable_elements.first.hint).to eq('My very useful hint')
      @sub_page_1_1.reload
      expect(@sub_page_1_1.editable_elements.first.hint).to eq('My very useful hint')
    end

  end

  describe '#localized' do

    it 'does not remove the editable elements in other locales' do
      Mongoid::Fields::I18n.with_locale(:fr) do
        @home.update_attributes raw_template: "{% editable_text 'corps' %}Lorem ipsum{% endeditable_text %}"
      end
      @home.reload
      expect(@home.editable_elements.count).to eq(2)
    end

    it 'removes the editable elements which are not present in at least one locale' do
      Mongoid::Fields::I18n.with_locale(:fr) do
        @home.update_attributes raw_template: ''
      end
      @home.reload
      expect(@home.editable_elements.count).to eq(1)

      @home.update_attributes raw_template: ''
      @home.reload
      expect(@home.editable_elements.count).to eq(0)
    end

  end

end


text:
module Ramverk
  class Controller
    # Cookies manager.
    #
    # @see https://www.rubydoc.info/gems/rack/Rack/Response/Helpers:set_cookie
    # @see https://www.rubydoc.info/gems/rack/Rack/Response/Helpers:delete_cookie
    class Cookies
      # Initializes the cookie manager.
      #
      # @param request [Ramverk::Controller::Request]
      #   Request object.
      # @param response [Ramverk::Controller::Response]
      #   Response object.
      # @param options [Hash]
      #   Cookie default options.
      #
      # @return [void]
      #
      # @private
      def initialize(request, response, options = {})
        @request = request
        @response = response
        @cookies = @request.cookies.dup
        @options = {
          path: request.script_name.to_s.empty? ? "/" : request.script_name,
          domain: request.host == "localhost" ? nil : request.host,
          secure: request.ssl?,
          httponly: true
        }.merge(options)
      end

      # Gets a cookie from the jar.
      #
      # @param key [Symbol, String]
      #   Cookie key to fetch value from.
      #
      # @return [Mixed]
      def [](key)
        @cookies[key.to_s]
      end

      # Sets a new cookie.
      #
      # @param key [Symbol, String]
      #   Name of the new cookie.
      # @param value [String, Hash]
      #   Cookie value or options.
      #
      # @return [void]
      def []=(key, value)
        key = key.to_s
        value = { value: value } unless value.is_a?(Hash)
        value = @options.merge(value)
        @cookies[key] = value[:value]
        @response.set_cookie(key, value)
      end

      # Delete, or eat, a cookie from the jar.
      #
      # @param key [Symbol, String]
      #   Name of the cookie to be deleted.
      # @param opts [Hash]
      #   Cookie options.
      #
      # @return [void]
      def delete(key, opts = {})
        key = key.to_s
        @cookies.delete(key)
        @response.delete_cookie(key, @options.merge(opts))
      end

      # Delete all existing cookies.
      #
      # @return [void]
      def clear
        @cookies.each_key { |key| delete key }
      end

      # Inspect the existing cookies.
      #
      # @return [String]
      def inspect
        @cookies.inspect
      end
    end
  end
end


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

<title>org.springframework.web.context.request.async (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.springframework.web.context.request.async

Interfaces

AsyncWebRequest

CallableProcessingInterceptor

DeferredResult.DeferredResultHandler

DeferredResultProcessingInterceptor

Classes

CallableProcessingInterceptorAdapter

DeferredResult

DeferredResultProcessingInterceptorAdapter

StandardServletAsyncWebRequest

TimeoutCallableProcessingInterceptor

TimeoutDeferredResultProcessingInterceptor

WebAsyncManager

WebAsyncTask

WebAsyncUtils

Exceptions

AsyncRequestTimeoutException


text:
<md-fab-toolbar md-open="false" count="2" md-direction="right" class="entrance-toobar">
  <md-fab-trigger class="align-with-text" id="menu-button">
    <md-button aria-label="menu" class="md-fab">
      <md-icon md-svg-src="images/menu.svg"></md-icon>
    </md-button>
  </md-fab-trigger>

  <md-toolbar>
    <md-fab-actions class="md-toolbar-tools">
      <md-button ng-href="#/">Home</md-button>
      <md-button ng-href="#orange">Orange</md-button>
      <md-button ng-href="#pineapple">Pineapple</md-button>
      <md-button ng-href="#greentea">Green Tea</md-button>
      <md-button ng-href="#lemon">Lemon</md-button>
      <md-button ng-href="#about">About</md-button>
    </md-fab-actions>
  </md-toolbar>
</md-fab-toolbar>

Natrual

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Slowganic

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Hand Made

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
package com.wo2b.sdk.assistant.exception.upload;

public class AppInfo
{

}


text:
package scray.core.service

import scray.core.service.properties.ScrayServicePropertiesRegistration

object ScrayTTestServer extends ScrayStatefulTServer {
  // initialize properties
  override def configureProperties: Unit = ScrayServicePropertiesRegistration.configure()

  def initializeResources: Unit = {}
  def destroyResources: Unit = {}
}


text:
var Clapp = require('../modules/clapp-discord');

module.exports = new Clapp.Command({
    name: 'enque',
    desc: 'adds strings to a queue',
    fn: (argv, context) => {
        context.queue.push(argv.args.songTitle);
        return argv.args.songTitle;
        },
    args: [
        {
            name: 'songTitle',
            desc: 'Search string for a song (e.g. the title)',
            type: 'string',
            required: true,
            default: 'null'
        }
    ],
    flags: [
        {
            name: 'placeHolder',
            desc: 'noFlagYet',
            type: 'boolean',
            default: false
        }
    ]
});


text:
require 'spec_helper'
require 'whois/record/parser/whois.nic.mg.rb'

describe Whois::Record::Parser::WhoisNicMg, "status_registered.expected" do

  subject do
    file = fixture("responses", "whois.nic.mg/status_registered.txt")
    part = Whois::Record::Part.new(body: File.read(file))
    described_class.new(part)
  end

  describe "#domain" do
    it do
      expect(subject.domain).to eq("google.mg")
    end
  end
  describe "#domain_id" do
    it do
      expect(subject.domain_id).to eq("1915-nicmg")
    end
  end
  describe "#status" do
    it do
      expect(subject.status).to eq(:registered)
    end
  end
  describe "#available?" do
    it do
      expect(subject.available?).to eq(false)
    end
  end
  describe "#registered?" do
    it do
      expect(subject.registered?).to eq(true)
    end
  end
  describe "#created_on" do
    it do
      expect(subject.created_on).to be_a(Time)
      expect(subject.created_on).to eq(Time.parse("2009-06-18 08:38:20 UTC"))
    end
  end
  describe "#updated_on" do
    it do
      expect(subject.updated_on).to be_a(Time)
      expect(subject.updated_on).to eq(Time.parse("2013-10-29 15:13:49 UTC"))
    end
  end
  describe "#expires_on" do
    it do
      expect(subject.expires_on).to be_a(Time)
      expect(subject.expires_on).to eq(Time.parse("2014-11-26 21:00:00 UTC"))
    end
  end
  describe "#registrar" do
    it do
      expect(subject.registrar).to be_a(Whois::Record::Registrar)
      expect(subject.registrar.id).to eq(nil)
      expect(subject.registrar.name).to eq("MarkMonitor")
      expect(subject.registrar.organization).to eq(nil)
      expect(subject.registrar.url).to eq("http://www.markmonitor.com")
    end
  end
  describe "#nameservers" do
    it do
      expect(subject.nameservers).to be_a(Array)
      expect(subject.nameservers).to have(4).items
      expect(subject.nameservers[0]).to be_a(Whois::Record::Nameserver)
      expect(subject.nameservers[0].name).to eq("ns1.google.com")
      expect(subject.nameservers[1]).to be_a(Whois::Record::Nameserver)
      expect(subject.nameservers[1].name).to eq("ns2.google.com")
      expect(subject.nameservers[2]).to be_a(Whois::Record::Nameserver)
      expect(subject.nameservers[2].name).to eq("ns3.google.com")
      expect(subject.nameservers[3]).to be_a(Whois::Record::Nameserver)
      expect(subject.nameservers[3].name).to eq("ns4.google.com")
    end
  end
end


text:
package com.datagre.apps.omicron.biz.service;

import com.datagre.apps.omicron.biz.entity.*;
import com.datagre.apps.omicron.biz.repository.ReleaseRepository;
import com.datagre.apps.omicron.biz.utils.ReleaseKeyGenerator;
import com.datagre.apps.omicron.common.constants.GsonType;
import com.datagre.apps.omicron.common.constants.ReleaseOperation;
import com.datagre.apps.omicron.common.constants.ReleaseOperationContext;
import com.datagre.apps.omicron.common.dto.ItemChangeSets;
import com.datagre.apps.omicron.common.exception.BadRequestException;
import com.datagre.apps.omicron.common.exception.NotFoundException;
import com.datagre.apps.omicron.common.utils.GrayReleaseRuleItemTransformer;
import com.datagre.apps.omicron.core.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Created by zengxiaobo on 2017/3/27.
 */
@Service
public class ReleaseService {

  private static final FastDateFormat TIMESTAMP_FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss");
  private Gson gson = new Gson();

  @Autowired
  private ReleaseRepository releaseRepository;
  @Autowired
  private ItemService itemService;
  @Autowired
  private AuditService auditService;
  @Autowired
  private NamespaceLockService namespaceLockService;
  @Autowired
  private NamespaceService namespaceService;
  @Autowired
  private NamespaceBranchService namespaceBranchService;
  @Autowired
  private ReleaseHistoryService releaseHistoryService;
  @Autowired
  private ItemSetService itemSetService;

  public Release findOne(long releaseId) {
    return releaseRepository.findOne(releaseId);
  }

  public Release findActiveOne(long releaseId) {
    return releaseRepository.findByIdAndIsAbandonedFalse(releaseId);
  }

  public List<Release> findByReleaseIds(Set<Long> releaseIds) {
    Iterable<Release> releases = releaseRepository.findAll(releaseIds);
    if (releases == null) {
      return Collections.emptyList();
    }
    return Lists.newArrayList(releases);
  }

  public List<Release> findByReleaseKeys(Set<String> releaseKeys) {
    return releaseRepository.findByReleaseKeyIn(releaseKeys);
  }

  public Release findLatestActiveRelease(Namespace namespace) {
    return findLatestActiveRelease(namespace.getAppId(),
                                   namespace.getClusterName(), namespace.getNamespaceName());

  }

  public Release findLatestActiveRelease(String appId, String clusterName, String namespaceName) {
    return releaseRepository.findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId,
                                                                                clusterName,
                                                                                namespaceName);
  }

  public List<Release> findAllReleases(String appId, String clusterName, String namespaceName, Pageable page) {
    List<Release> releases = releaseRepository.findByAppIdAndClusterNameAndNamespaceNameOrderByIdDesc(appId,
                                                                                clusterName,
                                                                                namespaceName,
                                                                                page);
    if (releases == null) {
      return Collections.emptyList();
    }
    return releases;
  }

  public List<Release> findActiveReleases(String appId, String clusterName, String namespaceName, Pageable page) {
    List<Release>
        releases =
        releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId, clusterName,
                                                                                namespaceName,
                                                                                page);
    if (releases == null) {
      return Collections.emptyList();
    }
    return releases;
  }

  @Transactional
  public Release mergeBranchChangeSetsAndRelease(Namespace namespace, String branchName, String releaseName,
                                                 String releaseComment, boolean isEmergencyPublish,
                                                 ItemChangeSets changeSets) {

    checkLock(namespace, isEmergencyPublish, changeSets.getDataChangeLastModifiedBy());

    itemSetService.updateSet(namespace, changeSets);

    Release branchRelease = findLatestActiveRelease(namespace.getAppId(), branchName, namespace
        .getNamespaceName());
    long branchReleaseId = branchRelease == null ? 0 : branchRelease.getId();

    Map<String, String> operateNamespaceItems = getNamespaceItems(namespace);

    Map<String, Object> operationContext = Maps.newHashMap();
    operationContext.put(ReleaseOperationContext.SOURCE_BRANCH, branchName);
    operationContext.put(ReleaseOperationContext.BASE_RELEASE_ID, branchReleaseId);
    operationContext.put(ReleaseOperationContext.IS_EMERGENCY_PUBLISH, isEmergencyPublish);

    return masterRelease(namespace, releaseName, releaseComment, operateNamespaceItems,
                         changeSets.getDataChangeLastModifiedBy(),
                         ReleaseOperation.GRAY_RELEASE_MERGE_TO_MASTER, operationContext);

  }

  @Transactional
  public Release publish(Namespace namespace, String releaseName, String releaseComment,
                         String operator, boolean isEmergencyPublish) {

    checkLock(namespace, isEmergencyPublish, operator);

    Map<String, String> operateNamespaceItems = getNamespaceItems(namespace);

    Namespace parentNamespace = namespaceService.findParentNamespace(namespace);

    //branch release
    if (parentNamespace != null) {
      return publishBranchNamespace(parentNamespace, namespace, operateNamespaceItems,
                                    releaseName, releaseComment, operator, isEmergencyPublish);
    }

    Namespace childNamespace = namespaceService.findChildNamespace(namespace);

    Release previousRelease = null;
    if (childNamespace != null) {
      previousRelease = findLatestActiveRelease(namespace);
    }

    //master release
    Map<String, Object> operationContext = Maps.newHashMap();
    operationContext.put(ReleaseOperationContext.IS_EMERGENCY_PUBLISH, isEmergencyPublish);

    Release release = masterRelease(namespace, releaseName, releaseComment, operateNamespaceItems,
                                    operator, ReleaseOperation.NORMAL_RELEASE, operationContext);

    //merge to branch and auto release
    if (childNamespace != null) {
      mergeFromMasterAndPublishBranch(namespace, childNamespace, operateNamespaceItems,
                                      releaseName, releaseComment, operator, previousRelease,
                                      release, isEmergencyPublish);
    }

    return release;
  }

  private void checkLock(Namespace namespace, boolean isEmergencyPublish, String operator) {
    if (!isEmergencyPublish) {
      NamespaceLock lock = namespaceLockService.findLock(namespace.getId());
      if (lock != null && lock.getDataChangeCreatedBy().equals(operator)) {
        throw new BadRequestException("Config can not be published by yourself.");
      }
    }
  }

  private void mergeFromMasterAndPublishBranch(Namespace parentNamespace, Namespace childNamespace,
                                               Map<String, String> parentNamespaceItems,
                                               String releaseName, String releaseComment,
                                               String operator, Release masterPreviousRelease,
                                               Release parentRelease, boolean isEmergencyPublish) {
    //create release for child namespace
    Map<String, String> childReleaseConfiguration = getNamespaceReleaseConfiguration(childNamespace);
    Map<String, String> parentNamespaceOldConfiguration = masterPreviousRelease == null ?
                                                          null : gson.fromJson(masterPreviousRelease.getConfigurations(),
                                                                        GsonType.CONFIG);

    Map<String, String> childNamespaceToPublishConfigs =
        calculateChildNamespaceToPublishConfiguration(parentNamespaceOldConfiguration,
                                                      parentNamespaceItems,
                                                      childNamespace);
    //compare
    if (!childNamespaceToPublishConfigs.equals(childReleaseConfiguration)) {
      branchRelease(parentNamespace, childNamespace, releaseName, releaseComment,
                    childNamespaceToPublishConfigs, parentRelease.getId(), operator,
                    ReleaseOperation.MASTER_NORMAL_RELEASE_MERGE_TO_GRAY, isEmergencyPublish);
    }

  }

  private Release publishBranchNamespace(Namespace parentNamespace, Namespace childNamespace,
                                         Map<String, String> childNamespaceItems,
                                         String releaseName, String releaseComment,
                                         String operator, boolean isEmergencyPublish) {
    Release parentLatestRelease = findLatestActiveRelease(parentNamespace);
    Map<String, String> parentConfigurations = parentLatestRelease != null ?
                                               gson.fromJson(parentLatestRelease.getConfigurations(),
                                                             GsonType.CONFIG) : new HashMap<>();
    long baseReleaseId = parentLatestRelease == null ? 0 : parentLatestRelease.getId();

    Map<String, String> childNamespaceToPublishConfigs = mergeConfiguration(parentConfigurations, childNamespaceItems);

    return branchRelease(parentNamespace, childNamespace, releaseName, releaseComment,
                         childNamespaceToPublishConfigs, baseReleaseId, operator,
                         ReleaseOperation.GRAY_RELEASE, isEmergencyPublish);

  }

  private Release masterRelease(Namespace namespace, String releaseName, String releaseComment,
                                Map<String, String> configurations, String operator,
                                int releaseOperation, Map<String, Object> operationContext) {
    Release lastActiveRelease = findLatestActiveRelease(namespace);
    long previousReleaseId = lastActiveRelease == null ? 0 : lastActiveRelease.getId();
    Release release = createRelease(namespace, releaseName, releaseComment,
                                    configurations, operator);

    releaseHistoryService.createReleaseHistory(namespace.getAppId(), namespace.getClusterName(),
                                               namespace.getNamespaceName(), namespace.getClusterName(),
                                               release.getId(), previousReleaseId, releaseOperation,
                                               operationContext, operator);

    return release;
  }

  private Release branchRelease(Namespace parentNamespace, Namespace childNamespace,
                                String releaseName, String releaseComment,
                                Map<String, String> configurations, long baseReleaseId,
                                String operator, int releaseOperation, boolean isEmergencyPublish) {
    Release previousRelease = findLatestActiveRelease(childNamespace.getAppId(),
                                                      childNamespace.getClusterName(),
                                                      childNamespace.getNamespaceName());
    long previousReleaseId = previousRelease == null ? 0 : previousRelease.getId();

    Map<String, Object> releaseOperationContext = Maps.newHashMap();
    releaseOperationContext.put(ReleaseOperationContext.BASE_RELEASE_ID, baseReleaseId);
    releaseOperationContext.put(ReleaseOperationContext.IS_EMERGENCY_PUBLISH, isEmergencyPublish);

    Release release =
        createRelease(childNamespace, releaseName, releaseComment, configurations, operator);

    //update gray release rules
    GrayReleaseRule grayReleaseRule = namespaceBranchService.updateRulesReleaseId(childNamespace.getAppId(),
                                                                                parentNamespace.getClusterName(),
                                                                                childNamespace.getNamespaceName(),
                                                                                childNamespace.getClusterName(),
                                                                                release.getId(), operator);

    if (grayReleaseRule != null) {
      releaseOperationContext.put(ReleaseOperationContext.RULES, GrayReleaseRuleItemTransformer
          .batchTransformFromJSON(grayReleaseRule.getRules()));
    }

    releaseHistoryService.createReleaseHistory(parentNamespace.getAppId(), parentNamespace.getClusterName(),
                                               parentNamespace.getNamespaceName(), childNamespace.getClusterName(),
                                               release.getId(),
                                               previousReleaseId, releaseOperation, releaseOperationContext, operator);

    return release;
  }

  private Map<String, String> mergeConfiguration(Map<String, String> baseConfigurations,
                                                 Map<String, String> coverConfigurations) {
    Map<String, String> result = new HashMap<>();
    //copy base configuration
    for (Map.Entry<String, String> entry : baseConfigurations.entrySet()) {
      result.put(entry.getKey(), entry.getValue());
    }

    //update and publish
    for (Map.Entry<String, String> entry : coverConfigurations.entrySet()) {
      result.put(entry.getKey(), entry.getValue());
    }

    return result;
  }

  private Map<String, String> getNamespaceItems(Namespace namespace) {
    List<Item> items = itemService.findItems(namespace.getId());
    Map<String, String> configurations = new HashMap<String, String>();
    for (Item item : items) {
      if (StringUtils.isEmpty(item.getKey())) {
        continue;
      }
      configurations.put(item.getKey(), item.getValue());
    }

    return configurations;
  }

  private Map<String, String> getNamespaceReleaseConfiguration(Namespace namespace) {
    Release release = findLatestActiveRelease(namespace);
    Map<String, String> configuration = new HashMap<>();
    if (release != null) {
      configuration = new Gson().fromJson(release.getConfigurations(), GsonType.CONFIG);
    }
    return configuration;
  }

  private Release createRelease(Namespace namespace, String name, String comment,
                                Map<String, String> configurations, String operator) {
    Release release = new Release();
    release.setReleaseKey(ReleaseKeyGenerator.generateReleaseKey(namespace));
    release.setDataChangeCreatedTime(new Date());
    release.setDataChangeCreatedBy(operator);
    release.setDataChangeLastModifiedBy(operator);
    release.setName(name);
    release.setComment(comment);
    release.setAppId(namespace.getAppId());
    release.setClusterName(namespace.getClusterName());
    release.setNamespaceName(namespace.getNamespaceName());
    release.setConfigurations(gson.toJson(configurations));
    release = releaseRepository.save(release);

    namespaceLockService.unlock(namespace.getId());
    auditService.audit(Release.class.getSimpleName(), release.getId(), Audit.OP.INSERT,
                       release.getDataChangeCreatedBy());

    return release;
  }

  @Transactional
  public Release rollback(long releaseId, String operator) {
    Release release = findOne(releaseId);
    if (release == null) {
      throw new NotFoundException("release not found");
    }
    if (release.isAbandoned()) {
      throw new BadRequestException("release is not active");
    }

    String appId = release.getAppId();
    String clusterName = release.getClusterName();
    String namespaceName = release.getNamespaceName();

    PageRequest page = new PageRequest(0, 2);
    List<Release> twoLatestActiveReleases = findActiveReleases(appId, clusterName, namespaceName, page);
    if (twoLatestActiveReleases == null || twoLatestActiveReleases.size() < 2) {
      throw new BadRequestException(String.format(
          "Can't rollback namespace(appId=%s, clusterName=%s, namespaceName=%s) because there is only one active release",
          appId,
          clusterName,
          namespaceName));
    }

    release.setAbandoned(true);
    release.setDataChangeLastModifiedBy(operator);

    releaseRepository.save(release);

    releaseHistoryService.createReleaseHistory(appId, clusterName,
                                               namespaceName, clusterName, twoLatestActiveReleases.get(1).getId(),
                                               release.getId(), ReleaseOperation.ROLLBACK, null, operator);

    //publish child namespace if namespace has child
    rollbackChildNamespace(appId, clusterName, namespaceName, twoLatestActiveReleases, operator);

    return release;
  }

  private void rollbackChildNamespace(String appId, String clusterName, String namespaceName,
                                      List<Release> parentNamespaceTwoLatestActiveRelease, String operator) {
    Namespace parentNamespace = namespaceService.findOne(appId, clusterName, namespaceName);
    Namespace childNamespace = namespaceService.findChildNamespace(appId, clusterName, namespaceName);
    if (parentNamespace == null || childNamespace == null) {
      return;
    }

    Release abandonedRelease = parentNamespaceTwoLatestActiveRelease.get(0);
    Release parentNamespaceNewLatestRelease = parentNamespaceTwoLatestActiveRelease.get(1);

    Map<String, String> parentNamespaceAbandonedConfiguration = gson.fromJson(abandonedRelease.getConfigurations(),
                                                                              GsonType.CONFIG);

    Map<String, String>
        parentNamespaceNewLatestConfiguration =
        gson.fromJson(parentNamespaceNewLatestRelease.getConfigurations(), GsonType.CONFIG);

    Map<String, String>
        childNamespaceNewConfiguration =
        calculateChildNamespaceToPublishConfiguration(parentNamespaceAbandonedConfiguration,
                                                      parentNamespaceNewLatestConfiguration,
                                                      childNamespace);

    branchRelease(parentNamespace, childNamespace,
                  TIMESTAMP_FORMAT.format(new Date()) + "-master-rollback-merge-to-gray", "",
                  childNamespaceNewConfiguration, parentNamespaceNewLatestRelease.getId(), operator,
                  ReleaseOperation.MATER_ROLLBACK_MERGE_TO_GRAY, false);
  }

  private Map<String, String> calculateChildNamespaceToPublishConfiguration(
      Map<String, String> parentNamespaceOldConfiguration,
      Map<String, String> parentNamespaceNewConfiguration,
      Namespace childNamespace) {
    //first. calculate child namespace modified configs
    Release childNamespaceLatestActiveRelease = findLatestActiveRelease(childNamespace);

    Map<String, String> childNamespaceLatestActiveConfiguration = childNamespaceLatestActiveRelease == null ? null :
                                                                  gson.fromJson(childNamespaceLatestActiveRelease
                                                                                .getConfigurations(),
                                                                                GsonType.CONFIG);

    Map<String, String> childNamespaceModifiedConfiguration = calculateBranchModifiedItemsAccordingToRelease(
        parentNamespaceOldConfiguration, childNamespaceLatestActiveConfiguration);

    //second. append child namespace modified configs to parent namespace new latest configuration
    return mergeConfiguration(parentNamespaceNewConfiguration, childNamespaceModifiedConfiguration);
  }

  private Map<String, String> calculateBranchModifiedItemsAccordingToRelease(
      Map<String, String> masterReleaseConfigs,
      Map<String, String> branchReleaseConfigs) {

    Map<String, String> modifiedConfigs = new HashMap<>();

    if (CollectionUtils.isEmpty(branchReleaseConfigs)) {
      return modifiedConfigs;
    }

    if (CollectionUtils.isEmpty(masterReleaseConfigs)) {
      return branchReleaseConfigs;
    }

    for (Map.Entry<String, String> entry : branchReleaseConfigs.entrySet()) {

      if (!Objects.equals(entry.getValue(), masterReleaseConfigs.get(entry.getKey()))) {
        modifiedConfigs.put(entry.getKey(), entry.getValue());
      }
    }

    return modifiedConfigs;

  }

  @Transactional
  public int batchDelete(String appId, String clusterName, String namespaceName, String operator) {
    return releaseRepository.batchDelete(appId, clusterName, namespaceName, operator);
  }

}


text:
/**
 * @brief XaMs - Open source C++ Micro Services framework
 * @author Alessandro Mariotti <alessandromariotti@hotmail.com>
*/

#ifndef XALIBERROR_H
#define XALIBERROR_H

#include <XaLibBase.h>

class XaLibError : protected XaLibBase {

    private:

        map<int,string> XaErrors;

    protected:

    public:

        void Setup();
        string GetError(const int& ErrorCode);

        XaLibError();
        ~XaLibError();
};
#endif


text:
#ifndef CHARACTER_CONTROLLER_INTERFACE_H
#define CHARACTER_CONTROLLER_INTERFACE_H

#include "LinearMath/btVector3.h"
#include "BulletDynamics/Dynamics/btActionInterface.h"

class btCollisionShape;
class btRigidBody;
class btCollisionWorld;

class btCharacterControllerInterface : public btActionInterface
{
public:
	btCharacterControllerInterface () {};
	virtual ~btCharacterControllerInterface () {};

	virtual void	setWalkDirection(const btVector3& walkDirection) = 0;
	virtual void	reset () = 0;
	virtual void	warp (const btVector3& origin) = 0;

	virtual void	preStep ( btCollisionWorld* collisionWorld) = 0;
	virtual void	playerStep (btCollisionWorld* collisionWorld, btScalar dt) = 0;
	virtual bool	canJump () const = 0;
	virtual void	jump () = 0;

	virtual bool	onGround () const = 0;
};

#endif


text:
package com.echsylon.kraken.request;

import com.echsylon.kraken.Dictionary;
import com.echsylon.kraken.dto.Order;
import com.echsylon.kraken.internal.CallCounter;
import com.google.gson.reflect.TypeToken;

import static com.echsylon.kraken.internal.Utils.asString;

/**
 * This class can build a request that retrieves information about any closed
 * orders.
 * <p>
 * For further technical details see Kraken API documentation at:
 * https://www.kraken.com/help/api
 */
@SuppressWarnings("WeakerAccess")
public class ClosedOrdersRequestBuilder extends RequestBuilder<Dictionary<Order>, ClosedOrdersRequestBuilder> {

    /**
     * Creates a new request builder.
     *
     * @param callCounter The request call counter. May be null.
     * @param baseUrl     The base url of the request.
     * @param key         The user API key.
     * @param secret      The corresponding secret.
     */
    public ClosedOrdersRequestBuilder(final CallCounter callCounter,
                                      final String baseUrl,
                                      final String key,
                                      final byte[] secret) {

        super(1, callCounter, key, secret, baseUrl,
                "POST", "/0/private/ClosedOrders",
                TypeToken.getParameterized(
                        Dictionary.class,
                        Order.class).getType());
    }

    /**
     * Sets the one time password to use when performing the request.
     *
     * @param oneTimePassword The password.
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useOneTimePassword(final String oneTimePassword) {
        data.put("otp", oneTimePassword);
        return this;
    }

    /**
     * Sets the include trades request property.
     *
     * @param includeTrades Whether to include trades. Defaults to false.
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useTradesFlag(final boolean includeTrades) {
        data.put("trades", asString(includeTrades));
        return this;
    }

    /**
     * Sets the user reference request property.
     *
     * @param userReferenceId Restrict results to given user reference id.
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useReference(final String userReferenceId) {
        data.put("userref", userReferenceId);
        return this;
    }

    /**
     * Sets the start request property.
     *
     * @param start Start time or transaction id of results. Exclusive.
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useStartTag(final String start) {
        data.put("start", start);
        return this;
    }

    /**
     * Sets the end request property.
     *
     * @param end End time or transaction id of results. Inclusive.
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useEndTag(final String end) {
        data.put("end", end);
        return this;
    }

    /**
     * Sets the offset request property.
     *
     * @param offset Result offset.
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useOffset(final int offset) {
        data.put("ofs", asString(offset));
        return this;
    }

    /**
     * Sets the close time request property.
     *
     * @param closeTime Which time to use. Options: "both" (default), "open", "close".
     * @return This request builder instance allowing method call chaining.
     */
    public ClosedOrdersRequestBuilder useCloseTime(final String closeTime) {
        data.put("closetime", closeTime);
        return this;
    }

}


text:
massive-octo-nemesis
====================

furry-octo-wookie


text:
package com.actian.ilabs.dataflow.cassandra.getter;

public interface Getter {

	Object get();
}


text:
/* https://www.cssscript.com/material-style-toggle-switches-with-pure-css-css3/ */

/* edited to fit our design */

.toggle-switch-label {
  position: relative;
  display: block;
  height: 20px;
  width: 44px;
  background: #898989;
  border-radius: 100px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 0px;
}

.toggle-switch-label:after {
  position: absolute;
  left: -2px;
  top: -3px;
  display: block;
  width: 26px;
  height: 26px;
  border-radius: 100px;
  background: #fff;
  box-shadow: 0px 2px 1px rgba(0, 0, 0, 0.2);
  content: '';
  transition: all 0.3s ease;
}

.toggle-switch-label:active:after {
  transform: scale(1.15, 0.85);
}

.toggle-switch:checked~label {
  background: #E77964;
}

.toggle-switch:checked~label:after {
  left: 20px;
  background: #B74934;
}

.toggle-switch:disabled~label {
  background: #d5d5d5;
  pointer-events: none;
}

.toggle-switch:disabled~label:after {
  background: #bcbdbc;
}

.hidden {
  display: none;
}


text:
using System;
using System.Collections.Generic;
using JabbR.Models;
using JabbR.Services;
using WorldDomination.Web.Authentication;

namespace JabbR.ViewModels
{
    public class LoginViewModel
    {
        public LoginViewModel(ApplicationSettings settings, IEnumerable<IAuthenticationProvider> configuredProviders, IEnumerable<ChatUserIdentity> userIdentities)
        {
            SocialDetails = new SocialLoginViewModel(configuredProviders, userIdentities);
            AllowUserRegistration = settings.AllowUserRegistration;
        }

        public bool AllowUserRegistration { get; set; }
        public SocialLoginViewModel SocialDetails { get; private set; }
    }
}


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

using System;

namespace Microsoft.Xunit.Performance.Api
{
    /// <summary>
    /// Defines an interval with a mechanism for testing if a value falls in the range.
    /// </summary>
    /// <typeparam name="T">The type interval space.</typeparam>
    internal interface IInterval<T>
        where T : IComparable, IComparable<T>
    {
        /// <summary>
        /// Start limit of the interval.
        /// </summary>
        T Start { get; }

        /// <summary>
        /// End limit of the interval.
        /// </summary>
        T End { get; }

        /// <summary>
        /// Determines if a value falls in this range.
        /// </summary>
        /// <param name="value">Value to test against this interval.</param>
        /// <returns>Less than zero, if value precedes Start. Greater than zero, if value follows End. Othewise, zero.</returns>
        int IsInInterval(T value);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_pro_selected" android:state_checked="true"></item>
    <item android:drawable="@drawable/ic_pro_normal" android:state_checked="false"></item>
</selector>


text:
//
//  BBResultsHeaderView.m
//  Bounding Bandits
//
//  Created by Nicholas Clark on 4/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BBResultsHeaderView.h"
#import "UIImageView+DD.h"

@implementation BBResultsHeaderView

@synthesize profileImage1;
@synthesize profileImage2;
@synthesize score1;
@synthesize score2;
@synthesize game;

+(id)headerWithGame:(CollabGame*)game
{
    BBResultsHeaderView* view = [[[ NSBundle mainBundle ] loadNibNamed:@"BBResultsHeaderView" owner:nil options:nil ] objectAtIndex:0 ];
    view.game = game;
    view.frame = CGRectMake(0,0,540,120);

    NSMutableDictionary* scores = [ view.game scoresForUsers ];
    PFUser* user1 = [ view.game.users objectAtIndex:0 ];
    PFUser* user2 = [ view.game.users objectAtIndex:1 ];

    [ view.profileImage1 loadImageWithURL:[ NSURL URLWithString:[ user1 objectForKey:@"profilePicture" ]] defaultImage:[ UIImage imageNamed:@"img/noface.png" ] onComplete:nil ];
    [ view.profileImage2 loadImageWithURL:[ NSURL URLWithString:[ user2 objectForKey:@"profilePicture" ]] defaultImage:[ UIImage imageNamed:@"img/noface.png" ] onComplete:nil ];

    NSString* user1Id = user1.objectId;
    NSString* user2Id = user2.objectId;

    NSString* score1 = [ NSString stringWithFormat:@"%d", [[ scores objectForKey:user1Id] intValue ]];
    NSString* score2= [ NSString stringWithFormat:@"%d", [[ scores objectForKey:user2Id] intValue ]];
    view.score1.text = score1;
    view.score2.text = score2;

    view.backgroundColor = [ UIColor colorWithRed:0.173 green:0.18 blue:0.196 alpha:1 ];

    return view;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Titusville, FL</location>
	<station_id>KTIX</station_id>
	<latitude>28.51667</latitude>
	<longitude>-80.8</longitude>
	<observation_time>Last Updated on Jan 4 2016, 8:47 pm EST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 20:47:00 -0500</observation_time_rfc822>
	<weather>Clear</weather>
	<temperature_string>55.0 F (13.0 C)</temperature_string>
	<temp_f>55.0</temp_f>
	<temp_c>13.0</temp_c>
	<relative_humidity>67</relative_humidity>
	<wind_string>North at 17.3 MPH (15 KT)</wind_string>
	<wind_dir>North</wind_dir>
	<wind_degrees>360</wind_degrees>
	<wind_mph>17.3</wind_mph>
	<wind_kt>15</wind_kt>
	<pressure_in>30.11</pressure_in>
	<dewpoint_string>44.6 F (7.0 C)</dewpoint_string>
	<dewpoint_f>44.6</dewpoint_f>
	<dewpoint_c>7.0</dewpoint_c>
	<windchill_string>51 F (11 C)</windchill_string>
      	<windchill_f>51</windchill_f>
      	<windchill_c>11</windchill_c>
	<visibility_mi>7.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KTIX.html</two_day_history_url>
	<icon_url_name>nskc.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KTIX.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
<component name="libraryTable">
  <library name="Maven: org.springframework.cloud:spring-cloud-starter-ribbon:1.1.0.M3">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/springframework/cloud/spring-cloud-starter-ribbon/1.1.0.M3/spring-cloud-starter-ribbon-1.1.0.M3.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/springframework/cloud/spring-cloud-starter-ribbon/1.1.0.M3/spring-cloud-starter-ribbon-1.1.0.M3-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/springframework/cloud/spring-cloud-starter-ribbon/1.1.0.M3/spring-cloud-starter-ribbon-1.1.0.M3-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package com.google.caliper.runner.instrument;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.caliper.bridge.AbstractLogMessageVisitor;
import com.google.caliper.bridge.StopMeasurementLogMessage;
import com.google.caliper.core.BenchmarkClassModel.MethodModel;
import com.google.caliper.core.InvalidBenchmarkException;
import com.google.caliper.model.InstrumentSpec;
import com.google.caliper.model.InstrumentType;
import com.google.caliper.model.Measurement;
import com.google.caliper.runner.config.VmConfig;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder;
import javax.inject.Inject;

public abstract class Instrument {
  protected ImmutableMap<String, String> options = ImmutableMap.of();
  private String name = getClass().getSimpleName();

  @VisibleForTesting
  @Inject
  public void setOptions(@InstrumentOptions ImmutableMap<String, String> options) {
    this.options =
        ImmutableMap.copyOf(Maps.filterKeys(options, Predicates.in(instrumentOptions())));
  }

  @Inject
  void setInstrumentName(@InstrumentName String name) {
    this.name = name;
  }

  public String name() {
    return name;
  }

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

  public abstract boolean isBenchmarkMethod(MethodModel method);

  public abstract InstrumentedMethod createInstrumentedMethod(MethodModel benchmarkMethod)
      throws InvalidBenchmarkException;

  /** Indicates that trials using this instrument can be run in parallel with other trials. */
  public boolean parallelizable() {
    return false;
  }

  /** The application of an instrument to a particular benchmark method. */
  // TODO(gak): consider passing in Instrument explicitly for DI
  public abstract class InstrumentedMethod {
    protected MethodModel benchmarkMethod;

    protected InstrumentedMethod(MethodModel benchmarkMethod) {
      this.benchmarkMethod = checkNotNull(benchmarkMethod);
    }

    public final Instrument instrument() {
      return Instrument.this;
    }

    public final MethodModel benchmarkMethod() {
      return benchmarkMethod;
    }

    @Override
    public final boolean equals(Object obj) {
      if (obj == this) {
        return true;
      } else if (obj instanceof InstrumentedMethod) {
        InstrumentedMethod that = (InstrumentedMethod) obj;
        return Instrument.this.equals(that.instrument())
            && this.benchmarkMethod.equals(that.benchmarkMethod);
      }
      return super.equals(obj);
    }

    @Override
    public final int hashCode() {
      return Objects.hashCode(Instrument.this, benchmarkMethod);
    }

    @Override
    public final String toString() {
      return MoreObjects.toStringHelper(InstrumentedMethod.class)
          .add("instrument", Instrument.this)
          .add("benchmarkMethod", benchmarkMethod)
          .toString();
    }

    public abstract InstrumentType type();

    /**
     * Return the subset of options (and possibly a transformation thereof) to be used in the
     * worker. Returns all instrument options by default.
     */
    public ImmutableMap<String, String> workerOptions() {
      return options;
    }

    public abstract MeasurementCollectingVisitor getMeasurementCollectingVisitor();

    /**
     * Subclasses can override this to validate results across all trials for a given instrumented
     * method.
     *
     * @return an optional warning message to be printed to the console.
     */
    public Optional<String> validateMeasurements(Iterable<ImmutableList<Measurement>> results) {
      return Optional.absent();
    }
  }

  public final ImmutableMap<String, String> options() {
    return options;
  }

  public final InstrumentSpec getSpec() {
    return new InstrumentSpec.Builder()
        .instrumentClass(getClass())
        .addAllOptions(options())
        .build();
  }

  /**
   * Defines the list of options applicable to this instrument. Implementations that use options
   * will need to override this method.
   */
  protected ImmutableSet<String> instrumentOptions() {
    return ImmutableSet.of();
  }

  /**
   * Returns some arguments that should be added to the command line when invoking this instrument's
   * worker.
   *
   * @param vmConfig the configuration for the VM on which this is running.
   */
  public ImmutableSet<String> getExtraCommandLineArgs(VmConfig vmConfig) {
    return ImmutableSet.of();
  }

  /**
   * A default implementation of {@link MeasurementCollectingVisitor} that collects measurements for
   * pre-specified descriptions.
   */
  protected static final class DefaultMeasurementCollectingVisitor extends AbstractLogMessageVisitor
      implements MeasurementCollectingVisitor {
    static final int DEFAULT_NUMBER_OF_MEASUREMENTS = 9;
    final ImmutableSet<String> requiredDescriptions;
    final ListMultimap<String, Measurement> measurementsByDescription;
    final int requiredMeasurements;

    DefaultMeasurementCollectingVisitor(ImmutableSet<String> requiredDescriptions) {
      this(requiredDescriptions, DEFAULT_NUMBER_OF_MEASUREMENTS);
    }

    DefaultMeasurementCollectingVisitor(
        ImmutableSet<String> requiredDescriptions, int requiredMeasurements) {
      this.requiredDescriptions = requiredDescriptions;
      checkArgument(!requiredDescriptions.isEmpty());
      this.requiredMeasurements = requiredMeasurements;
      checkArgument(requiredMeasurements > 0);
      this.measurementsByDescription =
          MultimapBuilder.hashKeys(requiredDescriptions.size())
              .arrayListValues(requiredMeasurements)
              .build();
    }

    @Override
    public void visit(StopMeasurementLogMessage logMessage) {
      for (Measurement measurement : logMessage.measurements()) {
        measurementsByDescription.put(measurement.description(), measurement);
      }
    }

    @Override
    public boolean isDoneCollecting() {
      for (String description : requiredDescriptions) {
        if (measurementsByDescription.get(description).size() < requiredMeasurements) {
          return false;
        }
      }
      return true;
    }

    @Override
    public boolean isWarmupComplete() {
      return true;
    }

    @Override
    public ImmutableList<Measurement> getMeasurements() {
      return ImmutableList.copyOf(measurementsByDescription.values());
    }

    @Override
    public ImmutableList<String> getMessages() {
      return ImmutableList.of();
    }
  }
}