text:
module PageModels
  class Book < PageModels::BlinkboxbooksSection
    element :layer, 'div.book'
    element :title_element, 'h2.title'
    element :title_element_list, 'h2.title a'
    element :author_element, '[data-test^="book-authors"]', :match => :first
    element :price_element, 'span[data-test="book-price"]'
    element :discount_price_element, 'span[data-test="book-price"] span.discount'
    element :cover_image, 'div.cover'
    element :buy_now_button, '[data-test="book-buy-button"]'
    element :book_details_button, '[data-test="book-details-button"]'
    element :isbn_element, 'div.details'
    element :cover_link, '[data-test="book-title-cover"]'

    # List View elements
    element :clubcard_points, '[data-test="book-clubcard-points"]'
    element :clubcard_logo, '.club_card_logo img'

    def free?
      wait_for_price_element
      has_price_element? && price_element.text.downcase.eql?('free')
    rescue e
      logger.warn("Warning: Book '#{self.isbn}' doesn't have price or text 'free' displayed (possibly a caching issue).\n \n#{e.message}")
      false
    end

    def purchasable?
      published? && !free? && price > 0.0
    end

    def price
      if has_discount_price_element?
        wait_for_discount_price_element
        book_price = discount_price_element.text
      elsif has_price_element?
        wait_for_price_element
        book_price = price_element.text
      else
        book_price = 0
        logger.info("Book '#{title}' has no price information displayed!")
      end
      book_price.to_s.gsub(/£/, '').to_f
    end

    def isbn
      isbn_element['data-test'].scan(/[0-9]+/)[0]
    end

    def title
      wait_for_title_element
      title_element.text
    end

    def publication_date
      DateTime.parse(layer['data-test'].scan(/[0-9]{4}\-[0-9]{2}\-[0-9]{2}/)[0])
    end

    def published?
      publication_date <= DateTime.now
    end

    def click_buy_now
      mouse_over(cover_image)
      wait_for_buy_now_button
      wait_until_buy_now_button_visible
      buy_now_button.click
    end

    def click_view_details
      if parent.parent.current_view == :grid
        mouse_over(cover_image)
        wait_for_book_details_button
        wait_until_book_details_button_visible
        book_details_button.click
      else
        wait_for_title_element_list
        wait_until_title_element_list_visible
        title_element_list.click
      end
    end

    def book_details_url
      cover_link[:href]
    end

    def author
      # Some book does not have author associated to it
      # ex. https://nodejs-internal.mobcastdev.com/#!/book/9780307554468/at-fenway?q=dan%20brown
      has_author_element? ? author_element[:title] : ''
    end
  end
end


text:
{{<layout}}

{{$head}}
{{>includes/elements_head}}
{{/head}}

{{$content}}

  Back    Question 4 of 6

  <form action="question51" method="get" class="form" name="certificate">

      Please tell us how you placed your order

       <input class="selectable" id="radio-1" type="radio" name="radio-order-how" value="online" data-storage="online">
        Online

          Please provide the COL number

          <input type="text" class="form-control" id="account-number" name="account-number">

            What is a COL number

                You would have received a COL number when you made the order online. The number would have been in the email we sent you as confirmation of the order. COL numbers typically look like this HMPO45678ERF0.

                If you can't provide the COL number you may have to send copies of the certificate you ordered through the post.

        <input id="radio-2" type="radio" name="radio-order-how" value="telephone" data-storage="telephone">
        Telephone

          Please provide the account number

          <input type="text" class="form-control" id="account-number" name="account-number">

            Help finding account number

                Your account number would have been given to you when you ordered the certificate. It will have been given to you when you telephoned to make the original order. Account numbers start with HMPO and typically look like this HMPO45678ERF0

                If you can't provide the reference number you may have to send copies of the certificate you ordered through the post.

        <input id="radio-3" type="radio" name="radio-order-how" value="post" data-storage="post">
        Post

          Please provide the account number

          <input type="text" class="form-control" id="account-number" name="account-number">

            Help finding account number

                Your account number would have been given to you when you ordered the certificate. It will have been given to you when you telephoned to make the original order. Account numbers start with HMPO and typically look like this HMPO45678ERF0

                If you can't provide the reference number you may have to send copies of the certificate you ordered through the post.

    Which service did you pay for

      <input id="radio-stan" type="radio" name="service-type" value="Standard" data-storage="standard">
      Standard

      <input id="radio-pri" type="radio" name="service-type" value="Priority" data-storage="priority">
      Priority

    Please tell us the order number

    <input type="text" class="form-control" id="order-number" name="order-number">

      Help finding the order number

          Your order number would have been given to you when you ordered the certificate. It will be on any email or postal correspondence regarding the order. Orders start with HMPO and typically look like this HMPO45678ERF0

          If you can't provide the reference number you may have to send copies of the certificate you ordered through the post.

    <input type="submit" class="button" value="Continue">

</form>

{{/content}}

{{$bodyEnd}}
{{>includes/elements_scripts}}
{{/bodyEnd}}

{{/layout}}

redpajama_set_name: RedPajamaGithub


text:
package com.linkedin.drelephant.spark.fetchers

import java.net.URI
import java.text.SimpleDateFormat
import java.util.{Calendar, Date, SimpleTimeZone}

import scala.async.Async
import scala.concurrent.{ExecutionContext, Future}
import scala.io.Source
import scala.util.control.NonFatal

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.linkedin.drelephant.spark.data.SparkRestDerivedData
import com.linkedin.drelephant.spark.fetchers.statusapiv1.{ApplicationAttemptInfo, ApplicationInfo, ExecutorSummary, JobData, StageData}
import javax.ws.rs.client.{Client, ClientBuilder, WebTarget}
import javax.ws.rs.core.MediaType
import org.apache.log4j.Logger
import org.apache.spark.SparkConf

import com.bretlowery.drelephant.exceptions.{InvalidJSONResponseException, MissingHistoryServerInfoException}
import sys.process._

/**
  * A client for getting data from the Spark monitoring REST API, e.g. <https://spark.apache.org/docs/1.4.1/monitoring.html#rest-api>.
  *
  * Jersey classloading seems to be brittle (at least when testing in the console), so some of the implementation is non-lazy
  * or synchronous when needed.
  */
class SparkRestClient(sparkConf: SparkConf) {

  import SparkRestClient._
  import Async.{async, await}

  private val _CMD1 = s"hadoop version | grep mapr"
  private val DISTRO = _CMD1.!!
  private val _CMD2 = s"maprcli urls -name spark-historyserver | grep http"
  private val MAPR_HISTORYSERVERADDRESS = _CMD2.!!

  private val logger: Logger = Logger.getLogger(classOf[SparkRestClient])

  private val client: Client = ClientBuilder.newClient()

  private def cleanString(s: String): String = {
    val cleanedString = s.replaceAll("\\s+$", "").replaceFirst("/*$", "").replaceAll("[\\p{C}\\p{Z}]", "").replace("urlhttp","http")
    cleanedString
  }

  private def getHistoryServer(): URI = {
    sparkConf.getOption(HISTORY_SERVER_ADDRESS_KEY) match {
      case Some(historyServerAddress) =>
        if (historyServerAddress.slice(0, 4) == s"http") {
          val baseUri = new URI(s"${historyServerAddress}")
          require(baseUri.getPath == "")
          baseUri
        } else {
          throw new IllegalArgumentException(HISTORY_SERVER_ADDRESS_KEY + s" did not contain the Spark History Server URL as expected; can't use Spark REST API")
        }
      case _ =>
        throw new IllegalArgumentException(HISTORY_SERVER_ADDRESS_KEY + s" did not contain the Spark History Server URL as expected; can't use Spark REST API")
    }
  }

  private def getMaprHistoryServer(): URI = {
    if (DISTRO.contains(s"mapr")) {
      Option(MAPR_HISTORYSERVERADDRESS) match {
        case Some(maprUri) =>
          val baseUri = new URI(cleanString(maprUri))
          require(baseUri.getPath == "")
          baseUri
        case _ =>
          throw new IllegalArgumentException(s"<maprcli urls -name spark-historyserver> did not return the Spark History Server URL as expected; can't use Spark REST API")
      }
    } else {
      getHistoryServer()
    }
  }

  private def getAPITarget(): WebTarget = {
    if (DISTRO.contains(s"mapr")) {
      client.target(getMaprHistoryServer()).path(API_V1_MOUNT_PATH)
    } else {
      client.target(getHistoryServer()).path(API_V1_MOUNT_PATH)
    }
  }

  def fetchData(appId: String)(implicit ec: ExecutionContext): Future[SparkRestDerivedData] = {
      val appTarget = getAPITarget().path(s"applications/${appId}")
      logger.info(s"calling REST API at ${appTarget.getUri}")
 //     try {
            // Limit scope of async.
          val applicationInfo = getApplicationInfo(appId, appTarget)
          async {
              val lastAttemptId = applicationInfo.attempts.maxBy {_.startTime}.attemptId
              val attemptTarget = lastAttemptId.map(appTarget.path).getOrElse(appTarget)
              val futureJobDatas = async { getJobDatas(appId, attemptTarget) }
              val futureStageDatas = async { getStageDatas(appId, attemptTarget) }
              val futureExecutorSummaries = async { getExecutorSummaries(appId, attemptTarget) }
              SparkRestDerivedData(
                applicationInfo,
                await(futureJobDatas),
                await(futureStageDatas),
                await(futureExecutorSummaries)
              )
          }
 //     } catch {
 //       case e: com.fasterxml.jackson.core.JsonParseException =>
 //         throw new InvalidJSONResponseException(s"${appTarget.getUri} did not return valid JSON. This may be caused by either a Spark History Server crash or a recent restart of the SHS with recovery in progress. Will retry shortly.")
 //       case NonFatal(e) => throw e
 //     }
  }

  private def getApplicationInfo(appId: String, appTarget: WebTarget): ApplicationInfo = {
      get(appId, appTarget, SparkRestObjectMapper.readValue[ApplicationInfo])
  }

  private def getJobDatas(appId: String, attemptTarget: WebTarget): Seq[JobData] = {
      val target = attemptTarget.path("jobs")
      try {
        get(appId, target, SparkRestObjectMapper.readValue[Seq[JobData]])
      } catch {
        case NonFatal(e) => {
          logger.error(s"error reading JobData for ${target.getUri}")
          throw e
        }
      }
  }

  private def getStageDatas(appId: String,attemptTarget: WebTarget): Seq[StageData] = {
      val target = attemptTarget.path("stages")
      try {
        get(appId, target, SparkRestObjectMapper.readValue[Seq[StageData]])
      } catch {
        case NonFatal(e) => {
          logger.error(s"error reading StageData for ${target.getUri}")
          throw e
        }
      }
  }

  private def getExecutorSummaries(appId: String,attemptTarget: WebTarget): Seq[ExecutorSummary] = {
    val target = attemptTarget.path("executors")
    try {
      get(appId, target, SparkRestObjectMapper.readValue[Seq[ExecutorSummary]])
    } catch {
      case NonFatal(e) => {
        logger.error(s"error reading ExecutorSummaries for ${target.getUri}")
        throw e
      }
    }
  }
}

object SparkRestClient {
  val HISTORY_SERVER_ADDRESS_KEY = "spark.yarn.historyServer.address"
  val API_V1_MOUNT_PATH = "api/v1"
  val objectMapper: com.fasterxml.jackson.databind.ObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper()

  val SparkRestObjectMapper = {
    val dateFormat = {
      val iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'GMT'")
      val cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"))
      iso8601.setCalendar(cal)
      iso8601
    }
    val objectMapper = new ObjectMapper() with ScalaObjectMapper
    objectMapper.setDateFormat(dateFormat)
    objectMapper.registerModule(DefaultScalaModule)
    objectMapper
  }

  def get[T](appId: String, webTarget: WebTarget, converter: String => T): T = {
 /**
    // Read the history server response as text first rather than as json directly; then try to parse as JSON.
    // This avoids HTTP 500 errors on the converter() call should response not be JSON format.
   val txtresults = Source.fromURL(webTarget.getUri.toString()).mkString
    try {
      val jsonresults: com.fasterxml.jackson.databind.JsonNode = objectMapper.readTree(txtresults)
    } catch {
      case e: com.fasterxml.jackson.core.JsonParseException =>
        throw new InvalidJSONResponseException(s"${webTarget.getUri} did not return valid JSON. This may be caused by either a Spark History Server crash or a recent restart of the SHS with recovery in progress. Will retry shortly.")
      case NonFatal(e) => throw e
    }
  **/
    converter(webTarget.request(MediaType.APPLICATION_JSON).get(classOf[String]))
  }
}


text:
use strict;
use warnings;
use utf8;
binmode(STDOUT, ":utf8");
use FindBin;
use File::Spec;
use File::Slurp;
use lib File::Spec->catdir($FindBin::Bin, File::Spec->updir(), 'lib');
use Data::Dumper;
use POSIX;
use Getopt::Long;
use Pod::Usage;
use URI::Afthon::ItemSearch;
use MongoDB;
use Log::Minimal;

my $search = URI::Afthon::ItemSearch->new(
    'affiliateId' => '11068980.9df881e7.11068981.510ea67c',
);
$search->search( genreId => '100433', shopCode => 'sexy' );

my $client     = MongoDB::MongoClient->new(host => 'localhost', port => 27017);
my $database   = $client->get_database( 'afthon' );
my $collection = $database->get_collection( 'search' );
my $id         = $collection->insert($search->{item_list});

infof('inserted: %s', $id);

1;


text:
package org.deri.iris.builtins;

import java.util.Set;

import org.deri.iris.api.basics.IPredicate;
import org.deri.iris.api.terms.ITerm;
import org.deri.iris.basics.EqualityTypeItem;
import org.deri.iris.factory.Factory;

/**
 * Builtin to compare two terms for inequality.
 */
public class NotEqualBuiltin extends BooleanBuiltin {
    /**
     * Constructs a built-in. Two terms must be passed to the constructor,
     * otherwise an exception will be thrown.
     *
     * @param terms
     *            the terms
     */
    public NotEqualBuiltin(final ITerm... terms) {
	super(PREDICATE, terms);
    }

    protected boolean computeResult(ITerm[] terms) {
	return !BuiltinHelper.equal(terms[0], terms[1]);
    }

    /** The predicate defining this built-in. */
    private static final IPredicate PREDICATE = Factory.BASIC.createPredicate(
	    "NOT_EQUAL", 2);

    public Set<EqualityTypeItem> getEqualityType() {
	return this.getEqualityType();
    }
}


text:
gmaa-playlists
==============

Website to share Google Music All Access playlists


text:
using System.Diagnostics;
using System.Windows;
using System.Windows.Navigation;
using Accidis.Apps.Preflight.Model;
using Accidis.Apps.Preflight.Services;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ProtoBuf;

namespace Accidis.Apps.Preflight
{
	public partial class App
	{
		static readonly FeedRepository _repository = new FeedRepository();
		static AppSettings _settings;

		/// <summary>
		/// Constructor for the Application object.
		/// </summary>
		public App()
		{
			UnhandledException += OnApplicationUnhandledException;
			InitializeComponent();
			InitializePhoneApplication();

			Serializer.PrepareSerializer<Feed>();
			Serializer.PrepareSerializer<AppSettings>();

			if( Debugger.IsAttached )
			{
				// Display the current frame rate counters.
				//Current.Host.Settings.EnableFrameRateCounter = true;

				// Show the areas of the app that are being redrawn in each frame.
				//Application.Current.Host.Settings.EnableRedrawRegions = true;

				// Enable non-production analysis visualization mode,
				// which shows areas of a page that are handed off to GPU with a colored overlay.
				//Application.Current.Host.Settings.EnableCacheVisualization = true;

				// Disable the application idle detection by setting the UserIdleDetectionMode property of the
				// application's PhoneApplicationService object to Disabled.
				// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
				// and consume battery power when the user is not using the phone.
				PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
			}
		}

		public static FeedRepository Repository
		{
			get { return _repository; }
		}

		public static AppSettings Settings
		{
			get { return _settings; }
		}

		/// <summary>
		/// Provides easy access to the root frame of the Phone Application.
		/// </summary>
		/// <returns>The root frame of the Phone Application.</returns>
		public PhoneApplicationFrame RootFrame { get; private set; }

		void OnApplicationLaunching( object sender, LaunchingEventArgs e )
		{
			Debug.WriteLine( "App: Launching" );
			LoadState();
		}

		void OnApplicationActivated( object sender, ActivatedEventArgs e )
		{
			Debug.WriteLine( "App: Activated" );
			LoadState();
		}

		void OnApplicationDeactivated( object sender, DeactivatedEventArgs e )
		{
			Debug.WriteLine( "App: Deactivated" );
			PersistState();
		}

		void OnApplicationClosing( object sender, ClosingEventArgs e )
		{
			Debug.WriteLine( "App: Closing" );
			PersistState();
		}

		static void LoadState()
		{
			if( !AppSettings.TryLoad( out _settings ) )
				_settings = new AppSettings();

			Repository.LoadOfflineFeed();
		}

		static void PersistState()
		{
			AppSettings.Persist( _settings );
			Repository.PersistOfflineFeed();
		}

		// Code to execute if a navigation fails
		static void OnRootFrameNavigationFailed( object sender, NavigationFailedEventArgs e )
		{
			if( Debugger.IsAttached )
				Debugger.Break();
		}

		// Code to execute on Unhandled Exceptions
		static void OnApplicationUnhandledException( object sender, ApplicationUnhandledExceptionEventArgs e )
		{
			if( Debugger.IsAttached )
				Debugger.Break();
		}

		#region Phone application initialization

		// Avoid double-initialization
		bool _phoneApplicationInitialized;

		// Do not add any additional code to this method
		void InitializePhoneApplication()
		{
			if( _phoneApplicationInitialized )
				return;

			// Create the frame but don't set it as RootVisual yet; this allows the splash
			// screen to remain active until the application is ready to render.
			RootFrame = new TransitionFrame();
			RootFrame.Navigated += CompleteInitializePhoneApplication;

			// Handle navigation failures
			RootFrame.NavigationFailed += OnRootFrameNavigationFailed;

			// Ensure we don't initialize again
			_phoneApplicationInitialized = true;
		}

		// Do not add any additional code to this method
		void CompleteInitializePhoneApplication( object sender, NavigationEventArgs e )
		{
			// Set the root visual to allow the application to render
			if( RootVisual != RootFrame )
				RootVisual = RootFrame;

			// Remove this handler since it is no longer needed
			RootFrame.Navigated -= CompleteInitializePhoneApplication;
		}

		#endregion
	}
}


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_file_lockedfile_h__
#define mozilla_dom_file_lockedfile_h__

#include "FileCommon.h"

#include "nsIDOMLockedFile.h"
#include "nsIRunnable.h"

#include "nsDOMEventTargetHelper.h"

class nsIInputStream;

BEGIN_FILE_NAMESPACE

class FileHandle;
class FileRequest;
class MetadataHelper;

class LockedFile : public nsDOMEventTargetHelper,
                   public nsIDOMLockedFile,
                   public nsIRunnable
{
  friend class FinishHelper;
  friend class FileService;
  friend class FileHelper;
  friend class MetadataHelper;

public:
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_NSIDOMLOCKEDFILE
  NS_DECL_NSIRUNNABLE

  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(LockedFile, nsDOMEventTargetHelper)

  enum Mode
  {
    READ_ONLY = 0,
    READ_WRITE
  };

  enum RequestMode
  {
    NORMAL = 0, // Sequential
    PARALLEL
  };

  enum ReadyState
  {
    INITIAL = 0,
    LOADING,
    FINISHING,
    DONE
  };

  static already_AddRefed<LockedFile>
  Create(FileHandle* aFileHandle,
         Mode aMode,
         RequestMode aRequestMode = NORMAL);

  // nsIDOMEventTarget
  virtual nsresult
  PreHandleEvent(nsEventChainPreVisitor& aVisitor);

  nsresult
  CreateParallelStream(nsISupports** aStream);

  nsresult
  GetOrCreateStream(nsISupports** aStream);

  bool
  IsOpen() const;

  bool
  IsAborted() const
  {
    return mAborted;
  }

  FileHandle*
  Handle() const
  {
    return mFileHandle;
  }

  nsresult
  OpenInputStream(bool aWholeFile, PRUint64 aStart, PRUint64 aLength,
                  nsIInputStream** aResult);

private:
  LockedFile();
  ~LockedFile();

  void
  OnNewRequest();

  void
  OnRequestFinished();

  inline already_AddRefed<FileRequest>
  GenerateFileRequest();

  nsresult
  WriteOrAppend(const jsval& aValue, JSContext* aCx,
                nsIDOMFileRequest** _retval, bool aAppend);

  nsresult
  Finish();

  nsRefPtr<FileHandle> mFileHandle;
  ReadyState mReadyState;
  Mode mMode;
  RequestMode mRequestMode;
  PRUint64 mLocation;
  PRUint32 mPendingRequests;

  NS_DECL_EVENT_HANDLER(complete)
  NS_DECL_EVENT_HANDLER(abort)
  NS_DECL_EVENT_HANDLER(error)

  nsTArray<nsCOMPtr<nsISupports> > mParallelStreams;
  nsCOMPtr<nsISupports> mStream;

  bool mAborted;
  bool mCreating;
};

class FinishHelper : public nsIRunnable
{
  friend class LockedFile;

public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIRUNNABLE

private:
  FinishHelper(LockedFile* aLockedFile);
  ~FinishHelper()
  { }

  nsRefPtr<LockedFile> mLockedFile;
  nsTArray<nsCOMPtr<nsISupports> > mParallelStreams;
  nsCOMPtr<nsISupports> mStream;

  bool mAborted;
};

END_FILE_NAMESPACE

#endif // mozilla_dom_file_lockedfile_h__


text:
using System;
using System.Linq;
using System.Net;
using Inforigami.Regalo.AzureTableStorage;
using Inforigami.Regalo.Core;
using Inforigami.Regalo.EventSourcing.Tests.Unit.DomainModel.Customers;
using Inforigami.Regalo.Interfaces;
using Inforigami.Regalo.Testing;
using NUnit.Framework;
using ILogger = Inforigami.Regalo.Core.ILogger;

namespace Inforigami.Regalo.EventSourcing.Tests.Unit
{
    [TestFixture]
    public class PersistenceTests
    {
        private ILogger _logger;

        [SetUp]
        public void SetUp()
        {
            _logger = new ConsoleLogger();

            Resolver.Configure(
                type =>
                {
                    if (type == typeof(ILogger))
                    {
                        return _logger;
                    }

                    throw new InvalidOperationException($"No type of {type} registered.");
                },
                type => null,
                o => { });
        }

        [TearDown]
        public void TearDown()
        {
            Conventions.SetFindAggregateTypeForEventType(null);

            Resolver.Reset();

            _logger = null;
        }

        [Test]
        public void Loading_GivenEmptyStore_ShouldReturnNull()
        {
            // Arrange
            IEventStore store = NewEventStore();

            // Act
            EventStream<Customer> events = store.Load<Customer>(Guid.NewGuid().ToString());

            // Assert
            Assert.That(events, Is.Null);
        }

        [Test]
        public void Saving_GivenSingleEvent_ShouldAllowReloading()
        {
            // Arrange
            var store = NewEventStore();

            // Act
            var id = Guid.NewGuid();
            var evt = new CustomerSignedUp(id);
            store.Save<Customer>(id.ToString(), EntityVersion.New, new[] { evt });
            store.Flush();
            var stream = store.Load<Customer>(id.ToString());

            // Assert
            Assert.NotNull(stream);
            CollectionAssert.AreEqual(
                new object[] { evt },
                stream.Events,
                "Events reloaded from store do not match those generated by aggregate.");
        }

        [Test]
        public void Saving_GivenSingleEventNotFlushed_ShouldAllowReloading()
        {
            // Arrange
            var store = NewEventStore();

            // Act
            var id = Guid.NewGuid();
            var evt = new CustomerSignedUp(id);
            store.Save<Customer>(id.ToString(), EntityVersion.New, new[] { evt });
            //store.Flush();
            var stream = store.Load<Customer>(id.ToString());

            // Assert
            Assert.NotNull(stream);
            CollectionAssert.AreEqual(
                new object[] { evt },
                stream.Events,
                "Events reloaded from store do not match those generated by aggregate.");
        }

        [Test]
        public void Saving_GivenEventWithGuidProperty_ShouldAllowReloadingToGuidType()
        {
            // Arrange
            var store = NewEventStore();

            var customer = new Customer();
            customer.Signup();

            var accountManager = new AccountManager();
            var startDate = new DateTime(2012, 4, 28);
            accountManager.Employ(startDate);

            customer.AssignAccountManager(accountManager.Id, startDate);

            store.Save<Customer>(customer.Id.ToString(), EntityVersion.New, customer.GetUncommittedEvents());
            store.Flush();

            // Act
            var acctMgrAssignedEvent = (AccountManagerAssigned)store.Load<Customer>(customer.Id.ToString())
                                                                    .Events
                                                                    .LastOrDefault();

            // Assert
            Assert.NotNull(acctMgrAssignedEvent);
            Assert.AreEqual(accountManager.Id, acctMgrAssignedEvent.AccountManagerId);
        }

        [Test]
        public void Saving_GivenEvents_ShouldAllowReloading()
        {
            // Arrange
            var store = NewEventStore();

            // Act
            var customer = new Customer();
            customer.Signup();
            store.Save<Customer>(customer.Id.ToString(), EntityVersion.New, customer.GetUncommittedEvents());
            store.Flush();
            var stream = store.Load<Customer>(customer.Id.ToString());

            // Assert
            Assert.NotNull(stream);
            CollectionAssert.AreEqual(customer.GetUncommittedEvents(), stream.Events, "Events reloaded from store do not match those generated by aggregate.");
        }

        [Test]
        public void Saving_GivenNoEvents_ShouldDoNothing()
        {
            // Arrange
            var store = NewEventStore();

            // Act
            var id = Guid.NewGuid();
            store.Save<Customer>(id.ToString(), EntityVersion.New, Enumerable.Empty<IEvent>());
            var stream = store.Load<Customer>(id.ToString());

            // Assert
            Assert.That(stream, Is.Null);
        }

        [Test]
        [TestCase(0)]
        [TestCase(1)]
        [TestCase(2)]
        public void GivenAggregateWithMultipleEvents_WhenLoadingSpecificVersion_ThenShouldOnlyReturnRequestedEvents(int version)
        {
            // Arrange
            var store = NewEventStore();
            var customerId = Guid.NewGuid();
            var storedEvents = new EventChain().Add(new CustomerSignedUp(customerId))
                                               .Add(new SubscribedToNewsletter("latest"))
                                               .Add(new SubscribedToNewsletter("top"));
            store.Save<Customer>(customerId.ToString(), EntityVersion.New, storedEvents);
            store.Flush();

            // Act
            var stream = store.Load<Customer>(customerId.ToString(), version);

            // Assert
            CollectionAssert.AreEqual(storedEvents.Take(version + 1), stream.Events, "Events loaded from store do not match version requested.");
        }

        [Test]
        public void GivenAggregateWithMultipleEvents_WhenLoadingMaxVersion_ThenShouldReturnAllEvents()
        {
            // Arrange
            var store = NewEventStore();
            var customerId = Guid.NewGuid();
            var storedEvents = new EventChain().Add(new CustomerSignedUp(customerId))
                                               .Add(new SubscribedToNewsletter("latest"))
                                               .Add(new SubscribedToNewsletter("top"));
            store.Save<Customer>(customerId.ToString(), EntityVersion.New, storedEvents);
            store.Flush();

            // Act
            var stream = store.Load<Customer>(customerId.ToString(), EntityVersion.Latest);

            // Assert
            CollectionAssert.AreEqual(storedEvents, stream.Events, "Events loaded from store do not match version requested.");
        }

        [Test]
        public void GivenAggregateWithMultipleEvents_WhenLoadingSpecificVersionThatNoEventHas_ThenShouldFail()
        {
            // Arrange
            var store = NewEventStore();
            var customerId = Guid.NewGuid();
            var storedEvents = new EventChain
                              {
                                  new CustomerSignedUp(customerId),
                                  new SubscribedToNewsletter("latest"),
                                  new SubscribedToNewsletter("top")
                              };
            store.Save<Customer>(customerId.ToString(), EntityVersion.New, storedEvents);
            store.Flush();

            // Act / Assert
            Assert.Throws<ArgumentOutOfRangeException>(() => store.Load<Customer>(customerId.ToString(), 10));
        }

        [Test]
        public void GivenAggregateWithMultipleEvents_WhenLoadingSpecialNoStreamVersion_ThenShouldFail()
        {
            // Arrange
            var store = NewEventStore();
            var customerId = Guid.NewGuid();
            var storedEvents = new EventChain
                              {
                                  new CustomerSignedUp(customerId),
                                  new SubscribedToNewsletter("latest"),
                                  new SubscribedToNewsletter("top")
                              };
            store.Save<Customer>(customerId.ToString(), EntityVersion.New, storedEvents);

            // Act / Assert
            Assert.Throws<ArgumentOutOfRangeException>(() => store.Load<Customer>(customerId.ToString(), EntityVersion.New));
        }

        private AzureTableStorageEventStore NewEventStore()
        {
            var name = GetEnvironmentVariable("Inforigami_Regalo_AzureTableStorage_UnitTest_AzureStorageAccountName");
            var key  = GetEnvironmentVariable("Inforigami_Regalo_AzureTableStorage_UnitTest_AzureStorageAccountKey");
            return new AzureTableStorageEventStore(name, key, _logger);
        }

        private static string GetEnvironmentVariable(string envVarName)
        {
            var result = Environment.GetEnvironmentVariable(envVarName, EnvironmentVariableTarget.User);
            if (string.IsNullOrWhiteSpace(result))
            {
                throw new InvalidOperationException(
                    $@"Unable to find USER environment variable value for {envVarName}");
            }
            return result;
        }
    }
}


text:
package com.chunyu.base;

/**
 * description : $todo
 * autour      : 姜春雨@沈阳
 * date        : 17-3-24 下午1:40
 * mail        : 1055655886@qq.com
 */

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;

import com.chunyu.contant.Contant;
import com.chunyu.impl.ReceiverListener;

/**
 * description : 进程间通讯基础类
 * autour      : 姜春雨@沈阳
 * date        : 17-3-24 下午1:41
 * mail        : 1055655886@qq.com
 */
public abstract class BaseIPCService extends Service {
    protected ReceiverListener mReceiverListener;

    @Override
    public IBinder onBind(Intent intent) {
        return mIPCBinder;
    }
    private IPCBinder mIPCBinder = new IPCBinder();

    /**
     * description : 自定义Binder实现消息传递
     * autour      : 姜春雨@沈阳
     * date        : 17-3-24 上午10:33
     * mail        : 1055655886@qq.com
     */
    public class IPCBinder extends Binder {

        /**
         *  处理消息
         * @param code 识别码
         * @param data 调用transact的对象传送过去的参数
         * @param reply 调用onTransact的对象返回的参数
         * @param flags Java里面默认的native方法都是阻塞的,当不需要阻塞的时候设置为IBinder.FLAG_ONEWAY,否则设置为0
         * @return
         * @throws RemoteException
         */
        @Override
        protected boolean onTransact(final int code, final Parcel data, final Parcel reply, final int flags) throws RemoteException {
            data.enforceInterface(Contant.DESCRIPTOR);
            Bundle bundle = dealMessage(code,data.readBundle());
            reply.writeNoException();
            reply.writeBundle(bundle);
            return true;
        }

        /**
         * 获取当前Service,用于与Service通信
         * @return
         */
        public BaseIPCService getService(){
            return BaseIPCService.this;
        }
    }

    public void setReceiverListener(ReceiverListener receiverListener) {
        mReceiverListener = receiverListener;
    }

    public abstract Bundle dealMessage(int code, Bundle msg);

}


text:
"%programfiles(x86)%\MSBuild\12.0\Bin\MSBuild.exe" buildall.proj
pause


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Chat
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package openapi

import (
	"time"
)

// ChatV1Service struct for ChatV1Service
type ChatV1Service struct {
	// The unique string that identifies the resource
	Sid *string `json:"sid,omitempty"`
	// The SID of the Account that created the resource
	AccountSid *string `json:"account_sid,omitempty"`
	// The string that you assigned to describe the resource
	FriendlyName *string `json:"friendly_name,omitempty"`
	// The RFC 2822 date and time in GMT when the resource was created
	DateCreated *time.Time `json:"date_created,omitempty"`
	// The RFC 2822 date and time in GMT when the resource was last updated
	DateUpdated *time.Time `json:"date_updated,omitempty"`
	// The service role assigned to users when they are added to the service
	DefaultServiceRoleSid *string `json:"default_service_role_sid,omitempty"`
	// The channel role assigned to users when they are added to a channel
	DefaultChannelRoleSid *string `json:"default_channel_role_sid,omitempty"`
	// The channel role assigned to a channel creator when they join a new channel
	DefaultChannelCreatorRoleSid *string `json:"default_channel_creator_role_sid,omitempty"`
	// Whether the Message Consumption Horizon feature is enabled
	ReadStatusEnabled *bool `json:"read_status_enabled,omitempty"`
	// Whether the Reachability Indicator feature is enabled for this Service instance
	ReachabilityEnabled *bool `json:"reachability_enabled,omitempty"`
	// How long in seconds to wait before assuming the user is no longer typing
	TypingIndicatorTimeout *int `json:"typing_indicator_timeout,omitempty"`
	// DEPRECATED
	ConsumptionReportInterval *int `json:"consumption_report_interval,omitempty"`
	// An object that describes the limits of the service instance
	Limits *interface{} `json:"limits,omitempty"`
	// An object that contains information about the webhooks configured for this service
	Webhooks *interface{} `json:"webhooks,omitempty"`
	// The webhook URL for pre-event webhooks
	PreWebhookUrl *string `json:"pre_webhook_url,omitempty"`
	// The URL for post-event webhooks
	PostWebhookUrl *string `json:"post_webhook_url,omitempty"`
	// The HTTP method  to use for both PRE and POST webhooks
	WebhookMethod *string `json:"webhook_method,omitempty"`
	// The list of WebHook events that are enabled for this Service instance
	WebhookFilters *[]string `json:"webhook_filters,omitempty"`
	// The notification configuration for the Service instance
	Notifications *interface{} `json:"notifications,omitempty"`
	// The absolute URL of the Service resource
	Url *string `json:"url,omitempty"`
	// The absolute URLs of the Service's Channels, Roles, and Users
	Links *map[string]interface{} `json:"links,omitempty"`
}


text:
using System;
using System.Net.NetworkInformation;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        Ping pinger = new Ping();
        while (true)
        {
            if (pinger.Send("8.8.8.8").Status == IPStatus.Success)
            {
                Console.Beep(4000, 60);
            }
            Thread.Sleep(1000);
        }
    }
}


text:
A container that allows creation of event

### Example Usage

```js
<CreateEventContainer  />
```

### Other Information
See ./index.js for implementation details


text:
package com.yelpdatasetchallenge.dataprocessing;

/**
 * @author feiyu
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.yelpdatasetchallenge.objects.BusinessHM;

import driven.com.fasterxml.jackson.annotation.PropertyAccessor;
import driven.com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import driven.com.fasterxml.jackson.databind.JsonNode;
import driven.com.fasterxml.jackson.databind.ObjectMapper;
import driven.com.fasterxml.jackson.databind.node.ArrayNode;

public class DataStoreHashMap extends DataStore implements BusinessCheckInWindowInterface {

  public DataStoreHashMap(String logFilePath, String businessFilePath, String checkinFilePath)
      throws Exception {
    super(logFilePath, businessFilePath, checkinFilePath);
  }

  private Map<String, JsonNode> businessHM = new HashMap<String, JsonNode>();
  private Map<String, JsonNode> checkInHourWeekHM = new HashMap<String, JsonNode>();

  @Override
  public void saveBusinessInfoToDataStore() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(businessFilePath));
    ObjectMapper mapper = new ObjectMapper();

    try {
      String line = br.readLine();
      while (line != null) {
        JsonNode actualObj = mapper.readTree(line);
        JsonNode businessID = actualObj.get("business_id");
        System.out.println("key:"+businessID.asText());//+", value:"+actualObj);
        businessHM.put(businessID.asText(), actualObj);

        line = br.readLine();
      }
    } finally {
      br.close();
    }
    logWriter.println("6TPxhpHqFedjMvBuw6pF3w : "+businessHM.get("6TPxhpHqFedjMvBuw6pF3w"));
    logWriter.println("num of business: "+ businessHM.size());
  }

  @Override
  public void getBusinessCheckInInfo() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(checkinFilePath));
    ObjectMapper mapper = new ObjectMapper();

    try {
      String line = br.readLine();
      while (line != null) {
        JsonNode actualObj = mapper.readTree(line);
        JsonNode businessID = actualObj.get("business_id");
        JsonNode checkinInfoObj = actualObj.get("checkin_info");
        System.out.println(checkinInfoObj);

        // iterate check-in info of each business and put <hour-week:[{business_id:_,count:_,},{business_id:_,count:_,},..]> into checkInHourWeekHM
        Iterator<Map.Entry<String,JsonNode>> fields = checkinInfoObj.fields();
        while (fields.hasNext()) {
          Map.Entry<String,JsonNode> field = fields.next();
          String key = field.getKey();
          JsonNode value = field.getValue();

          BusinessHM b = new BusinessHM();
          b.setBusinessID(businessID.asText());
          b.setCheckInCountTimeWindow(value.asText());
          ObjectMapper businessMapper = new ObjectMapper();
          businessMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

          List<BusinessHM> businessAryList = new ArrayList<BusinessHM>();
          businessAryList.add(b);
          JsonNode businessJsonAry = businessMapper.valueToTree(businessAryList);

          if (checkInHourWeekHM.containsKey(key)) {
            businessJsonAry = checkInHourWeekHM.get(key);
            // System.out.println(businessJsonAry);
            ((ArrayNode)businessJsonAry).add(businessMapper.valueToTree(b));
          }
          // System.out.println(key+"-----"+businessJsonAry);
          checkInHourWeekHM.put(key, businessJsonAry);
        }
        line = br.readLine();
      }
    } finally {
      br.close();
    }
    logWriter.println("value: "+checkInHourWeekHM.get("17-3"));
    logWriter.println("Size of checkInHourWeekHM: "+checkInHourWeekHM.size());
    /*
        Iterator it = checkInHourWeekHM.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            logWriter.println(pair.getKey() + " = " + pair.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }
     */
  }

  @Override
  public void callMethods() throws IOException {
    saveBusinessInfoToDataStore();
    getBusinessCheckInInfo();
  }

  public static void main(String[] argv) throws Exception {
    DataStoreHashMap dshm = new DataStoreHashMap(
      "src/main/resources/yelp-dataset/log_HashMap_yelp_academic_dataset.txt",
      "src/main/resources/yelp-dataset/yelp_academic_dataset_business.json",
        "src/main/resources/yelp-dataset/yelp_academic_dataset_checkin.json");
    dshm.run();
  }
}


text:
kan-extensions
==============

[![Hackage](https://img.shields.io/hackage/v/kan-extensions.svg)](https://hackage.haskell.org/package/kan-extensions) [![Build Status](https://secure.travis-ci.org/ekmett/kan-extensions.png?branch=master)](http://travis-ci.org/ekmett/kan-extensions)

This package provides tools for working with various Kan extensions and Kan lifts in Haskell.

Among the interesting bits included are:

* Right and left Kan extensions (`Ran` and `Lan`)
* Right and left Kan lifts (`Rift` and `Lift`)
* Multiple forms of the Yoneda lemma (`Yoneda`)
* The `Codensity` monad, which can be used to improve the asymptotic complexity of code over free monads (`Codensity`, `Density`)
* A "comonad to monad-transformer transformer" that is a special case of a right Kan lift. (`CoT`, `Co`)

Contact Information
-------------------

Contributions and bug reports are welcome!

Please feel free to contact me through github or on the #haskell IRC channel on irc.freenode.net.

-Edward Kmett


text:
declare module 'react-native/Libraries/Core/Devtools/parseErrorStack' {
    export type StackFrame = {
        file: string;
        methodName: string;
        lineNumber: number;
        column: number | null;
    };

    export interface ExtendedError extends Error {
        framesToPop?: number;
    }

    export default function parseErrorStack(error: ExtendedError): StackFrame[];
}

declare module 'react-native/Libraries/Core/Devtools/symbolicateStackTrace' {
    import { StackFrame } from 'react-native/Libraries/Core/Devtools/parseErrorStack';

    export default function symbolicateStackTrace(
        stack: ReadonlyArray<StackFrame>
    ): Promise<StackFrame[]>;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Encoding Hint: 雀の往来 -->
<project>
 <property name="jnlp.title"    value="JST 最終行のみ編集可能" />
 <property name="jnlp.Name"     value="LastLineEditableTextArea" />
 <property name="jnlp.name"     value="lastlineeditabletextarea" />
 <property name="jnlp.codebase" value="http://ateraimemo.com/swing/${jnlp.name}/" />
 <property name="jnlp.homepage" value="http://ateraimemo.com/Swing/${jnlp.Name}.html" />
</project>


text:
<?php

namespace frontend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class MaterialAsset extends AssetBundle
{
    public $sourcePath = '@frontend/themes/material';
    public $baseUrl = '@frontend/web';
    public $css = [
        'css/material-wfont.min.css',
        'css/material.min.css',
        'css/ripples.min.css',
        //'css/navbar.css',

    ];
    public $js = [
        'js/material.min.js',
        'js/ripples.min.js'
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}


text:
class CreateNewRulesTable < ActiveRecord::Migration
  def change
    create_table :rules do |t|
      t.string :public_id
      t.references :transaction, index: true, foreign_key: true
    end
  end
end


text:
echo "making dir ./apk-repository"
mkdir apk-repository

echo "installing apk-updater"
npm install

echo "patching apk-updater"
patch -p0 < patch.d

echo "done."


text:
$(function(){
	$("#filename").change(function(){
		$("#filename-preview").fadeOut(500, function() {
			$("#filename-preview").attr("src", $.path.preset + $("#filename").val());
			$("#filename-preview").fadeIn(500);
		});
	});
});


text:
extern crate byteorder;
use byteorder::{LittleEndian, BigEndian, ReadBytesExt};

use std::collections::HashMap;
use std::io::{self, Read, Seek, SeekFrom, BufRead, BufReader};
use std::fs::File;
use std::cell::RefCell;

pub mod errors;
use errors::ReadError;

pub struct BigArchive<T: Read + Seek> {
    pub format: Format,
    pub size: u32,

    _buf_reader: RefCell<BufReader<T>>,
    _junk_len: u32,
    _entries: HashMap<String, BigEntry>,
}

impl BigArchive<File> {
    pub fn new_from_path(path: &str) -> Result<Self, ReadError> {
        let f = try!(File::open(&path));
        let br = BufReader::new(f);
        Ok(try!(BigArchive::new(br)))
    }
}

impl<T: Read + Seek> BigArchive<T> {
    pub fn new(mut data: BufReader<T>) -> Result<Self, ReadError> {
        let format = try!(read_format(&mut data));

        if let Format::Unknown(bytes) = format {
            return Err(ReadError::UnknownArchiveFormat(bytes));
        }

        let archive_len = try!(data.read_u32::<LittleEndian>());
        let num_entries = try!(data.read_u32::<BigEndian>());
        let first_offset = try!(data.read_u32::<BigEndian>());
        let mut pos = 16;

        let mut entries = HashMap::new();

        for _ in 0..num_entries {
            let offset = try!(data.read_u32::<BigEndian>());
            let data_len = try!(data.read_u32::<BigEndian>());

            let mut buf = Vec::new();
            let name_len = try!(data.read_until(b'\0', &mut buf));

            let entry = BigEntry {
                offset: offset,
                data_len: data_len,
                name: String::from_utf8_lossy(&buf[..name_len - 1]).to_string(),
            };

            entries.insert(entry.name.clone(), entry);

            let entry_metadata_len = 4 + 4 + name_len as u32;
            pos += entry_metadata_len;
        }

        let junk_len = first_offset - pos
        // Patching an off-by-one. Need to revisit and fix this properly.
        + 1;

        Ok(BigArchive {
            format: format,
            size: archive_len,
            _buf_reader: RefCell::new(data),
            _junk_len: junk_len,
            _entries: entries,
        })
    }

    pub fn junk_len(&self) -> u32 {
        self._junk_len
    }

    pub fn entry_count(&self) -> usize {
        self._entries.len()
    }

    /// TODO: Don't return owned data, instead give the caller back a slice
    pub fn read_entry(&self, entry_name: &str) -> Option<Vec<u8>> {
        if let Some(entry) = self._entries.get(entry_name) {
            let br = &mut self._buf_reader.borrow_mut();

            if br.seek(SeekFrom::Start((*entry).offset as u64)).is_err() {
                return None;
            }

            let mut buf = vec![0; entry.data_len as usize];
            if br.read_exact(&mut buf).is_err() {
                return None;
            }

            Some(buf)
        } else {
            None
        }
    }

    pub fn contains(&self, entry_name: &str) -> bool {
        self._entries.contains_key(entry_name)
    }

    pub fn get_entry(&self, entry_name: &str) -> Option<&BigEntry> {
        self._entries.get(entry_name)
    }

    pub fn get_entry_mut(&mut self, entry_name: &str) -> Option<&mut BigEntry> {
        self._entries.get_mut(entry_name)
    }

    pub fn get_all_entry_names(&self) -> std::collections::hash_map::Keys<String, BigEntry> {
        self._entries.keys()
    }
}

#[derive(Debug)]
pub struct BigEntry {
    pub offset: u32,
    pub data_len: u32,
    pub name: String,
}

#[derive(Debug, PartialEq)]
pub enum Format {
    Unknown(Vec<u8>),
    Big4,
    BigF,
}

impl<'a> From<&'a mut BufRead> for Format {
    fn from(data: &'a mut BufRead) -> Self {
        let mut buf = [0; 4];
        let _ = data.read_exact(&mut buf);
        match &buf {
            b"BIG4" => Format::Big4,
            b"BIGF" => Format::BigF,
            _ => Format::Unknown(Vec::from(&buf[..])),
        }
    }
}

fn read_format(data: &mut BufRead) -> Result<Format, io::Error> {
    Ok(Format::from(data))
}

#[cfg(test)]
mod tests_bytes {
    const TEST_BYTES: &'static [u8] = include_bytes!("../test.big");
    use std::io::{BufReader, Cursor};
    use super::{Format, BigArchive};

    #[test]
    fn is_big4() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert_eq!(archive.format, Format::Big4);
    }

    #[test]
    fn has_two_entries() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert_eq!(archive.get_all_entry_names().len(), 2);
    }

    #[test]
    fn contains_art_slash_image_dot_txt() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert!(archive.contains("art/image.txt"));
    }

    #[test]
    fn contains_data_slash_test_dot_ini() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        assert!(archive.contains("data/test.ini"));
    }

    #[test]
    fn read_entry_art_slash_image_dot_txt() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        let data = archive.read_entry("art/image.txt").unwrap();
        assert_eq!(data, vec![98, 108, 97, 98, 108, 98, 97]);
    }

    #[test]
    fn read_entry_data_slash_test_dot_ini() {
        let c = Cursor::new(TEST_BYTES);
        let br = BufReader::new(c);
        let archive = BigArchive::new(br).unwrap();
        let data = archive.read_entry("data/test.ini").unwrap();
        assert_eq!(data,
                   vec![84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 105, 109, 112, 108,
                        101, 32, 116, 101, 115, 116, 32, 102, 105, 108, 101]);
    }

    mod benches {
        extern crate test;
        use self::test::Bencher;

        #[bench]
        fn is_big4(b: &mut Bencher) {
            b.iter(|| super::is_big4());
        }

        #[bench]
        fn has_two_entries(b: &mut Bencher) {
            b.iter(|| super::has_two_entries());
        }

        #[bench]
        fn contains_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::contains_art_slash_image_dot_txt());
        }

        #[bench]
        fn contains_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::contains_data_slash_test_dot_ini());
        }

        #[bench]
        fn read_entry_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::read_entry_art_slash_image_dot_txt());
        }

        #[bench]
        fn read_entry_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::read_entry_data_slash_test_dot_ini());
        }
    }
}

#[cfg(test)]
mod tests_file {
    use super::{Format, BigArchive};
    const ARCHIVE_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/test.big");

    #[test]
    fn is_big4() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert_eq!(archive.format, Format::Big4);
    }

    #[test]
    fn has_two_entries() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert_eq!(archive.get_all_entry_names().len(), 2);
    }

    #[test]
    fn contains_art_slash_image_dot_txt() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert!(archive.contains("art/image.txt"));
    }

    #[test]
    fn contains_data_slash_test_dot_ini() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        assert!(archive.contains("data/test.ini"));
    }

    #[test]
    fn read_entry_art_slash_image_dot_txt() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        let data = archive.read_entry("art/image.txt").unwrap();
        assert_eq!(data, vec![98, 108, 97, 98, 108, 98, 97]);
    }

    #[test]
    fn read_entry_data_slash_test_dot_ini() {
        let archive = BigArchive::new_from_path(&ARCHIVE_PATH).unwrap();
        let data = archive.read_entry("data/test.ini").unwrap();
        assert_eq!(data,
                   vec![84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 105, 109, 112, 108,
                        101, 32, 116, 101, 115, 116, 32, 102, 105, 108, 101]);
    }

    mod benches {
        extern crate test;
        use self::test::Bencher;

        #[bench]
        fn is_big4(b: &mut Bencher) {
            b.iter(|| super::is_big4());
        }

        #[bench]
        fn has_two_entries(b: &mut Bencher) {
            b.iter(|| super::has_two_entries());
        }

        #[bench]
        fn contains_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::contains_art_slash_image_dot_txt());
        }

        #[bench]
        fn contains_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::contains_data_slash_test_dot_ini());
        }

        #[bench]
        fn read_entry_art_slash_image_dot_txt(b: &mut Bencher) {
            b.iter(|| super::read_entry_art_slash_image_dot_txt());
        }

        #[bench]
        fn read_entry_data_slash_test_dot_ini(b: &mut Bencher) {
            b.iter(|| super::read_entry_data_slash_test_dot_ini());
        }
    }
}


text:
CAppEditorReactor::CAppEditorReactor (const bool autoInitAndRelease) : AcEditorReactor(), mbAutoInitAndRelease(autoInitAndRelease) {
	if ( autoInitAndRelease ) {
		if ( acedEditor )
			acedEditor->addReactor (this) ;
		else
			mbAutoInitAndRelease =false ;
	}
}

//-----------------------------------------------------------------------------
CAppEditorReactor::~CAppEditorReactor () {
	Detach () ;
}

//-----------------------------------------------------------------------------
void CAppEditorReactor::Attach () {
	Detach () ;
	if ( !mbAutoInitAndRelease ) {
		if ( acedEditor ) {
			acedEditor->addReactor (this) ;
			mbAutoInitAndRelease =true ;
		}
	}
}

void CAppEditorReactor::Detach () {
	if ( mbAutoInitAndRelease ) {
		if ( acedEditor ) {
			acedEditor->removeReactor (this) ;
			mbAutoInitAndRelease =false ;
		}
	}
}

AcEditor *CAppEditorReactor::Subject () const {
	return (acedEditor) ;
}

bool CAppEditorReactor::IsAttached () const {
	return (mbAutoInitAndRelease) ;
}

// -----------------------------------------------------------------------------
void CAppEditorReactor::databaseConstructed(AcDbDatabase * param2)
{
	CObjectAppendToDb::databaseConstructed(param2);
	AcEditorReactor::databaseConstructed (param2) ;
}

// -----------------------------------------------------------------------------
void CAppEditorReactor::databaseToBeDestroyed(AcDbDatabase * param2)
{
	CObjectAppendToDb::databaseDestroyed(param2);
	AcEditorReactor::databaseToBeDestroyed (param2) ;
}


text:
class EventsController < ApplicationController
  include SkinnyControllers::Diet

  # respond_to :json

  def index
    render json: model
  end

  def show
    render json: model
  end

  def create
    render json: model
  end

  def update
    render json: model
  end

  def destroy
    render json: model
  end

  # renders false, because the user doesn't have permission
  def throw_away
    render json: model
  end

  def load_hack
    # go-go-gadget rails autoload

    # rubocop:disable Lint/Void
    EventOperations
    EventPolicy
    # rubocop:enable Lint/Void

    render json: {}
  end

  def event_params
    params.permit!
    params
  end
end