text:
**Solution** (for the mouseOver / mouseOut problem)
All you have to do is hitTest from view you are in. if this is true:

```swift
window.view.hitTest(window.mousePos) === self/*Sudo code*/
```

What this code does is that it returns the view under the mouse position. Now all you have to do is setup a few if and else clauses to verify that your mouse is of or on the view. It works after initial testing. Example coming soon. Now this only works for NSView. CALayer still needs the root NSView to do its mouse handling. So we will use NSView scheme in the continuation of the project.

[Gist](https://gist.github.com/eonist/537ae53b86d5fc332fd3)

**Testing Overlapping NSView with NSTrackingArea:** (not working)

The problem with the above example is that the view that cover the view bellow doesn't cancel the hover interaction. As you would expect. In some-cases this could be intended behavior but most likely not. To differentiate the two behaviors one could imagine describing it as mouseRollOver and mouseRollOut and in the above example mouseEnter and mouseExit.

## **CALayer interaction**

**A possible solution:**
All windows have views, all views have layers. So place a generic NSView in all windows. The window we use could have this NSView placed inside it on init so we would just extend this window, call it "InteractiveWindow" The NSView named InteractiveView has a NSTrackingArea that handles all the mouse events for all subViews and sublayers. The root NSView would call Interactive methods: mouseDown,mouseUp,mouseEnter,mouseExited,mouseMove. Why do we do it this way? Because this is the only way to support mouseEnter/mouseExit that respects other views that may cover it. If a view is partly covered, we only want the top-most view to receive the interaction. This is also the only way to support CALayers with interaction.

- [ ] DO a little more research/digging into covered up views and interactions.
- [ ] Test mouseDown on your current TempNSView demo
- [x] What if we hittest from the window with the cur mouse pos. From the subview. refToWin.view.hittest(mousePos,nil), then assert if self == to the returned view? (this was it!!!)

A hit "sort-of" solution for CALayer: [link](http://stackoverflow.com/questions/1861961/pragmatic-way-of-handling-mouse-in-core-animation-layers)

**HitTesting:**
Because the NSView has an unknown number of layers in its hierarchy, we cannot assume which layer is being clicked just by its location. Fortunately, CALayer has a -hitTest: method designed to solve
this issue. When CGPoint is passed to the root CALayer, it returns the ==deepest CALayer that the point falls within==. This enables you to quickly determine which CALayer has been clicked so that your app can act accordingly.

## Code: (same as in the gist link)
NOTE: this should also work on RoundedRects provided that you implement isWithinPath in the hitTest method override
```swift
import Cocoa

/*
let a = TempNSView(frame:NSRect(0,0,100,100))
a.name = "a"
addSubview(a)

let b = TempNSView(frame:NSRect(50,50,100,100))
b.name = "b"
addSubview(b)
*/

class TempNSView :FlippedView{/*Organizes your view from top to bottom*/
    var name:String = ""/*Makes it easier to test*/
    var isMouseOver:Bool = false;/*you should hit test this on init*/
    var hasMouseEntered:Bool = false/*you should hit test this on init*/
    override var wantsDefaultClipping:Bool{return false}//avoids clipping the view
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        let trackingArea:NSTrackingArea = NSTrackingArea(rect: bounds, options: [NSTrackingAreaOptions.ActiveAlways, NSTrackingAreaOptions.MouseMoved,NSTrackingAreaOptions.MouseEnteredAndExited], owner: self, userInfo: nil)
        addTrackingArea(trackingArea)
    }
    /**
     * NOTE: this method is called from the root view if this view is the top-most visible view
     */
    override func hitTest(aPoint: NSPoint) -> NSView? {
        //Swift.print("hitTest")
        var pos = convertPoint(aPoint, toView: self)/*converts the p to local coordinates*/
        pos -= frame.origin/*converts the point from a global position to a local position*/
        //Swift.print("pos: " + "\(pos)")
        //Swift.print("containsPoint(p): " + String(NSPointInRect(pos + frame.origin, frame)))
        return NSPointInRect(pos + frame.origin, frame) ? self : nil
    }
    required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}
    /**
     * MouseMoved
     */
    override func mouseMoved(theEvent: NSEvent) {
        //Swift.print("mouseMoved")
        if(hasMouseEntered){/*Only run the following code when inside the actual TrackingArea*/
            let theHitView = window!.contentView?.hitTest((window?.mouseLocationOutsideOfEventStream)!)
            //Swift.print("theHitView: " + "\(theHitView)")
            if(theHitView === self){//mouse move on the "visible" part of the view
                if(!isMouseOver){mouseOver()}
                mouseMove()
            }
            else if(isMouseOver){mouseOut()}//mouse move on the "invisible" parth of the view
        }
    }
    /**
     * NOTE: draws a 100 by 100 square with a random color
     */
    override func drawRect(dirtyRect: NSRect) {
        Swift.print("TempNSView.drawRect()")
        let graphicsContext = NSGraphicsContext.currentContext()!
        let context = graphicsContext.CGContext/* Get the handle to the current context */
        let path = CGRect(0,0,100,100).path
        CGContextAddPath(context, path)
        CGContextSetFillColorWithColor(context,NSColor.random.CGColor)
        CGContextDrawPath(context, CGPathDrawingMode.Fill)
    }
    /**
     * MouseMove (only fires when the mouse is actualy moving on the visible  part of the view)
     * NOTE: It could be possible to only call this method if a bool value was true. Optimization
     */
    func mouseMove(){
        //Swift.print(name + " mouseMove")
    }
    /**
     * Only fires if the mouse is over the visible part of this view
     */
    func mouseOver(){
        Swift.print(name + " mouseOver")
        isMouseOver = true
    }
    /**
     * Only fires if the mouse is "rolls" out of the visible part of this view
     */
    func mouseOut(){
        Swift.print(name + " mouseOut")
        isMouseOver = false
    }
    /**
     * Fires when the mouse enters the tracking area, regardless if it is overlapping with other trackingAreas of other views
     */
    override func mouseEntered( event: NSEvent){
        //Swift.print("TempNSView.mouseEntered: ")
        hasMouseEntered = true/*optimization*/
        let theHitView = window!.contentView?.hitTest((window?.mouseLocationOutsideOfEventStream)!)
        //Swift.print("theHitView: " + "\(theHitView)")
        if(theHitView === self){mouseOver()}//mouse move on visible view
    }
    /**
     * Fires when the mouse exits the tracking area, regardless if it is overlapping with other trackingAreas of other views
     */
    override func mouseExited(event: NSEvent){
        //Swift.print("TempNSView.mouseExited:")
        hasMouseEntered = false/*optimization*/
        if(isMouseOver){mouseOut()}
    }
    /**
     * MouseDown (for testing purposes)
     */
    override func mouseDown(theEvent: NSEvent) {
        Swift.print("TempNSView.mouseDown()")
        //Swift.print("window?.mouseLocationOutsideOfEventStream: " + "\(window?.mouseLocationOutsideOfEventStream)")
        let theHitView = window!.contentView?.hitTest((window?.mouseLocationOutsideOfEventStream)!)
        Swift.print("theHitView: " + "\(theHitView)")
    }
}

```


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Ardularm: Class Members - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Ardularm

Creating an Arduino-based alarm on a budget

domain
: Config

key
: Config

mailaddAddressAddress
: Config

mailaddAddressName
: Config

mailHost
: Config

mailPassword
: Config

mailSetFromAddress
: Config

mailSetFromName
: Config

mailUsername
: Config

password
: Config

user
: Config

<address class="footer">
Generated by

 1.8.13
</address>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Msrp\Model;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;

class Msrp
{
    /**
     * @var array
     */
    protected $mapApplyToProductType = null;

    /**
     * @var AttributeFactory
     */
    protected $eavAttributeFactory;

    /**
     * @param AttributeFactory $eavAttributeFactory
     */
    public function __construct(
        AttributeFactory $eavAttributeFactory
    ) {
        $this->eavAttributeFactory = $eavAttributeFactory;
    }

    /**
     * Check whether Msrp applied to product Product Type
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return bool
     * @api
     */
    public function canApplyToProduct($product)
    {
        if ($this->mapApplyToProductType === null) {
            /** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
            $attribute = $this->eavAttributeFactory->create()->loadByCode(Product::ENTITY, 'msrp');
            $this->mapApplyToProductType = $attribute->getApplyTo();
        }
        return in_array($product->getTypeId(), $this->mapApplyToProductType);
    }
}


text:
<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
?>

Calibration

    <button id="calButton" class="edit_btn btn btn-default btn-sm" data-toggle="modal" data-target="#calModal" style="float: right;">Edit</button>

Cal Type

Cal Date


text:
import os
import dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
dotenv.load_dotenv(dotenv_path)

# Grab environment variables...
FILEPATH_RDF = os.environ.get("GUTENBERG_RDF_FILEPATH")
FILEPATH_GUTENBERG_TEXTS = os.environ.get("GUTENBERG_DATA")

LIVE_FILE_LIST = []
with open(FILEPATH_GUTENBERG_TEXTS + os.sep + "current_local_text_files.txt", encoding='utf-8') as file:
    for line in file:
        LIVE_FILE_LIST.append(int(str(line.rstrip())))


text:
/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: contextmenu,detabler */

(function () {
	'use strict';
	bender.editor = {
		config: {
			enterMode: CKEDITOR.ENTER_P
		}
	};
	bender.test({
		setUp: function () {
			this.command = this.editorBot.editor.getCommand('detable');
		},
		contextMenuItemIsPresent: function (editor) {
			// open and close the context menu, and return true if the detable option was present.

			editor.contextMenu.open(editor.editable());

			var itemExists = false;
			for (var i = 0; i < editor.contextMenu.items.length; ++i) {
				if (editor.contextMenu.items[i].command == 'detable') {
					itemExists = true;
					break;
				}
			}

			editor.contextMenu.hide();

			return itemExists;
		},
		'context menu item is not present outside of tables': function () {
			var editor = this.editorBot.editor,
				startHtml;

			startHtml = '
foobar^
' +
				'
baz
' +
				'
' +
					'
' +
						'
leave me alone
' +
					'
' +
				'
';

			this.editorBot.setHtmlWithSelection(startHtml);
			// setHtmlWithSelection doesn't appear to refresh command state, so we must manually do it
			this.command.refresh(editor, editor.elementPath());

			assert.areEqual(false, this.contextMenuItemIsPresent(editor));

		},
		'context menu item is present inside of tables': function () {
			var editor = this.editorBot.editor,
				startHtml;

			startHtml = '
foo
' +
				'
' +
					'
' +
						'
^foo	bar
' +
					'
' +
				'
';

			this.editorBot.setHtmlWithSelection(startHtml);
			// setHtmlWithSelection doesn't appear to refresh command state, so we must manually do it
			this.command.refresh(editor, editor.elementPath());

			assert.areEqual(true, this.contextMenuItemIsPresent(editor));
		}
	});
})();


text:
module Partisan
  class Helper
    # Retrieves the parent class name
    def self.parent_class_name(obj)
      # If the object is an ActiveRecord record
      klass = obj.class if obj.class < ActiveRecord::Base

      # If the object respond to `object` and the value is an ActiveRecord record
      klass ||= obj.object.class if obj.respond_to?(:object) && obj.object.class < ActiveRecord::Base

      # In case we're using STI, loop back until we find the top-level ActiveRecord model
      klass = klass.superclass while !klass.superclass.abstract_class && klass.superclass != ActiveRecord::Base

      klass.name
    end
  end
end


text:
void write_bidirectional_streambuf_test()
{
    using namespace std;
    using namespace pdalboost;
    using namespace pdalboost::iostreams;
    using namespace pdalboost::iostreams::test;

    test_file test;

    {
        temp_file test2;
        {
            filebuf dest;
            dest.open(test2.name().c_str(), out_mode);
            filtering_stream<bidirectional> out(dest, 0);
            write_data_in_chars(out);
        }
        BOOST_CHECK_MESSAGE(
            compare_files(test2.name(), test.name()),
            "failed writing to filtering_stream<bidirectional> based "
            "on a streambuf in chars with no buffer"
        );
    }

    {
        temp_file test2;
        {
            filebuf dest;
            dest.open(test2.name().c_str(), out_mode);
            filtering_stream<bidirectional> out(dest, 0);
            write_data_in_chunks(out);
        }
        BOOST_CHECK_MESSAGE(
            compare_files(test2.name(), test.name()),
            "failed writing to filtering_stream<bidirectional> based "
            "on a streambuf in chunks with no buffer"
        );
    }

    {
        temp_file test2;
        {
            filebuf dest;
            dest.open(test2.name().c_str(), out_mode);
            filtering_stream<bidirectional> out(dest);
            write_data_in_chars(out);
        }
        BOOST_CHECK_MESSAGE(
            compare_files(test2.name(), test.name()),
            "failed writing to filtering_stream<bidirectional> based "
            "on a streambuf in chars with large buffer"
        );
    }

    {
        temp_file test2;
        {
            filebuf dest;
            dest.open(test2.name().c_str(), out_mode);
            filtering_stream<bidirectional> out(dest);
            write_data_in_chunks(out);
        }
        BOOST_CHECK_MESSAGE(
            compare_files(test2.name(), test.name()),
            "failed writing to filtering_stream<bidirectional> based "
            "on a streambuf in chunks with large buffer"
        );
    }
}

#endif // #ifndef BOOST_IOSTREAMS_TEST_WRITE_BIDIRECTIONAL_STREAMBUF_HPP_INCLUDED


text:
using System;
using System.IO;

namespace Weaver.Util
{
    public sealed class TemporaryAssemblyPaths : IDisposable
    {
        public string DllPath { get; private set; }
        public string PdbPath { get; private set; }

        public TemporaryAssemblyPaths() :
            this(Path.GetTempPath())
        {
        }

        public TemporaryAssemblyPaths(string directory)
        {
            var randomFileName = Path.Combine(directory, Path.GetRandomFileName());
            DllPath = randomFileName + ".dll";
            PdbPath = randomFileName + ".pdb";
        }

        ~TemporaryAssemblyPaths() {
            Delete();
        }

        public void Dispose() {
            Delete();
            GC.SuppressFinalize(this);
        }

        private void Delete() {
            if (File.Exists(DllPath))
                File.Delete(DllPath);
            if (File.Exists(PdbPath))
                File.Delete(PdbPath);
        }
    }
}


text:
package com.jcommerce.gwt.client;

import java.io.IOException;

import com.google.gwt.user.client.Random;

public class ClientHttpRequestHelper{

	public String getRequestData() {
		return os.toString();
	}

	private StringBuffer os = new StringBuffer();

	protected void write(String s)  {
		os.append(s);
	}

	protected void write(char c) {
		os.append(c);
	}

	protected void newline() {
		write("\r\n");
	}

	protected void writeln(String s) {

		write(s);
		newline();
	}

	protected static String randomString() {
		return Long.toString(Random.nextInt(), 36);
	}

	String boundary = "---------------------------" + randomString()
			+ randomString() + randomString();

	private void boundary() {
		write("--");
		write(boundary);
	}

	private void writeName(String name) {
		newline();
		write("Content-Disposition: form-data; name=\"");
		write(name);
		write('"');
	}

	/**
	 * adds a string parameter to the request
	 *
	 * @param name
	 *            parameter name
	 * @param value
	 *            parameter value
	 * @throws IOException
	 */
	public void setParameter(String name, String value)  {
			boundary();
			writeName(name);
			newline();
			newline();
			writeln(value);
	}
}


text:
using System;
using System.Collections.Generic;

namespace Nest
{
	/// <summary>
	/// A reindex implementation that uses ScrollAll() BulkAll() to compose a reindex pipeline.
	///
	/// <para> This differs from ReindexOnServer() in that documents are fetched from Elasticsearch, transformed on the client side,
	/// then sent back to Elasticsearch.
	/// </para>
	///
	/// <para> This will create the target index if it doesn't exist already. If <see cref="CreateIndexRequest" /> is not specified
	/// and the source of the reindex  points to a single index we try and reuse the settings from source.
	/// You can completely opt out of all of this using <see cref="OmitIndexCreation"/>
	/// </para>
	///
	/// </summary>
	public interface IReindexRequest<TSource, TTarget>
		where TSource : class
		where TTarget : class
	{
		/// <summary>
		/// The scroll typically outperforms the bulk operations by a long shot. If we'd leave things unbounded you'd quickly have way too many pending scroll
		/// requests. What this property allows you to express is that for each bucket in the max concurrency of the minimum max concurrency between
		/// producer and consumer amply the maximum overal pending of the other side by this factor. Typically the concurrency of the consumer (bulkall) will
		/// be lower and with this factor we can dampen the overall pending scroll requests while we are still processing bulk requests.
		/// <para>defaults to 4 if not provided</para>
		/// </summary>
		int? BackPressureFactor { get; set; }

		/// <summary>
		/// Describes the scroll operation where we need to fetch the documents from.
		/// <para>
		/// Note that <see cref="IScrollAllRequest.BackPressure"/> can be overriden by our own.
		/// </para>
		/// </summary>
		IScrollAllRequest ScrollAll{ get; set; }

		/// <summary>
		/// Provide a factory for the bulk all request, the first argument is the lazy collection of scroll results which is a mandatory
		/// argument to create <see cref="BulkAllRequest{T}" /> or <see cref="BulkAllDescriptor{T}"/>
		/// <para>
		/// Note that <see cref="IBulkAllRequest{T}.BufferToBulk"/> is always overriden as well as
		/// <see cref="IBulkAllRequest{T}.BackPressure"/>
		/// </para>
		/// </summary>
		Func<IEnumerable<IHitMetadata<TTarget>>, IBulkAllRequest<IHitMetadata<TTarget>>> BulkAll { get; set; }

		Func<TSource, TTarget> Map { get; set; }

		/// <summary>
		/// Do not send a create index call on the target index, assume the index has been created outside of the reindex.
		/// Reindex will never create the index if it already exists however this will also omit the IndexExists call.
		/// </summary>
		bool OmitIndexCreation { get; set; }

		/// <summary>
		/// Describe how the newly created index should be created. Remember you can also register Index Templates for more dynamic usecases.
		/// </summary>
		ICreateIndexRequest CreateIndexRequest { get; set; }
	}

	/// <inheritdoc/>
	public interface IReindexRequest<TSource> : IReindexRequest<TSource, TSource> where TSource : class { }

	/// <inheritdoc/>
	public class ReindexRequest<TSource, TTarget> : IReindexRequest<TSource, TTarget>
		where TSource : class
		where TTarget : class
	{
		/// <inheritdoc/>
		IScrollAllRequest IReindexRequest<TSource, TTarget>.ScrollAll { get; set; }
		/// <inheritdoc/>
		Func<IEnumerable<IHitMetadata<TTarget>>,IBulkAllRequest<IHitMetadata<TTarget>>> IReindexRequest<TSource, TTarget>.BulkAll { get; set; }
		/// <inheritdoc/>
		Func<TSource, TTarget> IReindexRequest<TSource, TTarget>.Map { get; set; }

		/// <inheritdoc/>
		public bool OmitIndexCreation { get; set; }
		/// <inheritdoc/>
		public ICreateIndexRequest CreateIndexRequest { get; set; }
		/// <inheritdoc/>
		public int? BackPressureFactor { get; set; }

		/// <inheritdoc/>
		/// <param name="scrollSource">The scroll operation yielding the source documents for the reindex operation</param>
		/// <param name="map">A function that converts from a source document to a target document</param>
		/// <param name="bulkAllTarget">A factory that instantiates the bulk all operation over the lazy stream of search result hits</param>
		public ReindexRequest(IScrollAllRequest scrollSource, Func<TSource, TTarget> map, Func<IEnumerable<IHitMetadata<TTarget>>, IBulkAllRequest<IHitMetadata<TTarget>>> bulkAllTarget)
		{
			scrollSource.ThrowIfNull(nameof(scrollSource), "scrollSource must be set in order to get the source of a Reindex operation");
			bulkAllTarget.ThrowIfNull(nameof(bulkAllTarget), "bulkAllTarget must set in order to get the target of a Reindex operation");
			map.ThrowIfNull(nameof(map), "map must be set to know how to take TSource and transform it into TTarget");

			var i = (IReindexRequest<TSource, TTarget>) this;
			i.ScrollAll = scrollSource;
			i.BulkAll = bulkAllTarget;
			i.Map = map;
		}
	}

	public class ReindexRequest<TSource> : ReindexRequest<TSource, TSource>
		where TSource : class
	{
		public ReindexRequest(IScrollAllRequest scrollSource, Func<IEnumerable<IHitMetadata<TSource>>, IBulkAllRequest<IHitMetadata<TSource>>> bulkAllTarget)
			: base(scrollSource, s=>s, bulkAllTarget)
		{
		}
	}

	public class ReindexDescriptor<TSource, TTarget> : DescriptorBase<ReindexDescriptor<TSource, TTarget>, IReindexRequest<TSource, TTarget>>, IReindexRequest<TSource, TTarget>
		where TSource : class
		where TTarget : class
	{
		IScrollAllRequest IReindexRequest<TSource, TTarget>.ScrollAll{ get; set; }

		private Func<BulkAllDescriptor<IHitMetadata<TTarget>>, IBulkAllRequest<IHitMetadata<TTarget>>> _createBulkAll;
		Func<IEnumerable<IHitMetadata<TTarget>>, IBulkAllRequest<IHitMetadata<TTarget>>> IReindexRequest<TSource, TTarget>.BulkAll { get; set; }
		bool IReindexRequest<TSource, TTarget>.OmitIndexCreation { get; set; }
		ICreateIndexRequest IReindexRequest<TSource, TTarget>.CreateIndexRequest { get; set; }
		int? IReindexRequest<TSource, TTarget>.BackPressureFactor { get; set; }
		Func<TSource, TTarget> IReindexRequest<TSource, TTarget>.Map { get; set; }

		public ReindexDescriptor(Func<TSource, TTarget> mapper)
		{
			var i = (IReindexRequest<TSource, TTarget>) this;
			i.BulkAll = d => this._createBulkAll.InvokeOrDefault(new BulkAllDescriptor<IHitMetadata<TTarget>>(d));
			i.Map = mapper;
		}

		/// <inheritdoc/>
		public ReindexDescriptor<TSource, TTarget> ScrollAll(Time scrollTime, int slices, Func<ScrollAllDescriptor<TSource>,IScrollAllRequest> selector = null) =>
			Assign(a => a.ScrollAll = selector.InvokeOrDefault(new ScrollAllDescriptor<TSource>(scrollTime, slices)));

		/// <inheritdoc/>
		public ReindexDescriptor<TSource, TTarget> BackPressureFactor(int? maximum) =>
			Assign(a => a.BackPressureFactor = maximum);

		/// <inheritdoc/>
		public ReindexDescriptor<TSource, TTarget> BulkAll(Func<BulkAllDescriptor<IHitMetadata<TTarget>>, IBulkAllRequest<IHitMetadata<TTarget>>> selector) =>
			Assign(a => this._createBulkAll = selector);

		/// <inheritdoc/>
		public ReindexDescriptor<TSource, TTarget> OmitIndexCreation(bool omit = true) => Assign(a => a.OmitIndexCreation = true);

		/// <inheritdoc/>
		public ReindexDescriptor<TSource, TTarget> CreateIndex(Func<CreateIndexDescriptor, ICreateIndexRequest> createIndexSelector) =>
			Assign(a => a.CreateIndexRequest = createIndexSelector.InvokeOrDefault(new CreateIndexDescriptor("ignored")));
	}
}


text:
package org.sakaiproject.tool.assessment.facade;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.sakaiproject.tool.assessment.data.dao.assessment.FavoriteColChoices;
import org.sakaiproject.tool.assessment.services.PersistenceService;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class FavoriteColChoicesFacadeQueries extends HibernateDaoSupport
					implements FavoriteColChoicesFacadeQueriesAPI {
	private static Log log = LogFactory.getLog(FavoriteColChoicesFacadeQueries.class);
	 public FavoriteColChoicesFacadeQueries () {
	  }

	  public void saveOrUpdate(final FavoriteColChoices choices) {

		  List favoriteList = null;
		  final String query = "from FavoriteColChoices as a " +
		  "where a.favoriteName=? ";
		  HibernateCallback hcb = new HibernateCallback() {
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query q = session.createQuery(query);
					q.setString(0, choices.getFavoriteName());
					return q.list();
				};
			};
			favoriteList = getHibernateTemplate().executeFind(hcb);
			if(favoriteList != null){
				Iterator iter = favoriteList.iterator();
				if(iter.hasNext()){
					FavoriteColChoices fChoice = (FavoriteColChoices)iter.next();
					//remove the existing entry
					getHibernateTemplate().delete(fChoice);
				}
			}
				int retryCount = PersistenceService.getInstance().getPersistenceHelper().getRetryCount().intValue();
				while (retryCount > 0){
					try {

						getHibernateTemplate().save(choices);
						retryCount = 0;
					}
					catch (Exception e) {
						log.warn("problem saving favoriteColChoices: "+e.getMessage());
						retryCount = PersistenceService.getInstance().getPersistenceHelper().retryDeadlock(e, retryCount);
					}
				}

		  }

	public List getFavoriteColChoicesByAgent(final String siteAgentId){

			final String query = "from FavoriteColChoices as a " +
			"where a.ownerStringId=? ";
			//"order by b.sequence";

		HibernateCallback hcb = new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery(query);
				q.setString(0, siteAgentId);
				return q.list();
			};
		};
		return getHibernateTemplate().executeFind(hcb);

	}
}


text:
package com.codepath.apps.tweettrove.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;

import com.codepath.apps.tweettrove.R;
import com.codepath.apps.tweettrove.activities.ImageTweetDetailsActivity;
import com.codepath.apps.tweettrove.activities.TweetDetailsActivity;
import com.codepath.apps.tweettrove.adapters.TweetsAdapter;
import com.codepath.apps.tweettrove.helpers.EndlessRecyclerViewScrollListener;
import com.codepath.apps.tweettrove.helpers.ItemClickSupport;
import com.codepath.apps.tweettrove.helpers.SpacesItemDecoration;
import com.codepath.apps.tweettrove.models.Media;
import com.codepath.apps.tweettrove.models.Tweet;
import com.victor.loading.rotate.RotateLoading;

import org.parceler.Parcels;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter;
import jp.wasabeef.recyclerview.animators.FadeInUpAnimator;

/**
 * Created by Hari on 8/8/2016.
 */
public abstract class TimelineFragment extends Fragment
        implements ComposeTweetFragment.ComposeTweetFragmentListener
{

    private ArrayList<Tweet> tweets;
    private TweetsAdapter aTweets;

    @BindView(R.id.rvTweets)
    public RecyclerView rvTweets;

    @BindView(R.id.fabComposeTweet)
    public FloatingActionButton fabComposeTweet;

    @BindView(R.id.swipeContainer)
    public SwipeRefreshLayout swipeContainer;

    @BindView(R.id.rotateLoading)
    public RotateLoading rotateLoading;

    public LinearLayoutManager layoutManager;

    public boolean isDeviceOnline = true;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        tweets = new ArrayList<>();
        aTweets = new TweetsAdapter(getActivity(), tweets);

    }

    public void clearTweets()
    {
        aTweets.clear();
        deleteTweetsFromDB();
    }

    private void setupRVTweets()
    {
        rvTweets.setAdapter(aTweets);
        layoutManager = new LinearLayoutManager(getContext());
        rvTweets.setLayoutManager(layoutManager);

        rvTweets.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) {
            @Override
            public void onLoadMore(int page, int totalItemsCount) {
                if(isOnline())
                    populateTimeline(getLowestId());
            }
        });

        ItemClickSupport.addTo(rvTweets).setOnItemClickListener(
                new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {

                        try {
                            Tweet tweet = tweets.get(position);

                            Media media = null;
                            if (tweet.getEntities().getMedia() != null) {
                                media = tweet.getEntities().getMedia().get(0);
                            }
                            if (media != null && media.getMediaUrlHttps() != null && !media.getMediaUrlHttps().isEmpty()) {
                                Intent imageTweetIntent = new Intent(getActivity(), ImageTweetDetailsActivity.class);
                                imageTweetIntent.putExtra("tweet", Parcels.wrap(tweet));
                                imageTweetIntent.putExtra("position", position);

                                startActivityForResult(imageTweetIntent, 0);

                            }
                            else {

                                Intent intent = new Intent(getActivity(), TweetDetailsActivity.class);
                                intent.putExtra("tweet", Parcels.wrap(tweet));
                                intent.putExtra("position", position);
//                                startActivity(intent);
                                startActivityForResult(intent, 0);
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }
                    }
                }
        );

        SpacesItemDecoration decoration = new SpacesItemDecoration(20);
        rvTweets.addItemDecoration(decoration);
        setupRVAnimator();

    }

    private void setupRVAnimator() {
        SlideInBottomAnimationAdapter animator = new SlideInBottomAnimationAdapter(aTweets);
        animator.setDuration(500);
        animator.setFirstOnly(false);
        animator.setInterpolator(new OvershootInterpolator(1f));

        rvTweets.setItemAnimator(new FadeInUpAnimator());

        AlphaInAnimationAdapter alphaAnimator = new AlphaInAnimationAdapter(animator);
        alphaAnimator.setFirstOnly(false);
        alphaAnimator.setDuration(500);
        alphaAnimator.setInterpolator(new AccelerateInterpolator(1f));
        rvTweets.setAdapter(alphaAnimator);

    }

    public void deleteTweetsFromDB()
    {
        if(tweets == null)
            return;
        int numTweets = tweets.size();
        for(int i = 0 ; i < numTweets; i++)
        {
            tweets.get(0).delete();
        }
    }

    public void saveTweetsToDB()
    {
        if(tweets == null)
            return;

        for (int i = 0; i < tweets.size(); i++)
        {
            tweets.get(i).getUser().save();
//            tweets.get(i).getEntities().save();
//            tweets.get(i).getEntities().getMedia().save();
//            tweets.get(i).getExtendedEntities().save();
            tweets.get(i).save();
        }
    }

    public void displayDBData()
    {
        try
        {
            aTweets.addAll(Tweet.getAll());
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public boolean isOnline() {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }
        return false;
    }

    private Unbinder unbinder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_timeline, container, false);

        unbinder = ButterKnife.bind(this, view);
        clearTweets();
        setupRVTweets();

        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if(isOnline())
                    clearTweets();
                populateTimeline(getLowestId());
            }
        });

        // Configure the refreshing colors
        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void addAll(ArrayList<Tweet> tweets)
    {
        aTweets.addAll(tweets);
    }

    @OnClick(R.id.fabComposeTweet)
    public void startComposeTweetFragment()
    {
        if(!isOnline())
        {
            Toast.makeText(getActivity(), "Please connect to the Internet", Toast.LENGTH_SHORT).show();
            return;
        }
        FragmentManager fm = getFragmentManager(); //getSupportFragmentManager();
        ComposeTweetFragment composeTweetFragment = ComposeTweetFragment.newInstance(this, null, false);
        composeTweetFragment.show(fm,"compose_tweet_fragment");
    }

    @Override
    public void onFinishComposeTweetFragmentListener(String statusText) {

        if (statusText.isEmpty())
            return;

        finishComposeTweet(statusText);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // REQUEST_CODE is defined above
        if (resultCode == 0 && requestCode == 0) {

            boolean isRT  =  data.getBooleanExtra("isRetweeted", false);
            boolean isFav = data.getBooleanExtra("isFavorited", false);

            if(isFav || isRT)
            {
                aTweets.clear();
                    populateTimeline(getLowestId());
            }

        }
    }

    public long getLowestId()
    {

        if(tweets.size() < 1)
            return -1;
        long currentMinId = tweets.get(tweets.size() - 1).getUid();
        return currentMinId;
    }

    protected abstract void populateTimeline(long maxId);

    protected abstract void finishComposeTweet(String statusText);

}


text:
<?php

namespace Magento\Eav\Model\ResourceModel\Entity\Attribute\Group;

/**
 * Eav attribute group resource collection
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Init resource model for collection
     *
     * @return void
     * @codeCoverageIgnore
     */
    protected function _construct()
    {
        $this->_init(
            'Magento\Eav\Model\Entity\Attribute\Group',
            'Magento\Eav\Model\ResourceModel\Entity\Attribute\Group'
        );
    }

    /**
     * Set Attribute Set Filter
     *
     * @param int $setId
     * @return $this
     */
    public function setAttributeSetFilter($setId)
    {
        $this->addFieldToFilter('attribute_set_id', ['eq' => $setId]);
        $this->setOrder('sort_order');
        return $this;
    }

    /**
     * Set sort order
     *
     * @param string $direction
     * @return $this
     * @codeCoverageIgnore
     */
    public function setSortOrder($direction = self::SORT_ORDER_ASC)
    {
        return $this->addOrder('sort_order', $direction);
    }
}


text:
package org.apache.hadoop.hbase.regionserver;

import com.google.common.collect.ImmutableList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.coprocessor.*;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.WritableByteArrayComparable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.ipc.CoprocessorProtocol;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;

/**
 * Implements the coprocessor environment and runtime support for coprocessors
 * loaded within a {@link HRegion}.
 */
public class RegionCoprocessorHost
    extends CoprocessorHost<RegionCoprocessorHost.RegionEnvironment> {

  private static final Log LOG = LogFactory.getLog(RegionCoprocessorHost.class);

  /**
   * Encapsulation of the environment of each coprocessor
   */
  static class RegionEnvironment extends CoprocessorHost.Environment
      implements RegionCoprocessorEnvironment {

    private HRegion region;
    private RegionServerServices rsServices;

    /**
     * Constructor
     * @param impl the coprocessor instance
     * @param priority chaining priority
     */
    public RegionEnvironment(final Coprocessor impl, final int priority,
        final int seq, final Configuration conf, final HRegion region,
        final RegionServerServices services) {
      super(impl, priority, seq, conf);
      this.region = region;
      this.rsServices = services;
    }

    /** @return the region */
    @Override
    public HRegion getRegion() {
      return region;
    }

    /** @return reference to the region server services */
    @Override
    public RegionServerServices getRegionServerServices() {
      return rsServices;
    }

    public void shutdown() {
      super.shutdown();
    }
  }

  /** The region server services */
  RegionServerServices rsServices;
  /** The region */
  HRegion region;

  /**
   * Constructor
   * @param region the region
   * @param rsServices interface to available region server functionality
   * @param conf the configuration
   */
  public RegionCoprocessorHost(final HRegion region,
      final RegionServerServices rsServices, final Configuration conf) {
    this.rsServices = rsServices;
    this.region = region;
    this.pathPrefix = this.region.getRegionNameAsString().replace(',', '_');

    // load system default cp's from configuration.
    loadSystemCoprocessors(conf, REGION_COPROCESSOR_CONF_KEY);

    // load system default cp's for user tables from configuration.
    if (!HTableDescriptor.isMetaTable(region.getRegionInfo().getTableName())) {
      loadSystemCoprocessors(conf, USER_REGION_COPROCESSOR_CONF_KEY);
    }

    // load Coprocessor From HDFS
    loadTableCoprocessors(conf);
  }

  void loadTableCoprocessors(final Configuration conf) {
    // scan the table attributes for coprocessor load specifications
    // initialize the coprocessors
    List<RegionEnvironment> configured = new ArrayList<RegionEnvironment>();
    for (Map.Entry<ImmutableBytesWritable,ImmutableBytesWritable> e:
        region.getTableDesc().getValues().entrySet()) {
      String key = Bytes.toString(e.getKey().get()).trim();
      String spec = Bytes.toString(e.getValue().get()).trim();
      if (HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(key).matches()) {
        // found one
        try {
          Matcher matcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(spec);
          if (matcher.matches()) {
            // jar file path can be empty if the cp class can be loaded
            // from class loader.
            Path path = matcher.group(1).trim().isEmpty() ?
                null : new Path(matcher.group(1).trim());
            String className = matcher.group(2).trim();
            int priority = matcher.group(3).trim().isEmpty() ?
                Coprocessor.PRIORITY_USER : Integer.valueOf(matcher.group(3));
            String cfgSpec = null;
            try {
              cfgSpec = matcher.group(4);
            } catch (IndexOutOfBoundsException ex) {
              // ignore
            }
            if (cfgSpec != null) {
              cfgSpec = cfgSpec.substring(cfgSpec.indexOf('|') + 1);
              Configuration newConf = HBaseConfiguration.create(conf);
              Matcher m = HConstants.CP_HTD_ATTR_VALUE_PARAM_PATTERN.matcher(cfgSpec);
              while (m.find()) {
                newConf.set(m.group(1), m.group(2));
              }
              configured.add(load(path, className, priority, newConf));
            } else {
              configured.add(load(path, className, priority, conf));
            }
            LOG.info("Load coprocessor " + className + " from HTD of " +
              Bytes.toString(region.getTableDesc().getName()) +
                " successfully.");
          } else {
            throw new RuntimeException("specification does not match pattern");
          }
        } catch (Exception ex) {
          LOG.warn("attribute '" + key +
            "' has invalid coprocessor specification '" + spec + "'");
          LOG.warn(StringUtils.stringifyException(ex));
        }
      }
    }
    // add together to coprocessor set for COW efficiency
    coprocessors.addAll(configured);
  }

  @Override
  public RegionEnvironment createEnvironment(Class<?> implClass,
      Coprocessor instance, int priority, int seq, Configuration conf) {
    // Check if it's an Endpoint.
    // Due to current dynamic protocol design, Endpoint
    // uses a different way to be registered and executed.
    // It uses a visitor pattern to invoke registered Endpoint
    // method.
    for (Class c : implClass.getInterfaces()) {
      if (CoprocessorProtocol.class.isAssignableFrom(c)) {
        region.registerProtocol(c, (CoprocessorProtocol)instance);
        break;
      }
    }
    return new RegionEnvironment(instance, priority, seq, conf, region,
        rsServices);
  }

  @Override
  protected void abortServer(final CoprocessorEnvironment env, final Throwable e) {
    abortServer("regionserver", rsServices, env, e);
  }

  /**
   * HBASE-4014 : This is used by coprocessor hooks which are not declared to throw exceptions.
   *
   * For example, {@link
   * org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost#preOpen()} and
   * {@link org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost#postOpen()} are such hooks.
   *
   * See also {@link org.apache.hadoop.hbase.master.MasterCoprocessorHost#handleCoprocessorThrowable()}
   * @param env: The coprocessor that threw the exception.
   * @param e: The exception that was thrown.
   */
  private void handleCoprocessorThrowableNoRethrow(
      final CoprocessorEnvironment env, final Throwable e) {
    try {
      handleCoprocessorThrowable(env,e);
    } catch (IOException ioe) {
      // We cannot throw exceptions from the caller hook, so ignore.
      LOG.warn("handleCoprocessorThrowable() threw an IOException while attempting to handle Throwable " + e
        + ". Ignoring.",e);
    }
  }

  /**
   * Invoked before a region open
   */
  public void preOpen() {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
         try {
          ((RegionObserver)env.getInstance()).preOpen(ctx);
         } catch (Throwable e) {
           handleCoprocessorThrowableNoRethrow(env, e);
         }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Invoked after a region open
   */
  public void postOpen() {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postOpen(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Invoked before a region is closed
   * @param abortRequested true if the server is aborting
   */
  public void preClose(boolean abortRequested) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preClose(ctx, abortRequested);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
      }
    }
  }

  /**
   * Invoked after a region is closed
   * @param abortRequested true if the server is aborting
   */
  public void postClose(boolean abortRequested) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postClose(ctx, abortRequested);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }

      }
      shutdown(env);
    }
  }

  /**
   * Called prior to selecting the {@link StoreFile}s for compaction from
   * the list of currently available candidates.
   * @param store The store where compaction is being requested
   * @param candidates The currently available store files
   * @return If {@code true}, skip the normal selection process and use the current list
   */
  public boolean preCompactSelection(Store store, List<StoreFile> candidates) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    boolean bypass = false;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        ((RegionObserver)env.getInstance()).preCompactSelection(
            ctx, store, candidates);
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * Called after the {@link StoreFile}s to be compacted have been selected
   * from the available candidates.
   * @param store The store where compaction is being requested
   * @param selected The store files selected to compact
   */
  public void postCompactSelection(Store store,
      ImmutableList<StoreFile> selected) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postCompactSelection(
              ctx, store, selected);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env,e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Called prior to rewriting the store files selected for compaction
   * @param store the store being compacted
   * @param scanner the scanner used to read store data during compaction
   */
  public InternalScanner preCompact(Store store, InternalScanner scanner) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    boolean bypass = false;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          scanner = ((RegionObserver)env.getInstance()).preCompact(
              ctx, store, scanner);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env,e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? null : scanner;
  }

  /**
   * Called after the store compaction has completed.
   * @param store the store being compacted
   * @param resultFile the new store file written during compaction
   */
  public void postCompact(Store store, StoreFile resultFile) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postCompact(ctx, store, resultFile);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Invoked before a memstore flush
   */
  public void preFlush() {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preFlush(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Invoked after a memstore flush
   */
  public void postFlush() {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postFlush(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Invoked just before a split
   */
  public void preSplit() {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preSplit(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * Invoked just after a split
   * @param l the new left-hand daughter region
   * @param r the new right-hand daughter region
   */
  public void postSplit(HRegion l, HRegion r) {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postSplit(ctx, l, r);
        } catch (Throwable e) {
          handleCoprocessorThrowableNoRethrow(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  // RegionObserver support

  /**
   * @param row the row key
   * @param family the family
   * @param result the result set from the region
   * @return true if default processing should be bypassed
   * @exception IOException Exception
   */
  public boolean preGetClosestRowBefore(final byte[] row, final byte[] family,
      final Result result) throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preGetClosestRowBefore(ctx, row,
              family, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * @param row the row key
   * @param family the family
   * @param result the result set from the region
   * @exception IOException Exception
   */
  public void postGetClosestRowBefore(final byte[] row, final byte[] family,
      final Result result) throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postGetClosestRowBefore(ctx, row,
              family, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * @param get the Get request
   * @return true if default processing should be bypassed
   * @exception IOException Exception
   */
  public boolean preGet(final Get get, final List<KeyValue> results)
      throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preGet(ctx, get, results);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * @param get the Get request
   * @param results the result set
   * @return the possibly transformed result set to use
   * @exception IOException Exception
   */
  public void postGet(final Get get, final List<KeyValue> results)
  throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postGet(ctx, get, results);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * @param get the Get request
   * @return true or false to return to client if bypassing normal operation,
   * or null otherwise
   * @exception IOException Exception
   */
  public Boolean preExists(final Get get) throws IOException {
    boolean bypass = false;
    boolean exists = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          exists = ((RegionObserver)env.getInstance()).preExists(ctx, get, exists);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? exists : null;
  }

  /**
   * @param get the Get request
   * @param exists the result returned by the region server
   * @return the result to return to the client
   * @exception IOException Exception
   */
  public boolean postExists(final Get get, boolean exists)
      throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          exists = ((RegionObserver)env.getInstance()).postExists(ctx, get, exists);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return exists;
  }

  /**
   * @param put The Put object
   * @param edit The WALEdit object.
   * @param writeToWAL true if the change should be written to the WAL
   * @return true if default processing should be bypassed
   * @exception IOException Exception
   */
  public boolean prePut(Put put, WALEdit edit,
      final boolean writeToWAL) throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).prePut(ctx, put, edit, writeToWAL);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * @param put The Put object
   * @param edit The WALEdit object.
   * @param writeToWAL true if the change should be written to the WAL
   * @exception IOException Exception
   */
  public void postPut(Put put, WALEdit edit,
      final boolean writeToWAL) throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postPut(ctx, put, edit, writeToWAL);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * @param delete The Delete object
   * @param edit The WALEdit object.
   * @param writeToWAL true if the change should be written to the WAL
   * @return true if default processing should be bypassed
   * @exception IOException Exception
   */
  public boolean preDelete(Delete delete, WALEdit edit,
      final boolean writeToWAL) throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preDelete(ctx, delete, edit, writeToWAL);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * @param delete The Delete object
   * @param edit The WALEdit object.
   * @param writeToWAL true if the change should be written to the WAL
   * @exception IOException Exception
   */
  public void postDelete(Delete delete, WALEdit edit,
      final boolean writeToWAL) throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postDelete(ctx, delete, edit, writeToWAL);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * @param row row to check
   * @param family column family
   * @param qualifier column qualifier
   * @param compareOp the comparison operation
   * @param comparator the comparator
   * @param put data to put if check succeeds
   * @return true or false to return to client if default processing should
   * be bypassed, or null otherwise
   * @throws IOException e
   */
  public Boolean preCheckAndPut(final byte [] row, final byte [] family,
      final byte [] qualifier, final CompareOp compareOp,
      final WritableByteArrayComparable comparator, Put put)
    throws IOException {
    boolean bypass = false;
    boolean result = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          result = ((RegionObserver)env.getInstance()).preCheckAndPut(ctx, row, family,
            qualifier, compareOp, comparator, put, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }

        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? result : null;
  }

  /**
   * @param row row to check
   * @param family column family
   * @param qualifier column qualifier
   * @param compareOp the comparison operation
   * @param comparator the comparator
   * @param put data to put if check succeeds
   * @throws IOException e
   */
  public boolean postCheckAndPut(final byte [] row, final byte [] family,
      final byte [] qualifier, final CompareOp compareOp,
      final WritableByteArrayComparable comparator, final Put put,
      boolean result)
    throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          result = ((RegionObserver)env.getInstance()).postCheckAndPut(ctx, row,
            family, qualifier, compareOp, comparator, put, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return result;
  }

  /**
   * @param row row to check
   * @param family column family
   * @param qualifier column qualifier
   * @param compareOp the comparison operation
   * @param comparator the comparator
   * @param delete delete to commit if check succeeds
   * @return true or false to return to client if default processing should
   * be bypassed, or null otherwise
   * @throws IOException e
   */
  public Boolean preCheckAndDelete(final byte [] row, final byte [] family,
      final byte [] qualifier, final CompareOp compareOp,
      final WritableByteArrayComparable comparator, Delete delete)
      throws IOException {
    boolean bypass = false;
    boolean result = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          result = ((RegionObserver)env.getInstance()).preCheckAndDelete(ctx, row,
            family, qualifier, compareOp, comparator, delete, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? result : null;
  }

  /**
   * @param row row to check
   * @param family column family
   * @param qualifier column qualifier
   * @param compareOp the comparison operation
   * @param comparator the comparator
   * @param delete delete to commit if check succeeds
   * @throws IOException e
   */
  public boolean postCheckAndDelete(final byte [] row, final byte [] family,
      final byte [] qualifier, final CompareOp compareOp,
      final WritableByteArrayComparable comparator, final Delete delete,
      boolean result)
    throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          result = ((RegionObserver)env.getInstance())
            .postCheckAndDelete(ctx, row, family, qualifier, compareOp,
              comparator, delete, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return result;
  }

  /**
   * @param row row to check
   * @param family column family
   * @param qualifier column qualifier
   * @param amount long amount to increment
   * @param writeToWAL true if the change should be written to the WAL
   * @return return value for client if default operation should be bypassed,
   * or null otherwise
   * @throws IOException if an error occurred on the coprocessor
   */
  public Long preIncrementColumnValue(final byte [] row, final byte [] family,
      final byte [] qualifier, long amount, final boolean writeToWAL)
      throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          amount = ((RegionObserver)env.getInstance()).preIncrementColumnValue(ctx,
              row, family, qualifier, amount, writeToWAL);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? amount : null;
  }

  /**
   * @param row row to check
   * @param family column family
   * @param qualifier column qualifier
   * @param amount long amount to increment
   * @param writeToWAL true if the change should be written to the WAL
   * @param result the result returned by incrementColumnValue
   * @return the result to return to the client
   * @throws IOException if an error occurred on the coprocessor
   */
  public long postIncrementColumnValue(final byte [] row, final byte [] family,
      final byte [] qualifier, final long amount, final boolean writeToWAL,
      long result) throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          result = ((RegionObserver)env.getInstance()).postIncrementColumnValue(ctx,
              row, family, qualifier, amount, writeToWAL, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return result;
  }

  /**
   * @param increment increment object
   * @return result to return to client if default operation should be
   * bypassed, null otherwise
   * @throws IOException if an error occurred on the coprocessor
   */
  public Result preIncrement(Increment increment)
      throws IOException {
    boolean bypass = false;
    Result result = new Result();
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preIncrement(ctx, increment, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? result : null;
  }

  /**
   * @param increment increment object
   * @param result the result returned by postIncrement
   * @throws IOException if an error occurred on the coprocessor
   */
  public void postIncrement(final Increment increment, Result result)
      throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postIncrement(ctx, increment, result);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * @param scan the Scan specification
   * @return scanner id to return to client if default operation should be
   * bypassed, false otherwise
   * @exception IOException Exception
   */
  public RegionScanner preScannerOpen(Scan scan) throws IOException {
    boolean bypass = false;
    RegionScanner s = null;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          s = ((RegionObserver)env.getInstance()).preScannerOpen(ctx, scan, s);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? s : null;
  }

  /**
   * @param scan the Scan specification
   * @param s the scanner
   * @return the scanner instance to use
   * @exception IOException Exception
   */
  public RegionScanner postScannerOpen(final Scan scan, RegionScanner s)
      throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          s = ((RegionObserver)env.getInstance()).postScannerOpen(ctx, scan, s);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return s;
  }

  /**
   * @param s the scanner
   * @param results the result set returned by the region server
   * @param limit the maximum number of results to return
   * @return 'has next' indication to client if bypassing default behavior, or
   * null otherwise
   * @exception IOException Exception
   */
  public Boolean preScannerNext(final InternalScanner s,
      final List<Result> results, int limit) throws IOException {
    boolean bypass = false;
    boolean hasNext = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          hasNext = ((RegionObserver)env.getInstance()).preScannerNext(ctx, s, results,
            limit, hasNext);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass ? hasNext : null;
  }

  /**
   * @param s the scanner
   * @param results the result set returned by the region server
   * @param limit the maximum number of results to return
   * @param hasMore
   * @return 'has more' indication to give to client
   * @exception IOException Exception
   */
  public boolean postScannerNext(final InternalScanner s,
      final List<Result> results, final int limit, boolean hasMore)
      throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          hasMore = ((RegionObserver)env.getInstance()).postScannerNext(ctx, s,
            results, limit, hasMore);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return hasMore;
  }

  /**
   * @param s the scanner
   * @return true if default behavior should be bypassed, false otherwise
   * @exception IOException Exception
   */
  public boolean preScannerClose(final InternalScanner s)
      throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preScannerClose(ctx, s);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * @param s the scanner
   * @exception IOException Exception
   */
  public void postScannerClose(final InternalScanner s)
      throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postScannerClose(ctx, s);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  /**
   * @param info
   * @param logKey
   * @param logEdit
   * @return true if default behavior should be bypassed, false otherwise
   * @throws IOException
   */
  public boolean preWALRestore(HRegionInfo info, HLogKey logKey,
      WALEdit logEdit) throws IOException {
    boolean bypass = false;
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).preWALRestore(ctx, info, logKey,
              logEdit);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  /**
   * @param info
   * @param logKey
   * @param logEdit
   * @throws IOException
   */
  public void postWALRestore(HRegionInfo info, HLogKey logKey,
      WALEdit logEdit) throws IOException {
    ObserverContext<RegionCoprocessorEnvironment> ctx = null;
    for (RegionEnvironment env: coprocessors) {
      if (env.getInstance() instanceof RegionObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((RegionObserver)env.getInstance()).postWALRestore(ctx, info,
              logKey, logEdit);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }
}


text:
import { getNextPagePathWithIncreasingPageSize } from '../../src/lib/api'
import * as URL from 'url'

interface IPageInfo {
  per_page: number
  page: number
}

function createHeadersWithNextLink(url: string) {
  return new Headers({
    Link: `<${url}>; rel="next"`,
  })
}

function assertNext(current: IPageInfo, expected: IPageInfo) {
  const headers = createHeadersWithNextLink(
    `/items?per_page=${current.per_page}&page=${current.page}`
  )

  const nextPath = getNextPagePathWithIncreasingPageSize(
    new Response(null, { headers })
  )

  expect(nextPath).not.toBeNull()
  const { pathname, query } = URL.parse(nextPath!, true)

  expect(pathname).toBe('/items')

  const per_page = parseInt(
    typeof query.per_page === 'string' ? query.per_page : '',
    10
  )
  const page = parseInt(typeof query.page === 'string' ? query.page : '', 10)

  expect(per_page).toBe(expected.per_page)
  expect(page).toBe(expected.page)

  // If getNextPagePathWithIncreasingPageSize has fiddled with the
  // page size or page number we want to ensure that the next page will
  // get us more items than what we've gotten thus far.
  if (current.per_page !== per_page || current.page !== page) {
    const receivedCurrent = current.per_page * current.page
    const receivedNext = per_page * page

    expect(receivedNext).toBeGreaterThan(receivedCurrent)
  }
}

describe('API', () => {
  describe('getNextPagePathWithIncreasingPageSize', () => {
    it("returns null when there's no link header", () => {
      expect(getNextPagePathWithIncreasingPageSize(new Response())).toBeNull()
    })

    it('returns raw link when missing page size', () => {
      const nextPath = getNextPagePathWithIncreasingPageSize(
        new Response(null, {
          headers: createHeadersWithNextLink('/items?page=2'),
        })
      )

      expect(nextPath).toEqual('/items?page=2')
    })

    it('returns raw link when missing page number', () => {
      const nextPath = getNextPagePathWithIncreasingPageSize(
        new Response(null, {
          headers: createHeadersWithNextLink('/items?per_page=10'),
        })
      )

      expect(nextPath).toEqual('/items?per_page=10')
    })

    it('does not increase page size when not aligned', () => {
      const nextPath = getNextPagePathWithIncreasingPageSize(
        new Response(null, {
          headers: createHeadersWithNextLink('/items?per_page=10&page=2'),
        })
      )

      expect(nextPath).toEqual('/items?per_page=10&page=2')
    })

    it('increases page size on alignment with an initial page size of 10', () => {
      assertNext({ per_page: 10, page: 2 }, { per_page: 10, page: 2 })
      assertNext({ per_page: 10, page: 3 }, { per_page: 20, page: 2 })
      assertNext({ per_page: 20, page: 2 }, { per_page: 20, page: 2 })
      assertNext({ per_page: 20, page: 3 }, { per_page: 40, page: 2 })
      assertNext({ per_page: 40, page: 2 }, { per_page: 40, page: 2 })
      assertNext({ per_page: 40, page: 3 }, { per_page: 80, page: 2 })
      assertNext({ per_page: 80, page: 3 }, { per_page: 80, page: 3 })
      assertNext({ per_page: 80, page: 4 }, { per_page: 80, page: 4 })
      assertNext({ per_page: 80, page: 5 }, { per_page: 80, page: 5 })
      assertNext({ per_page: 80, page: 6 }, { per_page: 100, page: 5 })
    })

    it('increases page size on alignment with an initial page size of 5', () => {
      assertNext({ per_page: 5, page: 2 }, { per_page: 5, page: 2 })
      assertNext({ per_page: 5, page: 3 }, { per_page: 10, page: 2 })
    })

    it('increases page size on alignment with an initial page size of 1', () => {
      assertNext({ per_page: 1, page: 2 }, { per_page: 1, page: 2 })
      assertNext({ per_page: 1, page: 3 }, { per_page: 2, page: 2 })
      assertNext({ per_page: 2, page: 3 }, { per_page: 4, page: 2 })
      assertNext({ per_page: 4, page: 2 }, { per_page: 4, page: 2 })
      assertNext({ per_page: 4, page: 3 }, { per_page: 8, page: 2 })
      assertNext({ per_page: 8, page: 2 }, { per_page: 8, page: 2 })
      assertNext({ per_page: 8, page: 3 }, { per_page: 16, page: 2 })
      assertNext({ per_page: 16, page: 2 }, { per_page: 16, page: 2 })
      assertNext({ per_page: 16, page: 3 }, { per_page: 32, page: 2 })
      assertNext({ per_page: 32, page: 2 }, { per_page: 32, page: 2 })
      assertNext({ per_page: 32, page: 3 }, { per_page: 64, page: 2 })
    })

    it("doesn't increase page size when page size is 100", () => {
      assertNext({ per_page: 100, page: 2 }, { per_page: 100, page: 2 })
      assertNext({ per_page: 100, page: 3 }, { per_page: 100, page: 3 })
      assertNext({ per_page: 100, page: 4 }, { per_page: 100, page: 4 })
      assertNext({ per_page: 100, page: 5 }, { per_page: 100, page: 5 })
      assertNext({ per_page: 100, page: 6 }, { per_page: 100, page: 6 })
      assertNext({ per_page: 100, page: 7 }, { per_page: 100, page: 7 })
      assertNext({ per_page: 100, page: 8 }, { per_page: 100, page: 8 })
      assertNext({ per_page: 100, page: 9 }, { per_page: 100, page: 9 })
      assertNext({ per_page: 100, page: 10 }, { per_page: 100, page: 10 })
    })
  })
})


text:
package org.hisp.dhis.common;

import java.util.Random;
import java.util.regex.Pattern;

/**
 * @author bobj
 */
public class CodeGenerator
{
    public static final String letters = "abcdefghijklmnopqrstuvwxyz"
        + "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String ALLOWED_CHARS = "0123456789" + letters;

    public static final int NUMBER_OF_CODEPOINTS = ALLOWED_CHARS.length();
    public static final int CODESIZE = 11;

    private static final Pattern CODE_PATTERN = Pattern.compile( "^[a-zA-Z]{1}[a-zA-Z0-9]{10}$" );

    /**
     * Generates a pseudo random string using the allowed characters. Code is
     * 11 characters long.
     *
     * @param codeSize the number of characters in the code.
     * @return the code.
     */
    public static String generateCode()
    {
        return generateCode( CODESIZE );
    }

    /**
     * Generates a pseudo random string using the allowed characters.
     *
     * @param codeSize the number of characters in the code.
     * @return the code.
     */
    public static String generateCode( int codeSize )
    {
        Random sr = new Random();

        char[] randomChars = new char[codeSize];

        // First char should be a letter
        randomChars[0] = letters.charAt( sr.nextInt( letters.length() ) );

        for ( int i = 1; i < codeSize; ++i )
        {
            randomChars[i] = ALLOWED_CHARS.charAt( sr.nextInt( NUMBER_OF_CODEPOINTS ) );
        }

        return new String( randomChars );
    }

    /**
     * Tests whether the given code is valid.
     *
     * @param code the code to validate.
     * @return true if the code is valid.
     */
    public static boolean isValidCode( String code )
    {
        return code != null && CODE_PATTERN.matcher( code ).matches();
    }
}


text:
from rcquerybuilder.builder import Builder
from rcquerybuilder.builder import Expr
from rcquerybuilder.pipeline import PipelineExpr
from rcquerybuilder.pipeline import PipelineStage

__all__ = [
    'Builder',
    'Expr',
    'PipelineExpr',
    'PipelineStage'
]


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/window_translucent"
    tools:context="voidream.vcontroller.SettingOutputForm">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background_rounded_rectangle_grey"
        android:layout_centerInParent="true"
        android:layout_marginRight="6dp"
        android:layout_marginLeft="6dp" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="156dp"
            android:orientation="horizontal"
            android:id="@+id/linearLayout6"
            android:layout_marginRight="6dp"
            android:layout_marginLeft="6dp"
            android:layout_marginTop="6dp"
            android:background="@drawable/background_rounded_rectangle"
            android:elevation="2dp"
            android:layout_marginBottom="6dp" >

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="0.3"
                android:layout_margin="6dp"
                android:background="@drawable/background_textfield" >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview_setting_output_image_selected"
                    android:src="@drawable/out_1"
                    android:layout_centerVertical="true"
                    android:layout_centerHorizontal="true" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/dummy_number"
                    android:id="@+id/textView_output_number_output_form"
                    android:textColor="@color/text2"
                    android:layout_marginLeft="6dp"
                    android:layout_marginTop="4dp" />
            </RelativeLayout>

            <ListView
                android:layout_width="@dimen/abc_action_bar_default_height_material"
                android:layout_height="wrap_content"
                android:id="@+id/listview_output_option"
                android:background="@drawable/background_textfield"/>

        </LinearLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="156dp"
            android:layout_below="@+id/linearLayout6"
            android:id="@+id/scrollView2">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="156dp"
                android:layout_below="@+id/linearLayout6"
                android:id="@+id/linearLayout7"
                android:layout_marginBottom="6dp"
                android:background="@drawable/background_rounded_rectangle"
                android:layout_marginRight="6dp"
                android:layout_marginLeft="6dp"
                android:elevation="2dp" >

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="8dp"
                    android:layout_marginLeft="6dp"
                    android:layout_marginRight="6dp" >

                    <TextView
                        android:layout_width="64dp"
                        android:layout_height="wrap_content"
                        android:text="@string/output_name"
                        android:id="@+id/textView59"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingLeft="6dp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/double_dot"
                        android:id="@+id/textView60"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingRight="6dp" />

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="38dp"
                        android:id="@+id/editText_nama_output"
                        android:layout_marginRight="6dp"
                        android:hint="@string/output_name_hint"
                        android:textColorHint="@color/colorGrey200"
                        android:textColor="@color/text1"
                        android:textSize="14sp"
                        android:layout_gravity="center_vertical"
                        android:maxLength="14"
                        android:inputType="textWebEditText|textCapSentences"
                        android:paddingLeft="12dp"
                        android:paddingTop="6dp"
                        android:paddingRight="12dp"
                        android:paddingBottom="6dp"
                        android:background="@drawable/background_textfield"
                        android:linksClickable="false"
                        android:singleLine="false" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="8dp"
                    android:layout_marginRight="6dp"
                    android:layout_marginLeft="6dp" >

                    <TextView
                        android:layout_width="64dp"
                        android:layout_height="wrap_content"
                        android:text="@string/output_position"
                        android:id="@+id/textView61"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingLeft="6dp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/double_dot"
                        android:id="@+id/textView62"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingRight="6dp" />

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="38dp"
                        android:id="@+id/editText_posisi_output"
                        android:layout_marginRight="6dp"
                        android:background="@drawable/background_textfield"
                        android:textColor="@color/text1"
                        android:textColorHint="@color/colorGrey200"
                        android:hint="@string/output_position_hint"
                        android:textSize="14sp"
                        android:layout_gravity="center_vertical"
                        android:maxLength="11"
                        android:inputType="textCapSentences|textWebEditText"
                        android:paddingLeft="12dp"
                        android:paddingTop="6dp"
                        android:paddingRight="12dp"
                        android:paddingBottom="6dp" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="8dp"
                    android:layout_marginLeft="6dp"
                    android:layout_marginRight="6dp"
                    android:layout_marginBottom="6dp" >

                    <TextView
                        android:layout_width="64dp"
                        android:layout_height="wrap_content"
                        android:text="@string/output_power"
                        android:id="@+id/textView63"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingLeft="6dp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/double_dot"
                        android:id="@+id/textView64"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingRight="6dp" />

                    <EditText
                        android:layout_width="100dp"
                        android:layout_height="38dp"
                        android:id="@+id/editText_power_output"
                        android:layout_marginRight="6dp"
                        android:hint="@string/output_power_hint"
                        android:textColorHint="@color/colorGrey200"
                        android:background="@drawable/background_textfield"
                        android:textColor="@color/text1"
                        android:textSize="14sp"
                        android:layout_gravity="center_vertical"
                        android:maxLength="4"
                        android:inputType="numberDecimal"
                        android:paddingLeft="12dp"
                        android:paddingRight="12dp"
                        android:paddingTop="6dp"
                        android:paddingBottom="6dp" />

                    <TextView
                        android:layout_width="64dp"
                        android:layout_height="wrap_content"
                        android:text="@string/watt"
                        android:id="@+id/textView65"
                        android:textColor="@color/text2"
                        android:layout_gravity="center_vertical"
                        android:paddingLeft="6dp" />
                </LinearLayout>
            </LinearLayout>
        </ScrollView>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="54dp"
            android:layout_below="@+id/scrollView2"
            android:layout_alignRight="@+id/linearLayout6">

            <Button
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:text="@string/add"
                android:id="@+id/button_add"
                android:background="@drawable/button_flat"
                android:textColor="@android:color/white"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginBottom="6dp" />
        </RelativeLayout>

    </RelativeLayout>
</RelativeLayout>


text:
package com.kevincyt.toskeys.gui.menubar;

import com.airhacks.afterburner.views.FXMLView;

public class MenubarView extends FXMLView {

}


text:
var Q = require("q");
var _ = require("lodash");

var Manager = require('./manager').Manager;

module.exports = function(codebox) {
    codebox.logger.log("start editor sync services");

    // Create manager
    var manager = new Manager(codebox.rpc.get("fs"));

    codebox.socket.service("editorsync", function(socket) {
        var handler = _.partial(manager.handle, socket);

        // Send to sync handler
        socket.on('message', handler);
    });
};


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _styled = require('./styled');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var propTypes = {
    className: _propTypes.string,
    children: _propTypes.node,
    actionButtons: _propTypes.node
};

var defaultProps = {
    className: undefined,
    children: undefined,
    actionButtons: undefined
};

var ToolBar = function ToolBar(_ref) {
    var className = _ref.className,
        children = _ref.children,
        actionButtons = _ref.actionButtons;
    return _react2.default.createElement(
        _styled.StyledToolBar,
        { alignItems: 'center', justifyContent: 'space-between', className: className },
        _react2.default.createElement(
            _styled.ChildrenWrapper,
            { alignItems: 'center' },
            children
        ),
        actionButtons && _react2.default.createElement(
            _styled.ChildrenWrapper,
            { alignItems: 'center' },
            actionButtons
        )
    );
};

ToolBar.propTypes = propTypes;
ToolBar.defaultProps = defaultProps;

exports.default = ToolBar;


text:
{% extends "horizon/common/_modal_form.html" %}
{% load i18n %}
{% block modal-body-right %}

{% trans "Description" %}:

{% blocktrans trimmed %}
    Share networks contain network data, that will be used
    for creation of service VM, where will be hosted shares.
    {% endblocktrans %}

{% endblock %}