text:
({
	win: Ti.UI.currentWindow,
	app: Ti.UI.currentWindow.app,

	init: function() {
		var self = this;

		var label1 = Ti.UI.createLabel({text: 'New window created.', top: 20});

		var foundationContextAvailable = 'Foundation context available: ' + (typeof this.app.foundation != 'undefined' ? 'yes' : 'no');

		var label2 = Ti.UI.createLabel({text: foundationContextAvailable, top: 50});
		var closeButton = Ti.UI.createButton({title: 'Close', bottom: 10, height: 30});
		closeButton.addEventListener('click', function() {
			self.win.close();
		})
		this.win.add(label1);
		this.win.add(label2);

		if(!this.win.hideCloseButton) {
			this.win.add(closeButton);
		}
	}
}).init();


text:
//
// Copyright (C) OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//

#ifndef __INET_MEDIUMCANVASVISUALIZER_H
#define __INET_MEDIUMCANVASVISUALIZER_H

#include "inet/common/figures/HeatMapFigure.h"
#include "inet/common/figures/TrailFigure.h"
#include "inet/common/geometry/common/CanvasProjection.h"
#include "inet/physicallayer/contract/packetlevel/IRadioFrame.h"
#include "inet/physicallayer/contract/packetlevel/IReceptionDecision.h"
#include "inet/physicallayer/contract/packetlevel/ITransmission.h"
#include "inet/visualizer/base/MediumVisualizerBase.h"
#include "inet/visualizer/scene/NetworkNodeCanvasVisualizer.h"
#include "inet/visualizer/util/AnimationSpeedInterpolator.h"

namespace inet {

namespace visualizer {

class INET_API MediumCanvasVisualizer : public MediumVisualizerBase
{
  protected:
    /** @name Parameters */
    //@{
    double zIndex = NaN;
    const CanvasProjection *canvasProjection = nullptr;
    SignalShape signalShape = SIGNAL_SHAPE_RING;
    double signalOpacity = NaN;
    int signalRingCount = -1;
    double signalRingSize = NaN;
    double signalFadingDistance = NaN;
    double signalFadingFactor = NaN;
    int signalWaveCount = -1;
    double signalWaveLength = NaN;
    double signalWaveWidth = NaN;
    double signalWaveFadingAnimationSpeedFactor = NaN;
    bool displayCommunicationHeat = false;
    int communicationHeatMapSize = 100;
    //@}

    /** @name Internal state */
    //@{
    enum SignalInProgress {
        SIP_NONE,
        SIP_PROPAGATION,
        SIP_TRANSMISSION,
    };
    SignalInProgress lastSignalInProgress = SIP_NONE;
    AnimationSpeedInterpolator animationSpeedInterpolator;
    NetworkNodeCanvasVisualizer *networkNodeVisualizer = nullptr;
    /**
     * The list of ongoing transmissions.
     */
    std::vector<const ITransmission *> transmissions;
    /**
     * The list of transmission figures.
     */
    std::map<const IRadio *, cFigure *> transmissionFigures;
    /**
     * The list of reception figures.
     */
    std::map<const IRadio *, cFigure *> receptionFigures;
    /**
     * The propagating signal figures.
     */
    std::map<const ITransmission *, cFigure *> signalFigures;
    //@}

    /** @name Figures */
    //@{
    /**
     * The layer figure that contains the figures representing the ongoing communications.
     */
    cGroupFigure *signalLayer = nullptr;
    /**
     * The heat map figure that shows the recent successful communications.
     */
    HeatMapFigure *communicationHeat = nullptr;
    //@}

  protected:
    virtual void initialize(int stage) override;
    virtual void refreshDisplay() const override;
    virtual void setAnimationSpeed();

    virtual cFigure *getTransmissionFigure(const IRadio *radio) const;
    virtual void setTransmissionFigure(const IRadio *radio, cFigure *figure);
    virtual cFigure *removeTransmissionFigure(const IRadio *radio);

    virtual cFigure *getReceptionFigure(const IRadio *radio) const;
    virtual void setReceptionFigure(const IRadio *radio, cFigure *figure);
    virtual cFigure *removeReceptionFigure(const IRadio *radio);

    virtual cFigure *getSignalFigure(const ITransmission *transmission) const;
    virtual void setSignalFigure(const ITransmission *transmission, cFigure *figure);
    virtual cFigure *removeSignalFigure(const ITransmission *transmission);

    virtual cGroupFigure *createSignalFigure(const ITransmission *transmission) const;
    virtual void refreshSignalFigure(const ITransmission *transmission) const;

    virtual void radioAdded(const IRadio *radio) override;
    virtual void radioRemoved(const IRadio *radio) override;

    virtual void transmissionAdded(const ITransmission *transmission) override;
    virtual void transmissionRemoved(const ITransmission *transmission) override;

    virtual void transmissionStarted(const ITransmission *transmission) override;
    virtual void transmissionEnded(const ITransmission *transmission) override;
    virtual void receptionStarted(const IReception *reception) override;
    virtual void receptionEnded(const IReception *reception) override;
};

} // namespace visualizer

} // namespace inet

#endif // ifndef __INET_MEDIUMCANVASVISUALIZER_H

redpajama_set_name: RedPajamaGithub


text:
namespace arangodb {

namespace graph {

template <class StepDetails>
class BaseStep {
 public:
  BaseStep(size_t prev = std::numeric_limits<size_t>::max(), size_t depth = 0,
           double weight = 1.0)
      : _previous{prev}, _depth{depth}, _weight(weight) {}

  size_t getPrevious() const { return _previous; }

  bool isFirst() const {
    return _previous == std::numeric_limits<size_t>::max();
  }

  bool isLooseEnd() const {
    return static_cast<StepDetails*>(this)->isLooseEnd();
  }

  size_t getDepth() const { return _depth; }

  double getWeight() const { return _weight; }

  ResultT<std::pair<std::string, size_t>> extractCollectionName(
      arangodb::velocypack::HashedStringRef const& idHashed) const {
    size_t pos = idHashed.find('/');
    if (pos == std::string::npos) {
      // Invalid input. If we get here somehow we managed to store invalid
      // _from/_to values or the traverser did a let an illegal start through
      TRI_ASSERT(false);
      return Result{TRI_ERROR_GRAPH_INVALID_EDGE,
                    "edge contains invalid value " + idHashed.toString()};
    }

    std::string colName = idHashed.substr(0, pos).toString();
    return std::make_pair(colName, pos);
  }

 private:
  size_t _previous;
  size_t _depth;
  double _weight;
};
}  // namespace graph
}  // namespace arangodb


text:
alias indenitail="tail -200 -F $HOME/indeni/logs/indeni.log"
alias indenilog="emacs-gui $HOME/indeni/logs/indeni.log"


text:
package org.takes.rs;

import com.google.common.base.Joiner;
import com.jcabi.matchers.XhtmlMatchers;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.IOUtils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.BeforeClass;
import org.junit.Test;
import org.takes.misc.StateAwareInputStream;

/**
 * Test case for {@link RsXSLT}.
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 0.1
 */
public final class RsXSLTTest {

    /**
     * Validate encoding.
     */
    @BeforeClass
    public static void before() {
        MatcherAssert.assertThat(
            "default charset during testing must be UTF-8",
            Charset.defaultCharset().name(),
            Matchers.equalTo("UTF-8")
        );
    }

    /**
     * RsXSLT can convert XML to HTML.
     * @throws IOException If some problem inside
     */
    @Test
    public void convertsXmlToHtml() throws IOException {
        final String xml = Joiner.on(' ').join(
            "<?xml-stylesheet href='/a.xsl' type='text/xsl'?>",
            "<page><data>ура</data></page>"
        );
        final String xsl = Joiner.on(' ').join(
            ""
        );
        MatcherAssert.assertThat(
            IOUtils.toString(
                new RsXSLT(
                    new RsText(xml),
                    new URIResolver() {
                        @Override
                        public Source resolve(final String href,
                            final String base) {
                            return new StreamSource(new StringReader(xsl));
                        }
                    }
                ).body()
            ),
            XhtmlMatchers.hasXPath("//xhtml:p[.='\u0443']")
        );
    }

    /**
     * RsXSLT can convert XML to plain text.
     * @throws IOException If some problem inside
     */
    @Test
    public void convertsXmlToPlainText() throws IOException {
        final String xml = Joiner.on(' ').join(
            "<?xml-stylesheet href='/x.xsl' type='text/xsl'?>",
            "
<name>Jeffrey</name>
"
        );
        final String xsl = Joiner.on(' ').join(
            ""
        );
        MatcherAssert.assertThat(
            new RsPrint(
                new RsXSLT(
                    new RsText(xml),
                    new URIResolver() {
                        @Override
                        public Source resolve(final String href,
                            final String base) {
                            return new StreamSource(new StringReader(xsl));
                        }
                    }
                )
            ).print(),
            Matchers.endsWith("Hey, Jeffrey!")
        );
    }

    /**
     * RsXSLT closes decorated Response body's InputStream when XML conversion
     * is done.
     * @throws Exception If some problem inside
     */
    @Test
    public void closesDecoratedResponseInputStream() throws Exception {
        final String xml = Joiner.on(' ').join(
            "<?xml-stylesheet href='/b.xsl' type='text/xsl'?>",
            "<subject>World</subject>"
        );
        final String xsl = Joiner.on(' ').join(
            ""
        );
        final StateAwareInputStream stream =
            new StateAwareInputStream(IOUtils.toInputStream(xml));
        MatcherAssert.assertThat(
            new RsPrint(
                new RsXSLT(
                    new RsText(stream),
                    new URIResolver() {
                        @Override
                        public Source resolve(final String href,
                            final String base) {
                            return new StreamSource(new StringReader(xsl));
                        }
                    }
                )
            ).print(),
            Matchers.endsWith("Hello, World!")
        );
        MatcherAssert.assertThat(
            stream.isClosed(),
            Matchers.is(true)
        );
    }

    /**
     * RsXSLT can resolve in classpath.
     * @throws IOException If some problem inside
     */
    @Test
    public void resolvesInClasspath() throws IOException {
        MatcherAssert.assertThat(
            new RsPrint(
                new RsXSLT(
                    new RsText(
                        Joiner.on(' ').join(
                            "<?xml-stylesheet",
                            " href='/org/takes/rs/simple.xsl?0'",
                            " type='text/xsl'?>",
                            "
<name>Bobby</name>
"
                        )
                    )
                )
            ).print(),
            Matchers.endsWith("Hello, Bobby!")
        );
        MatcherAssert.assertThat(
            new RsPrint(
                new RsXSLT(
                    new RsText(
                        Joiner.on(' ').join(
                            "<?xml-stylesheet ",
                            " href='/org/takes/rs/simple.xsl'",
                            " type='text/xsl' ?>",
                            "
<name>Dan</name>
"
                        )
                    )
                )
            ).print(),
            Matchers.endsWith("Hello, Dan!")
        );
        MatcherAssert.assertThat(
            new RsPrint(
                new RsXSLT(
                    new RsText(
                        Joiner.on(' ').join(
                            "<?xml-stylesheet  ",
                            " href='/org/takes/rs/includes.xsl'",
                            "  type='text/xsl' ?>",
                            "
<name>Miranda</name>
"
                        )
                    )
                )
            ).print(),
            Matchers.endsWith("Hello, Miranda!")
        );
    }

}


text:
void mzk_init();
void mzkPlayBlock(short *blockBuffer);

#endif


text:
require "spec_helper"

describe Mongoid::Errors::InvalidFieldType do

  describe "#message" do

    let(:error) do
      described_class.new(Person, :first_name, :stringgy)
    end

    context 'when type is a symbol' do
      let(:error) do
        described_class.new(Person, :first_name, :stringgy)
      end

      it "contains the problem in the message" do
        expect(error.message).to include(
          "Invalid field type :stringgy for field 'first_name' on model 'Person'."
        )
      end

      it "contains the summary in the message" do
        expect(error.message).to include(
          "Model 'Person' defines a field 'first_name' with an unknown type value :stringgy."
        )
      end
    end

    context 'when type is a string' do
      let(:error) do
        described_class.new(Person, :first_name, 'stringgy')
      end

      it "contains the problem in the message" do
        expect(error.message).to include(
          %q,Invalid field type "stringgy" for field 'first_name' on model 'Person'.,
        )
      end

      it "contains the summary in the message" do
        expect(error.message).to include(
          %q,Model 'Person' defines a field 'first_name' with an unknown type value "stringgy".,
        )
      end
    end

    it "contains the resolution in the message" do
      expect(error.message).to include(
        'Please provide a valid type value for the field.'
      )
    end
  end
end


text:
package org.eclipse.jdt.internal.ui.javaeditor;

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

import org.eclipse.swt.custom.StyleRange;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;

import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedPosition;
import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager.Highlighting;
import org.eclipse.jdt.internal.ui.text.JavaPresentationReconciler;

/**
 * Semantic highlighting presenter - UI thread implementation.
 *
 * @since 3.0
 */
public class SemanticHighlightingPresenter implements ITextPresentationListener, ITextInputListener, IDocumentListener {

	/**
	 * Semantic highlighting position updater.
	 */
	private class HighlightingPositionUpdater implements IPositionUpdater {

		/** The position category. */
		private final String fCategory;

		/**
		 * Creates a new updater for the given category.
		 *
		 * @param category the new category.
		 */
		public HighlightingPositionUpdater(String category) {
			fCategory= category;
		}

		/*
		 * @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
		 */
		public void update(DocumentEvent event) {

			int eventOffset= event.getOffset();
			int eventOldLength= event.getLength();
			int eventEnd= eventOffset + eventOldLength;

			try {
				Position[] positions= event.getDocument().getPositions(fCategory);

				for (int i= 0; i != positions.length; i++) {

					HighlightedPosition position= (HighlightedPosition) positions[i];

					// Also update deleted positions because they get deleted by the background thread and removed/invalidated only in the UI runnable
//					if (position.isDeleted())
//						continue;

					int offset= position.getOffset();
					int length= position.getLength();
					int end= offset + length;

					if (offset > eventEnd)
						updateWithPrecedingEvent(position, event);
					else if (end < eventOffset)
						updateWithSucceedingEvent(position, event);
					else if (offset <= eventOffset && end >= eventEnd)
						updateWithIncludedEvent(position, event);
					else if (offset <= eventOffset)
						updateWithOverEndEvent(position, event);
					else if (end >= eventEnd)
						updateWithOverStartEvent(position, event);
					else
						updateWithIncludingEvent(position, event);
				}
			} catch (BadPositionCategoryException e) {
				// ignore and return
			}
		}

		/**
		 * Update the given position with the given event. The event precedes the position.
		 *
		 * @param position The position
		 * @param event The event
		 */
		private void updateWithPrecedingEvent(HighlightedPosition position, DocumentEvent event) {
			String newText= event.getText();
			int eventNewLength= newText != null ? newText.length() : 0;
			int deltaLength= eventNewLength - event.getLength();

			position.setOffset(position.getOffset() + deltaLength);
		}

		/**
		 * Update the given position with the given event. The event succeeds the position.
		 *
		 * @param position The position
		 * @param event The event
		 */
		private void updateWithSucceedingEvent(HighlightedPosition position, DocumentEvent event) {
		}

		/**
		 * Update the given position with the given event. The event is included by the position.
		 *
		 * @param position The position
		 * @param event The event
		 */
		private void updateWithIncludedEvent(HighlightedPosition position, DocumentEvent event) {
			int eventOffset= event.getOffset();
			String newText= event.getText();
			if (newText == null)
				newText= ""; //$NON-NLS-1$
			int eventNewLength= newText.length();

			int deltaLength= eventNewLength - event.getLength();

			int offset= position.getOffset();
			int length= position.getLength();
			int end= offset + length;

			int includedLength= 0;
			while (includedLength < eventNewLength && Character.isJavaIdentifierPart(newText.charAt(includedLength)))
				includedLength++;
			if (includedLength == eventNewLength)
				position.setLength(length + deltaLength);
			else {
				int newLeftLength= eventOffset - offset + includedLength;

				int excludedLength= eventNewLength;
				while (excludedLength > 0 && Character.isJavaIdentifierPart(newText.charAt(excludedLength - 1)))
					excludedLength--;
				int newRightOffset= eventOffset + excludedLength;
				int newRightLength= end + deltaLength - newRightOffset;

				if (newRightLength == 0) {
					position.setLength(newLeftLength);
				} else {
					if (newLeftLength == 0) {
						position.update(newRightOffset, newRightLength);
					} else {
						position.setLength(newLeftLength);
						addPositionFromUI(newRightOffset, newRightLength, position.getHighlighting());
					}
				}
			}
		}

		/**
		 * Update the given position with the given event. The event overlaps with the end of the position.
		 *
		 * @param position The position
		 * @param event The event
		 */
		private void updateWithOverEndEvent(HighlightedPosition position, DocumentEvent event) {
			String newText= event.getText();
			if (newText == null)
				newText= ""; //$NON-NLS-1$
			int eventNewLength= newText.length();

			int includedLength= 0;
			while (includedLength < eventNewLength && Character.isJavaIdentifierPart(newText.charAt(includedLength)))
				includedLength++;
			position.setLength(event.getOffset() - position.getOffset() + includedLength);
		}

		/**
		 * Update the given position with the given event. The event overlaps with the start of the position.
		 *
		 * @param position The position
		 * @param event The event
		 */
		private void updateWithOverStartEvent(HighlightedPosition position, DocumentEvent event) {
			int eventOffset= event.getOffset();
			int eventEnd= eventOffset + event.getLength();

			String newText= event.getText();
			if (newText == null)
				newText= ""; //$NON-NLS-1$
			int eventNewLength= newText.length();

			int excludedLength= eventNewLength;
			while (excludedLength > 0 && Character.isJavaIdentifierPart(newText.charAt(excludedLength - 1)))
				excludedLength--;
			int deleted= eventEnd - position.getOffset();
			int inserted= eventNewLength - excludedLength;
			position.update(eventOffset + excludedLength, position.getLength() - deleted + inserted);
		}

		/**
		 * Update the given position with the given event. The event includes the position.
		 *
		 * @param position The position
		 * @param event The event
		 */
		private void updateWithIncludingEvent(HighlightedPosition position, DocumentEvent event) {
			position.delete();
			position.update(event.getOffset(), 0);
		}
	}

	/** Position updater */
	private IPositionUpdater fPositionUpdater= new HighlightingPositionUpdater(getPositionCategory());

	/** The source viewer this semantic highlighting reconciler is installed on */
	private JavaSourceViewer fSourceViewer;
	/** The background presentation reconciler */
	private JavaPresentationReconciler fPresentationReconciler;

	/** UI's current highlighted positions - can contain null elements */
	private List<Position> fPositions= new ArrayList<Position>();
	/** UI position lock */
	private Object fPositionLock= new Object();

	/** true iff the current reconcile is canceled. */
	private boolean fIsCanceled= false;

	/**
	 * Creates and returns a new highlighted position with the given offset, length and highlighting.
	 *

	 * NOTE: Also called from background thread.
	 *

	 *
	 * @param offset The offset
	 * @param length The length
	 * @param highlighting The highlighting
	 * @return The new highlighted position
	 */
	public HighlightedPosition createHighlightedPosition(int offset, int length, Highlighting highlighting) {
		// TODO: reuse deleted positions
		return new HighlightedPosition(offset, length, highlighting, fPositionUpdater);
	}

	/**
	 * Adds all current positions to the given list.
	 *

	 * NOTE: Called from background thread.
	 *

	 *
	 * @param list The list
	 */
	public void addAllPositions(List<Position> list) {
		synchronized (fPositionLock) {
			list.addAll(fPositions);
		}
	}

	/**
	 * Create a text presentation in the background.
	 *

	 * NOTE: Called from background thread.
	 *

	 *
	 * @param addedPositions the added positions
	 * @param removedPositions the removed positions
	 * @return the text presentation or null, if reconciliation should be canceled
	 */
	public TextPresentation createPresentation(List<Position> addedPositions, List<Position> removedPositions) {
		JavaSourceViewer sourceViewer= fSourceViewer;
		JavaPresentationReconciler presentationReconciler= fPresentationReconciler;
		if (sourceViewer == null || presentationReconciler == null)
			return null;

		if (isCanceled())
			return null;

		IDocument document= sourceViewer.getDocument();
		if (document == null)
			return null;

		int minStart= Integer.MAX_VALUE;
		int maxEnd= Integer.MIN_VALUE;
		for (int i= 0, n= removedPositions.size(); i < n; i++) {
			Position position= removedPositions.get(i);
			int offset= position.getOffset();
			minStart= Math.min(minStart, offset);
			maxEnd= Math.max(maxEnd, offset + position.getLength());
		}
		for (int i= 0, n= addedPositions.size(); i < n; i++) {
			Position position= addedPositions.get(i);
			int offset= position.getOffset();
			minStart= Math.min(minStart, offset);
			maxEnd= Math.max(maxEnd, offset + position.getLength());
		}

		if (minStart < maxEnd)
			try {
				return presentationReconciler.createRepairDescription(new Region(minStart, maxEnd - minStart), document);
			} catch (RuntimeException e) {
				// Assume concurrent modification from UI thread
			}

		return null;
	}

	/**
	 * Create a runnable for updating the presentation.
	 *

	 * NOTE: Called from background thread.
	 *

	 * @param textPresentation the text presentation
	 * @param addedPositions the added positions
	 * @param removedPositions the removed positions
	 * @return the runnable or null, if reconciliation should be canceled
	 */
	public Runnable createUpdateRunnable(final TextPresentation textPresentation, List<Position> addedPositions, List<Position> removedPositions) {
		if (fSourceViewer == null || textPresentation == null)
			return null;

		// TODO: do clustering of positions and post multiple fast runnables
		final HighlightedPosition[] added= new SemanticHighlightingManager.HighlightedPosition[addedPositions.size()];
		addedPositions.toArray(added);
		final SemanticHighlightingManager.HighlightedPosition[] removed= new SemanticHighlightingManager.HighlightedPosition[removedPositions.size()];
		removedPositions.toArray(removed);

		if (isCanceled())
			return null;

		Runnable runnable= new Runnable() {
			public void run() {
				updatePresentation(textPresentation, added, removed);
			}
		};
		return runnable;
	}

	/**
	 * Invalidate the presentation of the positions based on the given added positions and the existing deleted positions.
	 * Also unregisters the deleted positions from the document and patches the positions of this presenter.
	 *

	 * NOTE: Indirectly called from background thread by UI runnable.
	 *

	 * @param textPresentation the text presentation or null, if the presentation should computed in the UI thread
	 * @param addedPositions the added positions
	 * @param removedPositions the removed positions
	 */
	public void updatePresentation(TextPresentation textPresentation, HighlightedPosition[] addedPositions, HighlightedPosition[] removedPositions) {
		if (fSourceViewer == null)
			return;

//		checkOrdering("added positions: ", Arrays.asList(addedPositions)); //$NON-NLS-1$
//		checkOrdering("removed positions: ", Arrays.asList(removedPositions)); //$NON-NLS-1$
//		checkOrdering("old positions: ", fPositions); //$NON-NLS-1$

		// TODO: double-check consistency with document.getPositions(...)
		// TODO: reuse removed positions
		if (isCanceled())
			return;

		IDocument document= fSourceViewer.getDocument();
		if (document == null)
			return;

		String positionCategory= getPositionCategory();

		List<HighlightedPosition> removedPositionsList= Arrays.asList(removedPositions);

		try {
			synchronized (fPositionLock) {
				List<Position> oldPositions= fPositions;
				int newSize= Math.max(fPositions.size() + addedPositions.length - removedPositions.length, 10);

				/*
				 * The following loop is a kind of merge sort: it merges two List<Position>, each
				 * sorted by position.offset, into one new list. The first of the two is the
				 * previous list of positions (oldPositions), from which any deleted positions get
				 * removed on the fly. The second of two is the list of added positions. The result
				 * is stored in newPositions.
				 */
				List<Position> newPositions= new ArrayList<Position>(newSize);
				Position position= null;
				Position addedPosition= null;
				for (int i= 0, j= 0, n= oldPositions.size(), m= addedPositions.length; i < n || position != null || j < m || addedPosition != null;) {
					// loop variant: i + j < old(i + j)

					// a) find the next non-deleted Position from the old list
					while (position == null && i < n) {
						position= oldPositions.get(i++);
						if (position.isDeleted() || contain(removedPositionsList, position)) {
							document.removePosition(positionCategory, position);
							position= null;
						}
					}

					// b) find the next Position from the added list
					if (addedPosition == null && j < m) {
						addedPosition= addedPositions[j++];
						document.addPosition(positionCategory, addedPosition);
					}

					// c) merge: add the next of position/addedPosition with the lower offset
					if (position != null) {
						if (addedPosition != null)
							if (position.getOffset() <= addedPosition.getOffset()) {
								newPositions.add(position);
								position= null;
							} else {
								newPositions.add(addedPosition);
								addedPosition= null;
							}
						else {
							newPositions.add(position);
							position= null;
						}
					} else if (addedPosition != null) {
						newPositions.add(addedPosition);
						addedPosition= null;
					}
				}
				fPositions= newPositions;
			}
		} catch (BadPositionCategoryException e) {
			// Should not happen
			JavaPlugin.log(e);
		} catch (BadLocationException e) {
			// Should not happen
			JavaPlugin.log(e);
		}
//		checkOrdering("new positions: ", fPositions); //$NON-NLS-1$

		if (textPresentation != null)
			fSourceViewer.changeTextPresentation(textPresentation, false);
		else
			fSourceViewer.invalidateTextPresentation();
	}

//	private void checkOrdering(String s, List positions) {
//		Position previous= null;
//		for (int i= 0, n= positions.size(); i < n; i++) {
//			Position current= (Position) positions.get(i);
//			if (previous != null && previous.getOffset() + previous.getLength() > current.getOffset())
//				return;
//		}
//	}

	/**
	 * Returns true iff the positions contain the position.
	 * @param positions the positions, must be ordered by offset but may overlap
	 * @param position the position
	 * @return true iff the positions contain the position
	 */
	private boolean contain(List<? extends Position> positions, Position position) {
		return indexOf(positions, position) != -1;
	}

	/**
	 * Returns index of the position in the positions, -1 if not found.
	 * @param positions the positions, must be ordered by offset but may overlap
	 * @param position the position
	 * @return the index
	 */
	private int indexOf(List<? extends Position> positions, Position position) {
		int index= computeIndexAtOffset(positions, position.getOffset());
		int size= positions.size();
		while (index < size) {
			if (positions.get(index) == position)
				return index;
			index++;
		}
		return -1;
	}

	/**
	 * Insert the given position in fPositions, s.t. the offsets remain in linear order.
	 *
	 * @param position The position for insertion
	 */
	private void insertPosition(Position position) {
		int i= computeIndexAfterOffset(fPositions, position.getOffset());
		fPositions.add(i, position);
	}

	/**
	 * Returns the index of the first position with an offset greater than the given offset.
	 *
	 * @param positions the positions, must be ordered by offset and must not overlap
	 * @param offset the offset
	 * @return the index of the last position with an offset greater than the given offset
	 */
	private int computeIndexAfterOffset(List<Position> positions, int offset) {
		int i= -1;
		int j= positions.size();
		while (j - i > 1) {
			int k= (i + j) >> 1;
			Position position= positions.get(k);
			if (position.getOffset() > offset)
				j= k;
			else
				i= k;
		}
		return j;
	}

	/**
	 * Returns the index of the first position with an offset equal or greater than the given offset.
	 *
	 * @param positions the positions, must be ordered by offset and must not overlap
	 * @param offset the offset
	 * @return the index of the last position with an offset equal or greater than the given offset
	 */
	private int computeIndexAtOffset(List<? extends Position> positions, int offset) {
		int i= -1;
		int j= positions.size();
		while (j - i > 1) {
			int k= (i + j) >> 1;
			Position position= positions.get(k);
			if (position.getOffset() >= offset)
				j= k;
			else
				i= k;
		}
		return j;
	}

	/*
	 * @see org.eclipse.jface.text.ITextPresentationListener#applyTextPresentation(org.eclipse.jface.text.TextPresentation)
	 */
	public void applyTextPresentation(TextPresentation textPresentation) {
		IRegion region= textPresentation.getExtent();
		int i= computeIndexAtOffset(fPositions, region.getOffset()), n= computeIndexAtOffset(fPositions, region.getOffset() + region.getLength());
		if (n - i > 2) {
			List


text:
namespace JustQuest.UI.DataModels
{
    internal interface IPageViewModel
    {
        string Title { get; }

        IContentViewModel ContentViewModel { get; set; }
    }
}


text:
set -ex

VENV=${1:-"functional"}

GATE_DEST=$BASE/new
NEUTRONCLIENT_PATH=$GATE_DEST/python-neutronclient
GATE_HOOKS=$NEUTRONCLIENT_PATH/neutronclient/tests/functional/hooks
DEVSTACK_PATH=$GATE_DEST/devstack

# Inject config from hook into localrc
function load_rc_hook {
    local hook="$1"
    config=$(cat $GATE_HOOKS/$hook)
    export DEVSTACK_LOCAL_CONFIG+="
# generated from hook '$hook'
${config}
"
}

if [ "$VENV" == "functional" ]
then
    load_rc_hook fwaas
fi

if [ "$VENV" == "functional-adv-svcs" ]
then
    export DEVSTACK_LOCAL_CONFIG="enable_plugin neutron-vpnaas git://git.openstack.org/openstack/neutron-vpnaas"
fi

$BASE/new/devstack-gate/devstack-vm-gate.sh


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../base/Page');
import Response = require('../../../http/response');
import V1 = require('../V1');
import { SerializableClass } from '../../../interfaces';

type UserStateType = 'active'|'deactivated';

/**
 * Initialize the UserList
 *
 * PLEASE NOTE that this class contains beta products that are subject to change.
 * Use them with caution.
 *
 * @param version - Version of the resource
 */
declare function UserList(version: V1): UserListInstance;

/**
 * Options to pass to update
 *
 * @property avatar - The avatar URL which will be shown in Frontline application
 * @property friendlyName - The string that you assigned to describe the User
 * @property isAvailable - Whether the User is available for new conversations
 * @property state - Current state of this user
 */
interface UserInstanceUpdateOptions {
  avatar?: string;
  friendlyName?: string;
  isAvailable?: boolean;
  state?: UserStateType;
}

interface UserListInstance {
  /**
   * @param sid - sid of instance
   */
  (sid: string): UserContext;
  /**
   * Constructs a user
   *
   * @param sid - The SID of the User resource to fetch
   */
  get(sid: string): UserContext;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

interface UserPayload extends UserResource, Page.TwilioResponsePayload {
}

interface UserResource {
  avatar: string;
  friendly_name: string;
  identity: string;
  is_available: boolean;
  sid: string;
  state: UserStateType;
  url: string;
}

interface UserSolution {
}

declare class UserContext {
  /**
   * Initialize the UserContext
   *
   * PLEASE NOTE that this class contains beta products that are subject to change.
   * Use them with caution.
   *
   * @param version - Version of the resource
   * @param sid - The SID of the User resource to fetch
   */
  constructor(version: V1, sid: string);

  /**
   * fetch a UserInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
  /**
   * update a UserInstance
   *
   * @param callback - Callback to handle processed record
   */
  update(callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance>;
  /**
   * update a UserInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  update(opts?: UserInstanceUpdateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance>;
}

declare class UserInstance extends SerializableClass {
  /**
   * Initialize the UserContext
   *
   * PLEASE NOTE that this class contains beta products that are subject to change.
   * Use them with caution.
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param sid - The SID of the User resource to fetch
   */
  constructor(version: V1, payload: UserPayload, sid: string);

  private _proxy: UserContext;
  avatar: string;
  /**
   * fetch a UserInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance>;
  friendlyName: string;
  identity: string;
  isAvailable: boolean;
  sid: string;
  state: UserStateType;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
  /**
   * update a UserInstance
   *
   * @param callback - Callback to handle processed record
   */
  update(callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance>;
  /**
   * update a UserInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  update(opts?: UserInstanceUpdateOptions, callback?: (error: Error | null, items: UserInstance) => any): Promise<UserInstance>;
  url: string;
}

declare class UserPage extends Page<V1, UserPayload, UserResource, UserInstance> {
  /**
   * Initialize the UserPage
   *
   * PLEASE NOTE that this class contains beta products that are subject to change.
   * Use them with caution.
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V1, response: Response<string>, solution: UserSolution);

  /**
   * Build an instance of UserInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: UserPayload): UserInstance;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

export { UserContext, UserInstance, UserInstanceUpdateOptions, UserList, UserListInstance, UserPage, UserPayload, UserResource, UserSolution, UserStateType }


text:
package com.nicktardif.seniorproject.goshnaforairlines.ApiResponses;

import com.nicktardif.seniorproject.goshnaforairlines.Gate;

import java.util.List;

/**
 * Created by tick on 4/7/15.
 */
public class GateResponse {
    public List<Gate> gates;

    public GateResponse(List<Gate> gates) {
        this.gates = gates;
    }

    @Override
    public String toString() {
        return "GateResponse{" +
                "gates=" + gates +
                '}';
    }
}


text:
#region License

#endregion License

using System;
using System.IO;
using Tao.DevIl;
using Tao.OpenGl;

namespace Microsoft.Xna.Framework.Graphics
{

    public abstract class Texture : GraphicsResource
    {
        //public static bool operator !=(Texture left, Texture right) { throw new NotImplementedException(); }

        //public static bool operator ==(Texture left, Texture right) { throw new NotImplementedException(); }

        public int LevelCount { get { throw new NotImplementedException(); } }

        public int LevelOfDetail { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } }

        protected override void Dispose(bool disposing)
        {
            throw new NotImplementedException();
        }

        public static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream) { throw new NotImplementedException(); }

        public static Texture FromFile(GraphicsDevice graphicsDevice, string filename) { throw new NotImplementedException(); }

        public static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes) { throw new NotImplementedException(); }

        public static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream, TextureCreationParameters creationParameters) { throw new NotImplementedException(); }

        public static Texture FromFile(GraphicsDevice graphicsDevice, string filename, TextureCreationParameters creationParameters) {
            TextureInformation texinfo = GetTextureInformation(filename);
            if (creationParameters.Width == 0) creationParameters.Width = texinfo.Width;
            if (creationParameters.Height == 0) creationParameters.Height = texinfo.Height;
            if (creationParameters.Depth == 0) creationParameters.Depth = texinfo.Depth;
            if (texinfo.ResourceType == ResourceType.Texture2D)
            {
                int ImgID;
                Il.ilGenImages(1, out ImgID);
                Il.ilBindImage(ImgID);
                Il.ilLoadImage(filename);
                int width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
                int height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);
                int depth = Il.ilGetInteger(Il.IL_IMAGE_DEPTH);
                int size = Il.ilGetInteger(Il.IL_IMAGE_SIZE_OF_DATA);
                Texture2D tex = new Texture2D(graphicsDevice, creationParameters.Width, creationParameters.Height, creationParameters.Depth, TextureUsage.None, SurfaceFormat.Rgb32);

                Gl.glBindTexture(Gl.GL_TEXTURE_2D, tex.textureId);
                Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Il.ilGetInteger(Il.IL_IMAGE_BYTES_PER_PIXEL), creationParameters.Width, creationParameters.Height, 0, Gl.GL_RGBA, Gl.GL_UNSIGNED_BYTE, Il.ilGetData());

                Il.ilBindImage(0);
                return tex;
            }
            else if (texinfo.ResourceType == ResourceType.Texture3D) { throw new NotImplementedException(); }
            else if (texinfo.ResourceType == ResourceType.Texture3DVolume) { throw new NotImplementedException(); } //FIXME: Should we handle this here too?
            else if (texinfo.ResourceType == ResourceType.TextureCube) { throw new NotImplementedException(); }
            else return null;
        }

        public static Texture FromFile(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes, TextureCreationParameters creationParameters) { throw new NotImplementedException(); }

        public static Texture FromFile(GraphicsDevice graphicsDevice, string filename, int width, int height, int depth) { throw new NotImplementedException(); }

        public void GenerateMipMaps(TextureFilter filterType) { throw new NotImplementedException(); }

        public static TextureCreationParameters GetCreationParameters(GraphicsDevice graphicsDevice, Stream textureStream) { throw new NotImplementedException(); }

        public static TextureCreationParameters GetCreationParameters(GraphicsDevice graphicsDevice, string filename) { throw new NotImplementedException(); }

        public static TextureCreationParameters GetCreationParameters(GraphicsDevice graphicsDevice, Stream textureStream, int numberBytes) { throw new NotImplementedException(); }

        public override int GetHashCode() { throw new NotImplementedException(); }

        public static TextureInformation GetTextureInformation(Stream textureStream) { throw new NotImplementedException(); }

        public static TextureInformation GetTextureInformation(string filename) {
            FileStream FS = null;
            try
            {
                FS = File.OpenRead(filename);
            }
            finally
            {
                if (FS != null) FS.Close();
            }
            TextureInformation TexInfo = new TextureInformation();
            TexInfo.Depth = Il.ilGetInteger(Il.IL_IMAGE_DEPTH);
            TexInfo.Format = SurfaceFormat.Color; //TODO: Set properly.
            TexInfo.Height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);
            TexInfo.imageFormat = ILimageformat2XNAimageformat(Il.ilGetInteger(Il.IL_IMAGE_FORMAT));
            TexInfo.resourcetype = ResourceType.Texture2D; //TODO: Find out how to detect and set properly.
            TexInfo.Width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
            return TexInfo;
        }

        private static ImageFileFormat ILimageformat2XNAimageformat(int ILFormat)
        {
            throw new NotImplementedException();
        }

        public static TextureInformation GetTextureInformation(Stream textureStream, int numberBytes) { throw new NotImplementedException(); }

        public void Save(string filename, ImageFileFormat format) { throw new NotImplementedException(); }

    }
}


text:
package uk.co.real_logic.aeron.common;

import uk.co.real_logic.agrona.DirectBuffer;
import uk.co.real_logic.agrona.MutableDirectBuffer;
import uk.co.real_logic.agrona.concurrent.UnsafeBuffer;
import uk.co.real_logic.agrona.BitUtil;

import java.util.Arrays;

/**
 * Builder for appending buffers that grows capacity as necessary.
 */
public class BufferBuilder
{
    public static final int INITIAL_CAPACITY = 4096;

    private final MutableDirectBuffer mutableDirectBuffer;

    private byte[] buffer;
    private int limit = 0;
    private int capacity;

    /**
     * Construct a buffer builder with a default growth increment of {@link #INITIAL_CAPACITY}
     */
    public BufferBuilder()
    {
        this(INITIAL_CAPACITY);
    }

    /**
     * Construct a buffer builder with an initial capacity that will be rounded up to the nearest power of 2.
     *
     * @param initialCapacity at which the capacity will start.
     */
    public BufferBuilder(final int initialCapacity)
    {
        capacity = BitUtil.findNextPositivePowerOfTwo(initialCapacity);
        buffer = new byte[capacity];
        mutableDirectBuffer = new UnsafeBuffer(buffer);
    }

    /**
     * The current capacity of the buffer.
     *
     * @return the current capacity of the buffer.
     */
    public int capacity()
    {
        return capacity;
    }

    /**
     * The current limit of the buffer that has been used by append operations.
     *
     * @return the current limit of the buffer that has been used by append operations.
     */
    public int limit()
    {
        return limit;
    }

    /**
     * The {@link MutableDirectBuffer} that encapsulates the internal buffer.
     *
     * @return the {@link MutableDirectBuffer} that encapsulates the internal buffer.
     */
    public MutableDirectBuffer buffer()
    {
        return mutableDirectBuffer;
    }

    /**
     * Reset the builder to restart append operations. The internal buffer does not shrink.
     *
     * @return the builder for fluent API usage.
     */
    public BufferBuilder reset()
    {
        limit = 0;
        return this;
    }

    /**
     * Compact the buffer to reclaim unused space above the limit.
     *
     * @return the builder for fluent API usage.
     */
    public BufferBuilder compact()
    {
        capacity = Math.max(INITIAL_CAPACITY, BitUtil.findNextPositivePowerOfTwo(limit));
        buffer = Arrays.copyOf(buffer, capacity);
        mutableDirectBuffer.wrap(buffer);

        return this;
    }

    /**
     * Append a source buffer to the end of the internal buffer, resizing the internal buffer as required.
     *
     * @param srcBuffer from which to copy.
     * @param srcOffset in the source buffer from which to copy.
     * @param length in bytes to copy from the source buffer.
     * @return the builder for fluent API usage.
     */
    public BufferBuilder append(final DirectBuffer srcBuffer, final int srcOffset, final int length)
    {
        ensureCapacity(length);

        srcBuffer.getBytes(srcOffset, buffer, limit, length);
        limit += length;

        return this;
    }

    private void ensureCapacity(final int additionalCapacity)
    {
        final int requiredCapacity = limit + additionalCapacity;

        if (requiredCapacity < 0)
        {
            final String s = String.format("Insufficient capacity: limit=%d additional=%d", limit, additionalCapacity);
            throw new IllegalStateException(s);
        }

        if (requiredCapacity > capacity)
        {
            final int newCapacity = findSuitableCapacity(capacity, requiredCapacity);
            final byte[] newBuffer = Arrays.copyOf(buffer, newCapacity);

            capacity = newCapacity;
            buffer = newBuffer;
            mutableDirectBuffer.wrap(newBuffer);
        }
    }

    private static int findSuitableCapacity(int capacity, final int requiredCapacity)
    {
        do
        {
            capacity <<= 1;
        }
        while (capacity < requiredCapacity);

        return capacity;
    }
}


text:
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Mvp.PresenterBinding
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;

    using Narvalo;
    using Narvalo.Mvp.Resolvers;

    public sealed partial class AttributedPresenterDiscoveryStrategy : IPresenterDiscoveryStrategy
    {
        private readonly IPresenterBindingAttributesResolver _attributesResolver;

        public AttributedPresenterDiscoveryStrategy()
            : this(new PresenterBindingAttributesResolver())
        { }

        public AttributedPresenterDiscoveryStrategy(
            IPresenterBindingAttributesResolver attributesResolver)
            : this(attributesResolver, true)
        { }

        public AttributedPresenterDiscoveryStrategy(
            IPresenterBindingAttributesResolver attributesResolver,
            bool enableCache)
        {
            Require.NotNull(attributesResolver, nameof(attributesResolver));

            _attributesResolver = enableCache
                 ? new CachedPresenterBindingAttributesResolver(attributesResolver)
                 : attributesResolver;
        }

        public PresenterDiscoveryResult FindBindings(
            IEnumerable<object> hosts,
            IEnumerable<IView> views)
        {
            Require.NotNull(hosts, nameof(hosts));
            Require.NotNull(views, nameof(views));

            var hostAttributes = hosts.Except(views.OfType<Object>())
                .SelectMany(_ => _attributesResolver.Resolve(_.GetType()))
                .ToList();

            var boundViews = new List<IView>();
            var bindings = new List<PresenterBindingParameter>();

            var pendingViews = views;

            while (pendingViews.Any())
            {
                var view = pendingViews.First();
                var viewType = view.GetType();

                var bindingsThisRound
                    = (from attr in
                           _attributesResolver.Resolve(viewType).Concat(hostAttributes)
                       where attr.ViewType.IsAssignableFrom(viewType)
                       select new PresenterBindingParameter(
                           attr.PresenterType,
                           attr.ViewType,
                           attr.BindingMode,
                           GetViewsToBind(attr, view, pendingViews))).ToList();

                bindings.AddRange(bindingsThisRound);

                var boundViewsThisRound = bindingsThisRound.SelectMany(_ => _.Views).ToList();

                boundViews.AddRange(boundViewsThisRound);

                // In case "boundViewsThisRound" is empty, we always add the currently
                // inspected view to the list of views to remove.
                pendingViews = pendingViews.Except(boundViewsThisRound.Concat(new[] { view }));
            }

            return new PresenterDiscoveryResult(boundViews, bindings);
        }

        [SuppressMessage("Microsoft.Contracts", "Requires-7-207", Justification = "[Intentionally] Requires unreachable but CCCheck still proves no case is forgotten.")]
        private static IEnumerable<IView> GetViewsToBind(
            PresenterBindingAttribute attribute,
            IView view,
            IEnumerable<IView> pendingViews)
        {
            Debug.Assert(attribute != null);
            Debug.Assert(view != null);
            Debug.Assert(pendingViews != null);

            Trace.TraceInformation(
                "[AttributeBasedPresenterDiscoveryStrategy] Found presenter '{0}' for view '{1}', origin='{2}', binding mode='{3}'.",
                attribute.PresenterType.FullName,
                attribute.ViewType?.FullName,
                attribute.Origin?.FullName,
                attribute.BindingMode.ToString());

            switch (attribute.BindingMode)
            {
                case PresenterBindingMode.Default:
                    return new[] { view };

                case PresenterBindingMode.SharedPresenter:
                    return pendingViews.Where(_ => attribute.ViewType?.IsInstanceOfType(_) ?? false);

                default:
                    throw new ControlFlowException();
            }
        }
    }
}


text:
package edu.ncsu.monopoly;

public class FreeParkingCell extends Cell {

	public FreeParkingCell() {
		setName("Free Parking");
	}

	public void playAction() {
		return;
	}
}


text:
require 'spec_helper'

describe 'User Snippets' do
  let(:author) { create(:user) }
  let!(:public_snippet) { create(:personal_snippet, :public, author: author, title: "This is a public snippet") }
  let!(:internal_snippet) { create(:personal_snippet, :internal, author: author, title: "This is an internal snippet") }
  let!(:private_snippet) { create(:personal_snippet, :private, author: author, title: "This is a private snippet") }

  before do
    sign_in author
    visit dashboard_snippets_path
  end

  it 'View all of my snippets' do
    expect(page).to have_content(public_snippet.title)
    expect(page).to have_content(internal_snippet.title)
    expect(page).to have_content(private_snippet.title)
  end

  it 'View my public snippets' do
    page.within('.snippet-scope-menu') do
      click_link "Public"
    end

    expect(page).to have_content(public_snippet.title)
    expect(page).not_to have_content(internal_snippet.title)
    expect(page).not_to have_content(private_snippet.title)
  end

  it 'View my internal snippets' do
    page.within('.snippet-scope-menu') do
      click_link "Internal"
    end

    expect(page).not_to have_content(public_snippet.title)
    expect(page).to have_content(internal_snippet.title)
    expect(page).not_to have_content(private_snippet.title)
  end

  it 'View my private snippets' do
    page.within('.snippet-scope-menu') do
      click_link "Private"
    end

    expect(page).not_to have_content(public_snippet.title)
    expect(page).not_to have_content(internal_snippet.title)
    expect(page).to have_content(private_snippet.title)
  end
end


text:
package com.iisigroup.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

    @RequestMapping("helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }

}


text:
package edacc.configurator.aac;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import edacc.parameterspace.ParameterConfiguration;
import edacc.api.API;
import edacc.model.ExperimentResult;
import edacc.model.ResultCode;
import edacc.model.StatusCode;

public class SolverConfiguration implements Comparable<SolverConfiguration> {
	/** the parameter configuration of the solver configuration */
	private ParameterConfiguration pConfig;

	/** id of the solver configuration from the DB */
	private int idSolverConfiguration;

	private int incumbentNumber;
	/**
	 * the cost of the configuration with regards to a statistic function and a
	 * metric (cost or runtime);
	 */
	private Double cost;

	private Double dbCost;

	public Double getDbCost() {
		return dbCost;
	}

	/**
	 * total runtime in seconds of all the jobs in the jobs list
	 *
	 */
	private float totalRuntime;

	/** the name of the configuration */
	private String nameRacing, nameSearch;
	protected boolean nameUpdated, wasBest;

	/** List of all jobs that a solver configuration has been executed so far */
	private List<ExperimentResult> jobs;

	private StatisticFunction statFunc;

	protected int numNotStartedJobs, numFinishedJobs, numSuccessfulJobs, numRunningJobs;

	private boolean finished;

	private int number;

	/**
	 * Common initialization
	 */
	private SolverConfiguration() {
		jobs = new LinkedList<ExperimentResult>();
		totalRuntime = 0.f;
	}

	public SolverConfiguration(int idSolverConfiguration, ParameterConfiguration pc, StatisticFunction statFunc) {
		this();

		this.pConfig = pc;
		this.idSolverConfiguration = idSolverConfiguration;
		this.cost = null;
		this.nameRacing = null;
		this.nameSearch = null;
		this.nameUpdated = false;
		this.wasBest = false;
		this.statFunc = statFunc;
		this.incumbentNumber = -1;
		this.finished = false;
		this.number = -1;
	}

	public SolverConfiguration(int idSolverConfiguration, ParameterConfiguration pc, StatisticFunction statFunc, double dbCost) {
		this();
		this.dbCost = dbCost;
		this.pConfig = pc;
		this.idSolverConfiguration = idSolverConfiguration;
		this.cost = null;
		this.nameRacing = null;
		this.nameSearch = null;
		this.nameUpdated = false;
		this.wasBest = false;
		this.statFunc = statFunc;
		this.incumbentNumber = -1;
		this.finished = false;
		this.number = -1;
	}

	public SolverConfiguration(SolverConfiguration sc) {
		this();

		this.pConfig = new ParameterConfiguration(sc.pConfig);
		this.idSolverConfiguration = sc.idSolverConfiguration;
		this.cost = sc.cost;
		this.nameRacing = sc.nameRacing;
		this.nameSearch = sc.nameSearch;
		this.nameUpdated = sc.nameUpdated;
		this.wasBest  = sc.wasBest;
		this.statFunc = sc.statFunc;
		this.incumbentNumber = sc.incumbentNumber;
		this.finished = sc.finished;
		this.number = sc.number;
	}

	public int getIncumbentNumber() {
		return incumbentNumber;
	}

	public void setIncumbentNumber(int incumbentNumber) {
		this.incumbentNumber = incumbentNumber;
	}

	public final ParameterConfiguration getParameterConfiguration() {
		return this.pConfig;
	}

	public final void setParameterConfiguration(ParameterConfiguration pc) {
		this.pConfig = pc;
	}

	public final int getIdSolverConfiguration() {
		return this.idSolverConfiguration;
	}

	public final void setIdSolverConfiguration(int id) {
		this.idSolverConfiguration = id;
	}

	/**
	 * Computes the cost of the solver configuration according to the
	 * statistical function that the solver configuration was initialized. Only
	 * jobs that are finished are taken into considertion; running, unstarted or
	 * crashed jobs are ignored
	 *
	 * @return the cost value with regards to the statistic function
	 */
	public final Double getCost() {
		return statFunc.getCostFunction().calculateCost(jobs);
	}

	/**
	 * Computes the cost of the solver configuration according to the
	 * statistical function that the solver configuration was initialized. Only
	 * jobs that are finished are taken into considertion; running, unstarted or
	 * crashed jobs are ignored
	 *
	 * @return the cost value with regards to the statistic function
	 */
	public final Double getCumulatedCost() {
		return statFunc.getCostFunction().calculateCumulatedCost(jobs);
	}

	public final void setCost(Double cost) {
		this.cost = cost;
	}

	public final String getName() {
		if (nameRacing == null) {
			return nameSearch;
		} else if (nameSearch == null) {
			return nameRacing;
		}
		return nameSearch + " " + nameRacing;
	}

	public final void setNameRacing(String name) {
		this.nameRacing = name;
		this.nameUpdated = true;
	}

	public final void setNameSearch(String name) {
		this.nameSearch = name;
		this.nameUpdated = true;
	}

	public void putJob(ExperimentResult job) {
                if((job != null) && !jobs.contains(job))
                    jobs.add(job);
	}

	/**
	 * Returns the all jobs at the last updateJobs() call.

	 *
	 * @return
	 */
	public List<ExperimentResult> getJobs() {
		LinkedList<ExperimentResult> res = new LinkedList<ExperimentResult>();
		for (ExperimentResult j : jobs) {
			res.add(j);
		}
		return res;
	}

	/**
	 * Returns the running jobs at the last updateJobs() call.

	 * Running jobs means, statusCode equals
	 * StatusCode.RUNNING.
	 *
	 * @return
	 */
	public List<ExperimentResult> getRunningJobs() {
		LinkedList<ExperimentResult> res = new LinkedList<ExperimentResult>();
		for (ExperimentResult j : jobs) {
			if (j.getStatus().equals(StatusCode.RUNNING)) {
				res.add(j);
			}
		}
		return res;
	}

	/**
	 * Returns the number of running jobs at the last updateJobs()
	 * call.

	 * Running jobs means, statusCode equals
	 * StatusCode.RUNNING.
	 *
	 * @return
	 */
	public int getNumRunningJobs() {
		return numRunningJobs;
	}

	/**
	 * Returns the finished jobs at the last updateJobs() call.

	 * Finished jobs means, statusCode is different to
	 * StatusCode.NOT_STARTED and StatusCode.RUNNING.
	 *
	 * @return
	 */
	public List<ExperimentResult> getFinishedJobs() {
		LinkedList<ExperimentResult> res = new LinkedList<ExperimentResult>();
		for (ExperimentResult j : jobs) {
			if (!j.getStatus().equals(StatusCode.NOT_STARTED) && !j.getStatus().equals(StatusCode.RUNNING)) {
				res.add(j);
			}
		}
		return res;
	}

	/**
	 * Returns the finished jobs at the last updateJobs() call.

	 * Finished jobs means, statusCode is different to
	 * StatusCode.NOT_STARTED and StatusCode.RUNNING.
	 *
	 * @return
	 */
	public int getNumFinishedJobs() {
		return numFinishedJobs;
	}

	/**
	 * Returns the not started jobs at the last updateJobs() call.

	 * Not started jobs means, statusCode is equal to
	 * StatusCode.NOT_STARTED.
	 *
	 * @return
	 */
	public List<ExperimentResult> getNotStartedJobs() {
		LinkedList<ExperimentResult> res = new LinkedList<ExperimentResult>();
		for (ExperimentResult j : jobs) {
			if (j.getStatus().equals(StatusCode.NOT_STARTED)) {
				res.add(j);
			}
		}
		return res;
	}

	/**
	 * Returns the number of not started jobs at the last
	 * updateJobs() call.

	 * Not started jobs means, statusCode is equal to
	 * StatusCode.NOT_STARTED.
	 *
	 * @return
	 */
	public int getNumNotStartedJobs() {
		return numNotStartedJobs;
	}

	public int getNumSuccessfulJobs() {
		return numSuccessfulJobs;
	}

	/**
	 * Returns the number of jobs for this solver configuration at the last
	 * updateJobs() call.
	 *
	 * @return
	 */
	public int getJobCount() {
		return jobs.size();
	}

	/**
	 * Updates the locally cached jobs for this solver configuration. It
	 * collects the id's of its own jobs and passes them to the api as a list of
	 * id's getting back the ExperimentResults list for this id's
	 *
	 * @return the cpu time needed since the last updateJobsStatus()-call
	 * @throws Exception
	 */

	protected List<ExperimentResult> updateJobsStatus(API api) throws Exception {
		List<ExperimentResult> res = new LinkedList<ExperimentResult>();
		LinkedList<Integer> ids = new LinkedList<Integer>();
		ArrayList<ExperimentResult> tmp = new ArrayList<ExperimentResult>();
		numRunningJobs = 0;
		numFinishedJobs = 0;
		numSuccessfulJobs = 0;
		numNotStartedJobs = 0;
		totalRuntime = 0.f;
		for (ExperimentResult j : jobs) {
			if (!j.getStatus().equals(StatusCode.NOT_STARTED) && !j.getStatus().equals(StatusCode.RUNNING)) {
				numFinishedJobs++;
				totalRuntime += j.getResultTime();
				if (String.valueOf(j.getResultCode().getResultCode()).startsWith("1")) {
					numSuccessfulJobs++;
				}
				tmp.add(j);
			} else {
				ids.add(j.getId());
			}
		}

		if (!ids.isEmpty()) {
			jobs.clear();
			jobs.addAll(api.getJobsByIDs(ids).values());

			for (ExperimentResult j : jobs) {
				totalRuntime += j.getResultTime();
				if (j.getStatus().equals(StatusCode.RUNNING)) {
					numRunningJobs++;
				}
				if (!j.getStatus().equals(StatusCode.NOT_STARTED) && !j.getStatus().equals(StatusCode.RUNNING)) {
					res.add(j);
					numFinishedJobs++;
				}
				if (String.valueOf(j.getResultCode().getResultCode()).startsWith("1")) {
					numSuccessfulJobs++;
				}
				if (j.getStatus().equals(StatusCode.NOT_STARTED)) {
					numNotStartedJobs++;
				}
			}
			jobs.addAll(tmp);

		}
		return res;
	}

	/**
	 * Returns a list of InstanceIdSeed where each entry satisfies:

	 * * this solver configuration has computed/computes/will compute the
	 * instance-seed-pair

	 * * the other solver configuration did not compute/is not
	 * currently computing/will not compute the instance-seed-pair

	 * * the list contains max. num items

	 * at the last updateJobs() call.

	 * If the list contains less than num items, then there aren't
	 * more instance-seed-pairs which would satisfy the first two assertions.
	 *
	 * @param other
	 * @param num
	 * @return
	 */
	public List<InstanceIdSeed> getInstanceIdSeed(SolverConfiguration other, int num, Random rng) {
		LinkedList<InstanceIdSeed> all = new LinkedList<InstanceIdSeed>();
		HashSet<InstanceIdSeed> ownInstanceIdSeed = new HashSet<InstanceIdSeed>();
		for (ExperimentResult j : jobs) {
			ownInstanceIdSeed.add(new InstanceIdSeed(j.getInstanceId(), j.getSeed()));
		}
		for (ExperimentResult j : other.getFinishedJobs()) {
			InstanceIdSeed tmp = new InstanceIdSeed(j.getInstanceId(), j.getSeed());
			if (!ownInstanceIdSeed.contains(tmp)) {
				all.add(tmp);
			}
		}

		if (all.size() <= num) {
			return all;
		} else {
			LinkedList<InstanceIdSeed> res = new LinkedList<InstanceIdSeed>();
			while (res.size() < num) {
				int index = rng.nextInt(all.size());
				res.add(all.get(index));
				all.remove(index);
			}
			return res;
		}

	}

	   /**
     * Returns a list of InstanceIdSeed where each entry satisfies:

     * * this solver configuration has computed/computes/will compute the
     * instance-seed-pair

     * * the other solver configuration did not compute/is not
     * currently computing/will not compute the instance-seed-pair

     * * the list contains max. num items

     * at the last updateJobs() call.

     * If the list contains less than num items, then there aren't
     * more instance-seed-pairs which would satisfy the first two assertions.
     *
     * @param other
     * @param num
     * @return
     */
    public List<InstanceIdSeed> getInstanceIdSeedAggressive(SolverConfiguration other, int num, Random rng) {
        LinkedList<InstanceIdSeed> allUnpenalized = new LinkedList<InstanceIdSeed>();
        LinkedList<InstanceIdSeed> allPenalized = new LinkedList<InstanceIdSeed>();
        HashSet<InstanceIdSeed> ownInstanceIdSeed = new HashSet<InstanceIdSeed>();
        List<ExperimentResult> otherFinishedJobs = other.getFinishedJobs();
        Collections.sort(otherFinishedJobs, new Comparator<ExperimentResult>() {
            @Override
            public int compare(ExperimentResult o1, ExperimentResult o2) {
                double y1 = statFunc.getCostFunction().singleCost(o1);
                double y2 = statFunc.getCostFunction().singleCost(o2);
                return statFunc.isMinimize() ? Double.compare(y1, y2) : Double.compare(y2, y1);
            }
        });
        for (ExperimentResult j : jobs) {
            ownInstanceIdSeed.add(new InstanceIdSeed(j.getInstanceId(), j.getSeed()));
        }
        for (ExperimentResult j : otherFinishedJobs) {
            InstanceIdSeed tmp = new InstanceIdSeed(j.getInstanceId(), j.getSeed());
            if (!ownInstanceIdSeed.contains(tmp)) {
                if (statFunc.getCostFunction().isSingleCostPenalized(j)) {
                    allPenalized.add(tmp);
                } else {
                    allUnpenalized.add(tmp);
                }
            }
        }

        if (allUnpenalized.size() + allPenalized.size() <= num) {
            List<InstanceIdSeed> all = new LinkedList<InstanceIdSeed>();
            all.addAll(allUnpenalized);
            all.addAll(allPenalized);
            return all;
        } else {
            LinkedList<InstanceIdSeed> res = new LinkedList<InstanceIdSeed>();
            // first take unpenalized jobs
            while (res.size() < num && !allUnpenalized.isEmpty()) {
                int index = rng.nextInt(allUnpenalized.size());
                res.add(allUnpenalized.get(index));
                allUnpenalized.remove(index);
            }
            // then penalized jobs if necessary
            while (res.size() < num) {
                int index = rng.nextInt(allPenalized.size());
                res.add(allPenalized.get(index));
                allPenalized.remove(index);
            }
            return res;
        }

    }

	public Float getTotalRuntime() {
		return totalRuntime;
	}

	public boolean isFinished() {
		return finished;
	}

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

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	@Override
	public int compareTo(SolverConfiguration other) {
		HashMap<InstanceIdSeed, ExperimentResult> ownJobs = new HashMap<InstanceIdSeed, ExperimentResult>();
		for (ExperimentResult job : getFinishedJobs()) {
			ownJobs.put(new InstanceIdSeed(job.getInstanceId(), job.getSeed()), job);
		}
		List<ExperimentResult> myJobs = new LinkedList<ExperimentResult>();
		List<ExperimentResult> otherJobs = new LinkedList<ExperimentResult>();
		for (ExperimentResult job : other.getFinishedJobs()) {
			InstanceIdSeed tmp = new InstanceIdSeed(job.getInstanceId(), job.getSeed());
			ExperimentResult ownJob;
			if ((ownJob = ownJobs.get(tmp)) != null) {
				myJobs.add(ownJob);
				otherJobs.add(job);
			}
		}
		return statFunc.compare(myJobs, otherJobs);
	}

	protected void jobReset(ExperimentResult er) {
		if (er.getStatus().equals(StatusCode.RUNNING)) {
			numRunningJobs--;
		}
		if (!er.getStatus().equals(StatusCode.NOT_STARTED) && !er.getStatus().equals(StatusCode.RUNNING)) {
			numFinishedJobs--;
		}
		if (String.valueOf(er.getResultCode().getResultCode()).startsWith("1")) {
			numSuccessfulJobs--;
		}
		if (!er.getStatus().equals(StatusCode.NOT_STARTED)) {
			numNotStartedJobs++;
		}
		er.setStatus(StatusCode.NOT_STARTED);
		er.setResultCode(ResultCode.UNKNOWN);
	}
}


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

$lang = array
(
	'general_error' => 'Une erreur est survenue lors de l\'envoi du message.'
);


text:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {DummyComponent} from "./dummy.component";

const Dummyroutes: Routes = [
    {path:'',component:DummyComponent,

    },
];

@NgModule({
    imports: [RouterModule.forChild(Dummyroutes)],
    exports: [RouterModule]
})
export class DummyRoutingModule { }


text:
'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');

var layoutAttributes = require('./layout_attributes');
var handleTickValueDefaults = require('./tick_value_defaults');
var handleTickMarkDefaults = require('./tick_mark_defaults');
var handleTickLabelDefaults = require('./tick_label_defaults');
var handleCategoryOrderDefaults = require('./category_order_defaults');
var handleLineGridDefaults = require('./line_grid_defaults');
var setConvert = require('./set_convert');

/**
 * options: object containing:
 *
 *  letter: 'x' or 'y'
 *  title: name of the axis (ie 'Colorbar') to go in default title
 *  font: the default font to inherit
 *  outerTicks: boolean, should ticks default to outside?
 *  showGrid: boolean, should gridlines be shown by default?
 *  noHover: boolean, this axis doesn't support hover effects?
 *  noTickson: boolean, this axis doesn't support 'tickson'
 *  data: the plot data, used to manage categories
 *  bgColor: the plot background color, to calculate default gridline colors
 */
module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
    var letter = options.letter;
    var font = options.font || {};
    var splomStash = options.splomStash || {};

    var visible = coerce('visible', !options.cheateronly);

    var axType = containerOut.type;

    if(axType === 'date') {
        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
    }

    setConvert(containerOut, layoutOut);

    var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));
    if(autoRange && (axType === 'linear' || axType === '-')) coerce('rangemode');

    coerce('range');
    containerOut.cleanRange();

    handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);

    if(axType !== 'category' && !options.noHover) coerce('hoverformat');

    if(!visible) return containerOut;

    var dfltColor = coerce('color');
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    // Compare to dflt rather than to containerIn, so we can provide color via
    // template too.
    var dfltFontColor = (dfltColor !== layoutAttributes.color.dflt) ? dfltColor : font.color;
    // try to get default title from splom trace, fallback to graph-wide value
    var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter];

    coerce('title.text', dfltTitle);
    Lib.coerceFont(coerce, 'title.font', {
        family: font.family,
        size: Math.round(font.size * 1.2),
        color: dfltFontColor
    });

    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
    handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
    handleTickMarkDefaults(containerIn, containerOut, coerce, options);
    handleLineGridDefaults(containerIn, containerOut, coerce, {
        dfltColor: dfltColor,
        bgColor: options.bgColor,
        showGrid: options.showGrid,
        attributes: layoutAttributes
    });

    if(containerOut.showline || containerOut.ticks) coerce('mirror');

    if(options.automargin) coerce('automargin');

    var isMultiCategory = containerOut.type === 'multicategory';

    if(!options.noTickson &&
        (containerOut.type === 'category' || isMultiCategory) &&
        (containerOut.ticks || containerOut.showgrid)
    ) {
        var ticksonDflt;
        if(isMultiCategory) ticksonDflt = 'boundaries';
        coerce('tickson', ticksonDflt);
    }

    if(isMultiCategory) {
        var showDividers = coerce('showdividers');
        if(showDividers) {
            coerce('dividercolor');
            coerce('dividerwidth');
        }
    }

    return containerOut;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 日历定义的一些尺寸 -->
    <dimen name="text_size_day">14sp</dimen>
    <dimen name="text_size_tag">12sp</dimen>
    <dimen name="text_size_month">16sp</dimen>
    <dimen name="text_size_day_name">10sp</dimen>
    <dimen name="header_month_height">50dip</dimen>
    <dimen name="selected_day_radius">16dip</dimen>
    <dimen name="calendar_height">270dip</dimen>
</resources>


text:
class CreateQuestions < ActiveRecord::Migration
  def change
    create_table :questions do |t|
      t.string :summary
      t.text :body

      t.timestamps
    end
  end
end


text:
package com.veridu.idos.endpoints;

import com.google.gson.JsonObject;
import com.veridu.idos.exceptions.SDKException;
import com.veridu.idos.utils.IdOSAuthType;

import java.util.HashMap;

public class ProfileProcesses extends AbstractEndpoint {
    /**
     * Class Constructor
     *
     * @param credentials
     * @param baseURL
     * @param doNotCheckSSL
     */
    public ProfileProcesses(HashMap<String, String> credentials, String baseURL, boolean doNotCheckSSL) {
        super(credentials, IdOSAuthType.HANDLER, baseURL, doNotCheckSSL);
    }

    /**
     * Lists all profiles processes related to the given user
     *
     * @param username
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject listAll(String username) throws SDKException {
        return this.fetch("GET", "profiles/" + username + "/processes");
    }

    /**
     * Retrieves an process given its process id
     *
     * @param username
     * @param processId
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject getOne(String username, int processId) throws SDKException {
        return this.fetch("GET", "profiles/" + username + "/processes/" + processId);
    }
}


text:
#=============================================================================
# Copyright 2009 Kitware, Inc.
# Copyright 2006 Tristan Carel
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
#  License text for the above reference.)

FIND_PROGRAM(FLEX_EXECUTABLE flex DOC "path to the flex executable")
MARK_AS_ADVANCED(FLEX_EXECUTABLE)

FIND_LIBRARY(FL_LIBRARY NAMES fl
  DOC "path to the fl library")
MARK_AS_ADVANCED(FL_LIBRARY)
SET(FLEX_LIBRARIES ${FL_LIBRARY})

IF(FLEX_EXECUTABLE)

  EXECUTE_PROCESS(COMMAND ${FLEX_EXECUTABLE} --version
    OUTPUT_VARIABLE FLEX_version_output
    ERROR_VARIABLE FLEX_version_error
    RESULT_VARIABLE FLEX_version_result
    OUTPUT_STRIP_TRAILING_WHITESPACE)
  IF(NOT ${FLEX_version_result} EQUAL 0)
    IF(FLEX_FIND_REQUIRED)
      MESSAGE(SEND_ERROR "Command \"${FLEX_EXECUTABLE} --version\" failed with output:\n${FLEX_version_output}\n${FLEX_version_error}")
    ELSE()
      MESSAGE("Command \"${FLEX_EXECUTABLE} --version\" failed with output:\n${FLEX_version_output}\n${FLEX_version_error}\nFLEX_VERSION will not be available")
    ENDIF()
  ELSE()
    STRING(REGEX REPLACE "^flex (.*)$" "\\1"
      FLEX_VERSION "${FLEX_version_output}")
  ENDIF()

  #============================================================
  # FLEX_TARGET (public macro)
  #============================================================
  #
  MACRO(FLEX_TARGET Name Input Output)
    SET(FLEX_TARGET_usage "FLEX_TARGET(<Name> <Input> <Output> [COMPILE_FLAGS <string>]")
    IF(${ARGC} GREATER 3)
      IF(${ARGC} EQUAL 5)
        IF("${ARGV3}" STREQUAL "COMPILE_FLAGS")
          SET(FLEX_EXECUTABLE_opts  "${ARGV4}")
          SEPARATE_ARGUMENTS(FLEX_EXECUTABLE_opts)
        ELSE()
          MESSAGE(SEND_ERROR ${FLEX_TARGET_usage})
        ENDIF()
      ELSE()
        MESSAGE(SEND_ERROR ${FLEX_TARGET_usage})
      ENDIF()
    ENDIF()

    ADD_CUSTOM_COMMAND(OUTPUT ${Output}
      COMMAND ${FLEX_EXECUTABLE}
      ARGS ${FLEX_EXECUTABLE_opts} -o${Output} ${Input}
      DEPENDS ${Input}
      COMMENT "[FLEX][${Name}] Building scanner with flex ${FLEX_VERSION}"
      WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

    SET(FLEX_${Name}_DEFINED TRUE)
    SET(FLEX_${Name}_OUTPUTS ${Output})
    SET(FLEX_${Name}_INPUT ${Input})
    SET(FLEX_${Name}_COMPILE_FLAGS ${FLEX_EXECUTABLE_opts})
  ENDMACRO(FLEX_TARGET)
  #============================================================

  #============================================================
  # ADD_FLEX_BISON_DEPENDENCY (public macro)
  #============================================================
  #
  MACRO(ADD_FLEX_BISON_DEPENDENCY FlexTarget BisonTarget)

    IF(NOT FLEX_${FlexTarget}_OUTPUTS)
      MESSAGE(SEND_ERROR "Flex target `${FlexTarget}' does not exists.")
    ENDIF()

    IF(NOT BISON_${BisonTarget}_OUTPUT_HEADER)
      MESSAGE(SEND_ERROR "Bison target `${BisonTarget}' does not exists.")
    ENDIF()

    SET_SOURCE_FILES_PROPERTIES(${FLEX_${FlexTarget}_OUTPUTS}
      PROPERTIES OBJECT_DEPENDS ${BISON_${BisonTarget}_OUTPUT_HEADER})
  ENDMACRO(ADD_FLEX_BISON_DEPENDENCY)
  #============================================================

ENDIF(FLEX_EXECUTABLE)

INCLUDE("${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake")
FIND_PACKAGE_HANDLE_STANDARD_ARGS(FLEX REQUIRED_VARS FLEX_EXECUTABLE
                                       VERSION_VAR FLEX_VERSION)

# FindFLEX.cmake ends here


text:
import unittest
from datetime import datetime
from mock import Mock

from airflow.models import DAG, BaseOperator
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.deps.prev_dagrun_dep import PrevDagrunDep
from airflow.utils.state import State

class PrevDagrunDepTest(unittest.TestCase):

    def _get_task(self, **kwargs):
        return BaseOperator(task_id='test_task', dag=DAG('test_dag'), **kwargs)

    def test_not_depends_on_past(self):
        """
        If depends on past isn't set in the task then the previous dagrun should be
        ignored, even though there is no previous_ti which would normally fail the dep
        """
        task = self._get_task(depends_on_past=False,
                              start_date=datetime(2016, 1, 1),
                              wait_for_downstream=False)
        prev_ti = Mock(task=task, state=State.SUCCESS,
                       are_dependents_done=Mock(return_value=True),
                       execution_date=datetime(2016, 1, 2))
        ti = Mock(task=task, previous_ti=prev_ti,
                  execution_date=datetime(2016, 1, 3))
        dep_context = DepContext(ignore_depends_on_past=False)

        self.assertTrue(PrevDagrunDep().is_met(ti=ti, dep_context=dep_context))

    def test_context_ignore_depends_on_past(self):
        """
        If the context overrides depends_on_past then the dep should be met,
        even though there is no previous_ti which would normally fail the dep
        """
        task = self._get_task(depends_on_past=True,
                              start_date=datetime(2016, 1, 1),
                              wait_for_downstream=False)
        prev_ti = Mock(task=task, state=State.SUCCESS,
                       are_dependents_done=Mock(return_value=True),
                       execution_date=datetime(2016, 1, 2))
        ti = Mock(task=task, previous_ti=prev_ti,
                  execution_date=datetime(2016, 1, 3))
        dep_context = DepContext(ignore_depends_on_past=True)

        self.assertTrue(PrevDagrunDep().is_met(ti=ti, dep_context=dep_context))

    def test_first_task_run(self):
        """
        The first task run for a TI should pass since it has no previous dagrun.
        """
        task = self._get_task(depends_on_past=True,
                              start_date=datetime(2016, 1, 1),
                              wait_for_downstream=False)
        prev_ti = None
        ti = Mock(task=task, previous_ti=prev_ti,
                  execution_date=datetime(2016, 1, 1))
        dep_context = DepContext(ignore_depends_on_past=False)

        self.assertTrue(PrevDagrunDep().is_met(ti=ti, dep_context=dep_context))

    def test_prev_ti_bad_state(self):
        """
        If the previous TI did not complete execution this dep should fail.
        """
        task = self._get_task(depends_on_past=True,
                              start_date=datetime(2016, 1, 1),
                              wait_for_downstream=False)
        prev_ti = Mock(state=State.NONE,
                       are_dependents_done=Mock(return_value=True))
        ti = Mock(task=task, previous_ti=prev_ti,
                  execution_date=datetime(2016, 1, 2))
        dep_context = DepContext(ignore_depends_on_past=False)

        self.assertFalse(PrevDagrunDep().is_met(ti=ti, dep_context=dep_context))

    def test_failed_wait_for_downstream(self):
        """
        If the previous TI specified to wait for the downstream tasks of the
        previous dagrun then it should fail this dep if the downstream TIs of
        the previous TI are not done.
        """
        task = self._get_task(depends_on_past=True,
                              start_date=datetime(2016, 1, 1),
                              wait_for_downstream=True)
        prev_ti = Mock(state=State.SUCCESS,
                       are_dependents_done=Mock(return_value=False))
        ti = Mock(task=task, previous_ti=prev_ti,
                  execution_date=datetime(2016, 1, 2))
        dep_context = DepContext(ignore_depends_on_past=False)

        self.assertFalse(PrevDagrunDep().is_met(ti=ti, dep_context=dep_context))

    def test_all_met(self):
        """
        Test to make sure all of the conditions for the dep are met
        """
        task = self._get_task(depends_on_past=True,
                              start_date=datetime(2016, 1, 1),
                              wait_for_downstream=True)
        prev_ti = Mock(state=State.SUCCESS,
                       are_dependents_done=Mock(return_value=True))
        ti = Mock(task=task, previous_ti=prev_ti,
                  execution_date=datetime(2016, 1, 2))
        dep_context = DepContext(ignore_depends_on_past=False)

        self.assertTrue(PrevDagrunDep().is_met(ti=ti, dep_context=dep_context))


text:
package org.apache.flink.graph.drivers.input;

import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.drivers.parameter.Parameterized;
import org.apache.flink.graph.generator.GraphGenerator;

/**
 * Input source for a {@link Graph}, for example a file reader or
 * {@link GraphGenerator}.
 *
 * @param <K> graph ID type
 * @param <VV> vertex value type
 * @param <EV> edge value type
 */
public interface Input<K, VV, EV>
extends Parameterized {

	/**
	 * A human-readable identifier summarizing the input and configuration.
	 *
	 * @return the unique identifier
	 */
	String getIdentity();

	/**
	 * Create the input {@link Graph}.
	 *
	 * @param env the ExecutionEnvironment
	 * @return the input Graph
	 */
	Graph<K, VV, EV> create(ExecutionEnvironment env) throws Exception;
}


text:
DELIMITER ;;

CREATE TABLE IF NOT EXISTS shelves (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    theme VARCHAR(1024) NOT NULL
    )
;;

CREATE TABLE IF NOT EXISTS books (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    shelf BIGINT UNSIGNED NOT NULL,
    author VARCHAR(1024) NOT NULL,
    title VARCHAR(1024) NOT NULL,
    CONSTRAINT FOREIGN KEY (shelf) REFERENCES shelves(id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
    )
;;

DROP PROCEDURE IF EXISTS list_shelves;;
CREATE PROCEDURE list_shelves()
BEGIN
    SELECT * FROM shelves;
END
;;

DROP PROCEDURE IF EXISTS create_shelf;;
CREATE PROCEDURE create_shelf(IN t VARCHAR(1024), OUT id BIGINT)
BEGIN
   INSERT INTO shelves (theme) VALUES (t);
   SELECT LAST_INSERT_ID() INTO id;
END
;;

DROP PROCEDURE IF EXISTS get_shelf;;
CREATE PROCEDURE get_shelf(IN id BIGINT)
BEGIN
    SELECT * FROM shelves WHERE shelves.id=id;
END
;;

DROP PROCEDURE IF EXISTS delete_shelf;;
CREATE PROCEDURE delete_shelf(IN id BIGINT, OUT valid BOOLEAN)
BEGIN
    SELECT COUNT(1) > 0 FROM shelves WHERE shelves.id=id INTO valid;
    DELETE FROM shelves WHERE shelves.id=id;
END
;;

DROP PROCEDURE IF EXISTS list_books;;
CREATE PROCEDURE list_books(IN shelf BIGINT, OUT valid BOOLEAN)
BEGIN
    SELECT COUNT(1) > 0 FROM shelves WHERE shelves.id=shelf INTO valid;
    SELECT * FROM books WHERE books.shelf=shelf;
END
;;

DROP PROCEDURE IF EXISTS create_book;;
CREATE PROCEDURE create_book(IN shelf BIGINT, IN author VARCHAR(1024), IN title VARCHAR(1024), OUT valid BOOLEAN, OUT id BIGINT)
BEGIN
    SET id = 0;
    SELECT COUNT(1) > 0 FROM shelves WHERE shelves.id=shelf INTO valid;
    IF valid = TRUE THEN BEGIN
      INSERT INTO books (shelf, author, title) VALUES (shelf, author, title);
      SELECT LAST_INSERT_ID() INTO id;
    END;
    END IF;
END
;;

DROP PROCEDURE IF EXISTS get_book;;
CREATE PROCEDURE get_book(IN shelf BIGINT, IN id BIGINT)
BEGIN
    SELECT * FROM books WHERE books.id=id AND books.shelf=shelf;
END
;;

DROP PROCEDURE IF EXISTS delete_book;;
CREATE PROCEDURE delete_book(IN shelf BIGINT, IN id BIGINT, OUT valid BOOLEAN)
BEGIN
    SELECT COUNT(1) > 0 from shelves WHERE shelves.id=shelf INTO valid;
    DELETE FROM books WHERE books.id=id AND books.shelf=shelf;
END
;;

DROP PROCEDURE IF EXISTS initialize_database;;
CREATE PROCEDURE initialize_database()
BEGIN
  SELECT COUNT(*) FROM shelves into @shelf_count;
  IF @shelf_count <= 0 THEN
      CALL create_shelf('Fiction', @fiction_id);
      CALL create_shelf('Fantasy', @fantasy_id);
      CALL create_book(@fiction_id, 'Neal Stephenson', 'REAMDE', @valid, @book_id);
      CALL create_book(@fantasy_id, 'George R.R. Martin', 'A Game of Thrones', @valid, @book_id);
  END IF;
END
;;

CALL initialize_database();;
DROP PROCEDURE IF EXISTS initialize_database;;


text:
package com.team687.lib.kauailabs.sf2.sensor;

import com.team687.lib.kauailabs.sf2.quantity.IQuantity;
import com.team687.lib.kauailabs.sf2.time.Timestamp;

/**
 * Interface to be implemented by any subscriber of Sensor Data of type T.
 *
 * @author Scott
 * @param system_timestamp
 *            - the system timestamp when the data was received.
 * @param update
 *            - the object of type T representing the newly-received data.
 */
public interface ISensorDataSubscriber {
    void publish(IQuantity[] curr_values, Timestamp timestamp);
}


text:
import * as child_process from 'child_process';
import {blue, yellow} from 'chalk';
import {getGlobalVariable} from './env';
import {rimraf} from './fs';
import {wait} from './utils';
const treeKill = require('tree-kill');

interface ExecOptions {
  silent?: boolean;
  waitForMatch?: RegExp;
}

let _processes: child_process.ChildProcess[] = [];

export type ProcessOutput = {
  stdout: string;
  stderr: string;
};

function _exec(options: ExecOptions, cmd: string, args: string[]): Promise<ProcessOutput> {
  let stdout = '';
  let stderr = '';
  const cwd = process.cwd();
  console.log(
    `==========================================================================================`
  );

  args = args.filter(x => x !== undefined);
  const flags = [
    options.silent && 'silent',
    options.waitForMatch && `matching(${options.waitForMatch})`
  ]
    .filter(x => !!x)  // Remove false and undefined.
    .join(', ')
    .replace(/^(.+)$/, ' [$1]');  // Proper formatting.

  console.log(blue(`Running \`${cmd} ${args.map(x => `"${x}"`).join(' ')}\`${flags}...`));
  console.log(blue(`CWD: ${cwd}`));
  const spawnOptions: any = {cwd};

  if (process.platform.startsWith('win')) {
    args.unshift('/c', cmd);
    cmd = 'cmd.exe';
    spawnOptions['stdio'] = 'pipe';
  }

  const childProcess = child_process.spawn(cmd, args, spawnOptions);
  childProcess.stdout.on('data', (data: Buffer) => {
    stdout += data.toString('utf-8');
    if (options.silent) {
      return;
    }
    data.toString('utf-8')
      .split(/[\n\r]+/)
      .filter(line => line !== '')
      .forEach(line => console.log('  ' + line));
  });
  childProcess.stderr.on('data', (data: Buffer) => {
    stderr += data.toString('utf-8');
    if (options.silent) {
      return;
    }
    data.toString('utf-8')
      .split(/[\n\r]+/)
      .filter(line => line !== '')
      .forEach(line => console.error(yellow('  ' + line)));
  });

  _processes.push(childProcess);

  // Create the error here so the stack shows who called this function.
  const err = new Error(`Running "${cmd} ${args.join(' ')}" returned error code `);
  return new Promise((resolve, reject) => {
    childProcess.on('exit', (error: any) => {
      _processes = _processes.filter(p => p !== childProcess);

      if (!error) {
        resolve({ stdout, stderr });
      } else {
        err.message += `${error}...\n\nSTDOUT:\n${stdout}\n\nSTDERR:\n${stderr}\n`;
        reject(err);
      }
    });

    if (options.waitForMatch) {
      childProcess.stdout.on('data', (data: Buffer) => {
        if (data.toString().match(options.waitForMatch)) {
          resolve({ stdout, stderr });
        }
      });
    }
  });
}

export function waitForAnyProcessOutputToMatch(match: RegExp,
                                               timeout = 30000): Promise<ProcessOutput> {
  // Race between _all_ processes, and the timeout. First one to resolve/reject wins.
  const timeoutPromise: Promise<ProcessOutput> = new Promise((_resolve, reject) => {
    // Wait for 30 seconds and timeout.
    setTimeout(() => {
      reject(new Error(`Waiting for ${match} timed out (timeout: ${timeout}msec)...`));
    }, timeout);
  });

  const matchPromises: Promise<ProcessOutput>[] = _processes.map(
    childProcess => new Promise(resolve => {
      let stdout = '';
      let stderr = '';
      childProcess.stdout.on('data', (data: Buffer) => {
        stdout += data.toString();
        if (data.toString().match(match)) {
          resolve({ stdout, stderr });
        }
      });
      childProcess.stderr.on('data', (data: Buffer) => {
        stderr += data.toString();
        if (data.toString().match(match)) {
          resolve({ stdout, stderr });
        }
      });
    }));

  return Promise.race(matchPromises.concat([timeoutPromise]));
}

export function killAllProcesses(signal = 'SIGTERM') {
  _processes.forEach(process => treeKill(process.pid, signal));
  _processes = [];
}

export function exec(cmd: string, ...args: string[]) {
  return _exec({}, cmd, args);
}

export function silentExec(cmd: string, ...args: string[]) {
  return _exec({ silent: true }, cmd, args);
}

export function execAndWaitForOutputToMatch(cmd: string, args: string[], match: RegExp) {
  let maybeWait = Promise.resolve();
  if (cmd === 'ng' && args[0] === 'serve') {
    // Webpack watcher can rebuild a few times due to files changes that happened just before the
    // build (e.g. `git clean`), so we wait here.
    maybeWait = wait(5000);
  }
  return maybeWait.then(() => _exec({ waitForMatch: match }, cmd, args));
}

export function silentExecAndWaitForOutputToMatch(cmd: string, args: string[], match: RegExp) {
  let maybeWait = Promise.resolve();
  if (cmd === 'ng' && args[0] === 'serve') {
    // See execAndWaitForOutputToMatch for why the wait.
    maybeWait = wait(5000);
  }
  return maybeWait.then(() => _exec({ silent: true, waitForMatch: match }, cmd, args));
}

let npmInstalledEject = false;
export function ng(...args: string[]) {
  const argv = getGlobalVariable('argv');
  const maybeSilentNg = argv['nosilent'] ? noSilentNg : silentNg;
  if (['build', 'serve', 'test', 'e2e', 'xi18n'].indexOf(args[0]) != -1) {
    // If we have the --eject, use webpack for the test.
    if (args[0] == 'build' && argv.eject) {
      return maybeSilentNg('eject', ...args.slice(1), '--force')
        .then(() => {
          if (!npmInstalledEject) {
            npmInstalledEject = true;
            // We need to run npm install on the first eject.
            return silentNpm('install');
          }
        })
        .then(() => rimraf('dist'))
        .then(() => _exec({silent: true}, 'node_modules/.bin/webpack', []));
    } else if (args[0] == 'e2e') {
      // Wait 1 second before running any end-to-end test.
      return new Promise(resolve => setTimeout(resolve, 1000))
        .then(() => maybeSilentNg(...args));
    }

    return maybeSilentNg(...args);
  } else {
    return noSilentNg(...args);
  }
}

export function noSilentNg(...args: string[]) {
  return _exec({}, 'ng', args);
}

export function silentNg(...args: string[]) {
  return _exec({silent: true}, 'ng', args);
}

export function silentNpm(...args: string[]) {
  return _exec({silent: true}, 'npm', args);
}

export function npm(...args: string[]) {
  return _exec({}, 'npm', args);
}

export function node(...args: string[]) {
  return _exec({}, 'node', args);
}

export function git(...args: string[]) {
  return _exec({}, 'git', args);
}

export function silentGit(...args: string[]) {
  return _exec({silent: true}, 'git', args);
}


text:
/**
 * @module modifiers/snapEdges
 *
 * @description
 * WOW> This module allows snapping of the edges of targets during resize
 * interactions.
 *
 * ```js
 * interact(target).resizable({
 *   snapEdges: {
 *     targets: [interact.snappers.grid({ x: 100, y: 50 })],
 *   },
 * })
 *
 * interact(target).resizable({
 *   snapEdges: {
 *     targets: [
 *       interact.snappers.grid({
 *        top: 50,
 *        left: 50,
 *        bottom: 100,
 *        right: 100,
 *       }),
 *     ],
 *   },
 * })
 * ```
 */

import clone from '@interactjs/utils/clone'
import extend from '@interactjs/utils/extend'

import { makeModifier } from '../base'
import type { ModifierArg, ModifierModule } from '../types'

import type { SnapOptions, SnapState } from './pointer'
import { snapSize } from './size'

export type SnapEdgesOptions = Pick<SnapOptions, 'targets' | 'range' | 'offset' | 'endOnly' | 'enabled'>

function start (arg: ModifierArg<SnapState>) {
  const { edges } = arg

  if (!edges) {
    return null
  }

  arg.state.targetFields = arg.state.targetFields || [
    [edges.left ? 'left' : 'right', edges.top ? 'top' : 'bottom'],
  ]

  return snapSize.start(arg)
}

const snapEdges: ModifierModule<SnapEdgesOptions, SnapState, ReturnType<typeof snapSize.set>> = {
  start,
  set: snapSize.set,
  defaults: extend(clone(snapSize.defaults), {
    targets: null,
    range: null,
    offset: { x: 0, y: 0 },
  } as const),
}

export default makeModifier(snapEdges, 'snapEdges')
export { snapEdges }


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Admin\ConfigurationUI
 */

/**
 * Config Component interface.
 */
interface WPSEO_Config_Component {

	/**
	 * Get onboarding wizard component identifier.
	 *
	 * @return string
	 */
	public function get_identifier();

	/**
	 * Get onboarding wizard component data.
	 *
	 * @return mixed
	 */
	public function get_data();

	/**
	 * Save changes.
	 *
	 * @param array $data Data provided by the API.
	 *
	 * @return mixed
	 */
	public function set_data( $data );

	/**
	 * Get onboarding wizard component field.
	 *
	 * @return WPSEO_Config_Field
	 */
	public function get_field();
}


text:
using namespace vnotex;

EntryPopup::EntryPopup(QWidget *p_parent)
    : QFrame(p_parent)
{
    Q_ASSERT(p_parent);
    auto layout = new QVBoxLayout(this);
    Q_UNUSED(layout);
}

EntryPopup::~EntryPopup()
{
    if (m_widget) {
        takeWidget(m_widget.data());
    }
}

void EntryPopup::setWidget(const QSharedPointer<QWidget> &p_widget)
{
    if (p_widget == m_widget) {
        return;
    }

    if (m_widget) {
        takeWidget(m_widget.data());
    }

    m_widget = p_widget;
    if (m_widget) {
        layout()->addWidget(m_widget.data());
        m_widget->show();
    }
}

void EntryPopup::takeWidget(QWidget *p_widget)
{
    layout()->removeWidget(p_widget);
    p_widget->hide();
    p_widget->setParent(nullptr);
}