text:
#include "config.h"
#include "WebProcess.h"

#include "WebKit2Initialize.h"
#include <QGuiApplication>
#include <QList>
#include <QNetworkProxyFactory>
#include <QString>
#include <QStringList>
#include <QUrl>
#include <WebCore/RunLoop.h>
#include <errno.h>

#ifndef NDEBUG
#if !OS(WINDOWS)
#include <unistd.h>
#endif
#endif

#ifndef NDEBUG
#include <QDebug>
#endif

#if OS(DARWIN) && !USE(UNIX_DOMAIN_SOCKETS)
#include <servers/bootstrap.h>

extern "C" kern_return_t bootstrap_look_up2(mach_port_t, const name_t, mach_port_t*, pid_t, uint64_t);
#endif

#if ENABLE(SUID_SANDBOX_LINUX)
#include "SandboxEnvironmentLinux.h"
#include <sys/wait.h>
#endif

using namespace WebCore;

namespace WebKit {
#ifndef NDEBUG
#if OS(WINDOWS)
static void sleep(unsigned seconds)
{
    ::Sleep(seconds * 1000);
}
#endif
#endif

class EnvHttpProxyFactory : public QNetworkProxyFactory
{
public:
    EnvHttpProxyFactory() { }

    bool initializeFromEnvironment();

    QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery& query = QNetworkProxyQuery());

private:
    QList<QNetworkProxy> m_httpProxy;
    QList<QNetworkProxy> m_httpsProxy;
};

bool EnvHttpProxyFactory::initializeFromEnvironment()
{
    bool wasSetByEnvironment = false;

    QUrl proxyUrl = QUrl::fromUserInput(QString::fromLocal8Bit(qgetenv("http_proxy")));
    if (proxyUrl.isValid() && !proxyUrl.host().isEmpty()) {
        int proxyPort = (proxyUrl.port() > 0) ? proxyUrl.port() : 8080;
        m_httpProxy << QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyPort);
        wasSetByEnvironment = true;
    } else
        m_httpProxy << QNetworkProxy::NoProxy;

    proxyUrl = QUrl::fromUserInput(QString::fromLocal8Bit(qgetenv("https_proxy")));
    if (proxyUrl.isValid() && !proxyUrl.host().isEmpty()) {
        int proxyPort = (proxyUrl.port() > 0) ? proxyUrl.port() : 8080;
        m_httpsProxy << QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyPort);
        wasSetByEnvironment = true;
    } else
        m_httpsProxy << QNetworkProxy::NoProxy;

    return wasSetByEnvironment;
}

QList<QNetworkProxy> EnvHttpProxyFactory::queryProxy(const QNetworkProxyQuery& query)
{
    QString protocol = query.protocolTag().toLower();
    bool localHost = false;

    if (!query.peerHostName().compare(QLatin1String("localhost"), Qt::CaseInsensitive) || !query.peerHostName().compare(QLatin1String("127.0.0.1"), Qt::CaseInsensitive))
        localHost = true;
    if (protocol == QLatin1String("http") && !localHost)
        return m_httpProxy;
    if (protocol == QLatin1String("https") && !localHost)
        return m_httpsProxy;

    QList<QNetworkProxy> proxies;
    proxies << QNetworkProxy::NoProxy;
    return proxies;
}

static void initializeProxy()
{
    QList<QNetworkProxy> proxylist = QNetworkProxyFactory::systemProxyForQuery();
    if (proxylist.count() == 1) {
        QNetworkProxy proxy = proxylist.first();
        if (proxy == QNetworkProxy::NoProxy || proxy == QNetworkProxy::DefaultProxy) {
            OwnPtr<EnvHttpProxyFactory> proxyFactory = adoptPtr(new EnvHttpProxyFactory());
            if (proxyFactory->initializeFromEnvironment()) {
                QNetworkProxyFactory::setApplicationProxyFactory(proxyFactory.leakPtr());
                return;
            }
        }
    }
    QNetworkProxyFactory::setUseSystemConfiguration(true);
}

#if ENABLE(SUID_SANDBOX_LINUX)
pid_t chrootMe()
{
    // Get the file descriptor of the socketpair.
    char* sandboxSocketDescriptorString = getenv(SANDBOX_DESCRIPTOR);
    if (!sandboxSocketDescriptorString)
        return -1;

    char* firstInvalidCharacter;
    long int sandboxSocketDescriptor = strtol(sandboxSocketDescriptorString, &firstInvalidCharacter, 10);
    if (*firstInvalidCharacter != '\0') {
        fprintf(stderr, "The socket descriptor of sandbox is not valid.\n");
        return -1;
    }

    // Get the PID of the setuid helper.
    char* sandboxHelperPIDString = getenv(SANDBOX_HELPER_PID);
    pid_t sandboxHelperPID = -1;

    // If no PID is available, the default of -1 will do.
    if (sandboxHelperPIDString) {
        errno = 0;
        sandboxHelperPID = strtol(sandboxHelperPIDString, &firstInvalidCharacter, 10);
        if (*firstInvalidCharacter != '\0') {
            fprintf(stderr, "The PID of sandbox is not valid.\n");
            return -1;
        }
    }

    // Send the chrootMe message to the helper.
    char sandboxMeMessage = MSG_CHROOTME;
    ssize_t numberOfCharacters = write(sandboxSocketDescriptor, &sandboxMeMessage, 1);
    if (numberOfCharacters != 1) {
        fprintf(stderr, "ChrootMe msg failed to write: %s.\n", strerror(errno));
        return -1;
    }

    // Read the acknowledgement message from the helper.
    numberOfCharacters = read(sandboxSocketDescriptor, &sandboxMeMessage, 1);
    if (numberOfCharacters != 1 || sandboxMeMessage != MSG_CHROOTED) {
        fprintf(stderr, "Couldn't read the confirmation message: %s.\n", strerror(errno));
        return -1;
    }
    close(sandboxSocketDescriptor);

    // Wait for the helper process.
    int expectedPID = waitpid(sandboxHelperPID, 0, 0);
    if (expectedPID != -1 && (sandboxHelperPID == -1 || expectedPID == sandboxHelperPID))
        return expectedPID;
    fprintf(stderr, "Couldn't wait for the helper process: %s\n", strerror(errno));
    return -1;
}
#endif

Q_DECL_EXPORT int WebProcessMainQt(QGuiApplication* app)
{
#if ENABLE(SUID_SANDBOX_LINUX)
    pid_t helper = chrootMe();
    if (helper == -1) {
        fprintf(stderr, "Asking for chroot failed.\n");
        return -1;
    }
#endif
    initializeProxy();

    InitializeWebKit2();

    // Create the connection.
    if (app->arguments().size() <= 1) {
        qDebug() << "Error: wrong number of arguments.";
        return 1;
    }

#if OS(DARWIN)
    QString serviceName = app->arguments().value(1);

    // Get the server port.
    mach_port_t identifier;
    kern_return_t kr = bootstrap_look_up2(bootstrap_port, serviceName.toUtf8().data(), &identifier, 0, 0);
    if (kr) {
        printf("bootstrap_look_up2 result: %x", kr);
        return 2;
    }
#else
    bool wasNumber = false;
    qulonglong id = app->arguments().at(1).toULongLong(&wasNumber, 10);
    if (!wasNumber) {
        qDebug() << "Error: connection identifier wrong.";
        return 1;
    }
    CoreIPC::Connection::Identifier identifier;
#if OS(WINDOWS)
    // Convert to HANDLE
    identifier = reinterpret_cast<CoreIPC::Connection::Identifier>(id);
#else
    // Convert to int
    identifier = static_cast<CoreIPC::Connection::Identifier>(id);
#endif
#endif

    WebKit::ChildProcessInitializationParameters parameters;
    parameters.connectionIdentifier = identifier;

    WebKit::WebProcess::shared().initialize(parameters);

    RunLoop::run();

    // FIXME: Do more cleanup here.
    delete app;

    return 0;
}

}


text:
package com.hpe.application.automation.tools.nv.plugin.results;

import com.fasterxml.jackson.databind.ObjectMapper;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.tasks.junit.JUnitParser;
import hudson.tasks.junit.TestResult;
import com.hpe.application.automation.tools.nv.model.NvNetworkProfile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

public class NvJUnitResultsHandler {
    private final String JSON_FILE_NAME = "nvResult.json";

    private String reportFilesPattern;

    private JUnitParser parser;
    private NvResultsBuilder aggregator;
    private ObjectMapper objectMapper;

    public NvJUnitResultsHandler(Map<String, Float> thresholdsMap, String reportFilesPattern) {
        this.reportFilesPattern = reportFilesPattern;

        parser = new JUnitParser(true, true);
        aggregator = new NvResultsBuilder(thresholdsMap);
        objectMapper = new ObjectMapper();
    }

    public void handle(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, NvNetworkProfile profile) throws IOException, InterruptedException {
        TestResult testResult = parser.parseResult(reportFilesPattern, build, build.getWorkspace(), launcher, listener);
        aggregator.aggregate(testResult, profile);
    }

    public void finalizeResults(AbstractBuild<?, ?> build) throws IOException, InterruptedException {
        NvJUnitResult result = aggregator.finalizeResults();
        writeResultToFile(build.getRootDir(), result);
        mergeResults(build, result);
    }

    private void writeResultToFile(File rootDir, NvJUnitResult result) throws IOException {
        File resultFile = new File(rootDir, JSON_FILE_NAME);
        objectMapper.writeValue(resultFile, result);
    }

    private void mergeResults(AbstractBuild<?, ?> build, NvJUnitResult result) throws IOException, InterruptedException {
        NvResultsMerger.mergeResults(build, reportFilesPattern, result);
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation JumpStatus

- (void)jumpWithMonster:(Monster *)monster
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    monster.status = [IdleStatus new];
}

- (void)runWithMonster:(Monster *)monster
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    monster.status = [IdleStatus new];
}

@end


text:
'use strict';

var basicCache = require('memory-cache');

var TYPE = 'basic';

// Basic in-memory pure JS database.
var BasicDb = function() {
  this.type = TYPE;
};

BasicDb.prototype.save = function(key, value, expire, onSuccess, onExpire) {
  basicCache.put(key, value, expire * 1000, onExpire);
  onSuccess();
};

BasicDb.prototype.load = function(key, callback) {
  var value = basicCache.get(key);
  callback(null, value);
};

var instance = new BasicDb();

exports.type = TYPE;

exports.connect = function() {
  return instance;
};


text:
//
// FileChannel.cs
//
// Author:
//	Zachary Gramana  <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

namespace Sharpen
{
	using System;
	using System.IO;

	internal class FileChannel
	{
		private FileStream s;
		byte[] buffer;
		bool isOpen;

		internal FileChannel (FileStream s)
		{
			this.s = s;
			isOpen = true;
		}

		internal FileStream Stream {
			get { return s; }
		}

		public void Close ()
		{
			isOpen = false;
			s.Close ();
		}

		public bool IsOpen ()
		{
			return isOpen;
		}

		public void Force (bool f)
		{
			s.Flush ();
		}

		public MappedByteBuffer Map ()
		{
			throw new NotImplementedException ();
		}

		public MappedByteBuffer Map (MapMode mode, long pos, int size)
		{
			throw new NotImplementedException ();
		}

		public int Read (byte[] buffer)
		{
			return s.Read (buffer, 0, buffer.Length);
		}

		public int Read (ByteBuffer buffer)
		{
			int offset = buffer.Position () + buffer.ArrayOffset ();
			int num2 = s.Read (buffer.Array (), offset, (buffer.Limit () + buffer.ArrayOffset ()) - offset);
			buffer.Position (buffer.Position () + num2);
			return num2;
		}

		public long Size ()
		{
			return s.Length;
		}

		public FileLock TryLock ()
		{
			try {
				s.Lock (0, int.MaxValue);
				return new FileLock (s);
			} catch (IOException) {
				return null;
			}
		}

		public int Write (byte[] buffer)
		{
			s.Write (buffer, 0, buffer.Length);
			return buffer.Length;
		}

		public int Write (ByteBuffer buffer)
		{
			int offset = buffer.Position () + buffer.ArrayOffset ();
			int count = (buffer.Limit () + buffer.ArrayOffset ()) - offset;
			s.Write (buffer.Array (), offset, count);
			buffer.Position (buffer.Position () + count);
			return count;
		}

		public long TransferFrom (FileChannel src, long pos, long count)
		{
			if (buffer == null)
				buffer = new byte [8092];
			int nr = src.s.Read (buffer, 0, (int) Math.Min (buffer.Length, count));
			long curPos = s.Position;
			s.Position = pos;
			s.Write (buffer, 0, nr);
			s.Position = curPos;
			return nr;
		}

		public enum MapMode
		{
			READ_ONLY
		}
	}
}


text:
package org.apache.nifi.processors.mqtt;

import io.moquette.proto.messages.PublishMessage;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processors.mqtt.common.MQTTQueueMessage;
import org.apache.nifi.processors.mqtt.common.MqttTestClient;
import org.apache.nifi.processors.mqtt.common.TestConsumeMqttCommon;
import org.apache.nifi.util.TestRunners;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.concurrent.BlockingQueue;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestConsumeMQTT extends TestConsumeMqttCommon {
    public MqttTestClient mqttTestClient;

    public class UnitTestableConsumeMqtt extends ConsumeMQTT {

        public UnitTestableConsumeMqtt(){
            super();
        }

        @Override
        public IMqttClient getMqttClient(String broker, String clientID, MemoryPersistence persistence) throws MqttException {
            mqttTestClient =  new MqttTestClient(broker, clientID, MqttTestClient.ConnectType.Subscriber);
            return mqttTestClient;
        }
    }

    @Before
    public void init() throws IOException {
        PUBLISH_WAIT_MS = 0;

        broker = "tcp://localhost:1883";
        UnitTestableConsumeMqtt proc = new UnitTestableConsumeMqtt();
        testRunner = TestRunners.newTestRunner(proc);
        testRunner.setProperty(ConsumeMQTT.PROP_BROKER_URI, broker);
        testRunner.setProperty(ConsumeMQTT.PROP_CLIENTID, "TestClient");
        testRunner.setProperty(ConsumeMQTT.PROP_TOPIC_FILTER, "testTopic");
        testRunner.setProperty(ConsumeMQTT.PROP_MAX_QUEUE_SIZE, "100");
    }

    /**
     * If the session.commit() fails, we should not remove the unprocessed message
     */
    @Test
    public void testMessageNotConsumedOnCommitFail() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        testRunner.run(1, false);
        ConsumeMQTT processor = (ConsumeMQTT) testRunner.getProcessor();
        MQTTQueueMessage mock = mock(MQTTQueueMessage.class);
        when(mock.getPayload()).thenReturn(new byte[0]);
        when(mock.getTopic()).thenReturn("testTopic");
        BlockingQueue<MQTTQueueMessage> mqttQueue = getMqttQueue(processor);
        mqttQueue.add(mock);
        try {
            ProcessSession session = testRunner.getProcessSessionFactory().createSession();
            transferQueue(processor,
                    (ProcessSession) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { ProcessSession.class }, (proxy, method, args) -> {
                        if (method.getName().equals("commit")) {
                            throw new RuntimeException();
                        } else {
                            return method.invoke(session, args);
                        }
                    }));
            fail("Expected runtime exception");
        } catch (InvocationTargetException e) {
            assertTrue("Expected generic runtime exception, not " + e, e.getCause() instanceof RuntimeException);
        }
        assertTrue("Expected mqttQueue to contain uncommitted message.", mqttQueue.contains(mock));
    }

    @After
    public void tearDown() throws Exception {
        if (MQTT_server != null) {
            MQTT_server.stopServer();
        }
        final File folder =  new File("./target");
        final File[] files = folder.listFiles( new FilenameFilter() {
            @Override
            public boolean accept( final File dir,
                                   final String name ) {
                return name.matches( "moquette_store.mapdb.*" );
            }
        } );
        for ( final File file : files ) {
            if ( !file.delete() ) {
                System.err.println( "Can't remove " + file.getAbsolutePath() );
            }
        }
    }

    @Override
    public void internalPublish(PublishMessage publishMessage) {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(publishMessage.getPayload().array());
        mqttMessage.setRetained(publishMessage.isRetainFlag());
        mqttMessage.setQos(publishMessage.getQos().ordinal());

        try {
            mqttTestClient.publish(publishMessage.getTopicName(), mqttMessage);
        } catch (MqttException e) {
            fail("Should never get an MqttException when publishing using test client");
        }
    }
}


text:
"""Authentication against the twitter OAUTH api."""

import urlparse

import oauth2 as oauth

import base
import rowan.controllers as controllers
import rowan.http as http

TWITTER_OAUTH = {
    # These should be fine, unless twitter changes its API
    "host": "api.twitter.com",
    "callback": "http://localhost:8000/auth/twitter/done/",

    "request_token": dict(resource="/oauth/request_token", method="POST"),
    "user_authorization": dict(resource="/oauth/authorize", method="GET"),
    "access_token": dict(resource="/oauth/access_token", method="POST")
    }
class TwitterOAuthError(Exception): pass

class TwitterAuthChannel(base.AuthChannel):
    """
    Encapsulates the handling of twitters authentication data and its
    storage in a database.
    """
    def get_channel_key(self):
        return "twitter"

    def create_session_data(self):
        return {
            'token': self.data['oauth_token'],
            'secret': self.data['oauth_token_secret'],
            }

    def create_user_data(self):
        return {
            'user_id': self.data['user_id'],
            'user_name': self.data['screen_name']
            }

    def create_auth_data(self):
        return {
            "twitter_id": self.data['user_id']
            }

    def get_auth_data(self, db):
        auth_table_name = self.get_auth_table_name()
        return db[auth_table_name].find_one(
            {'twitter_id': self.data['user_id']}
            )

def twitter_begin_auth(request):
    """
    Initiate the authentication against the twitter oauth server.
    """
    consumer = oauth.Consumer(
        request.auth.twitter['consumer_key'],
        request.auth.twitter['consumer_secret']
        )
    client = oauth.Client(consumer)

    action = TWITTER_OAUTH['request_token']
    host = TWITTER_OAUTH['host']
    url = "http://%s%s" % (host, action['resource'])
    resp, content = client.request(
        url, action['method'],
        "oauth_callback=%s" % TWITTER_OAUTH['callback']
        )
    if resp['status'] != "200":
        raise TwitterOAuthError("Invalid response '%s'." % resp['status'])
    else:
        # Write the auth token to the session
        twitter_data = dict(urlparse.parse_qsl(content))
        request.session['twitter'] = {
            "token": twitter_data['oauth_token'],
            "secret": twitter_data['oauth_token_secret']
            }

    # Redirect the user to the twitter login screen
    action = TWITTER_OAUTH['user_authorization']
    url = "http://%s%s?oauth_token=%s" % (
        host, action['resource'], twitter_data['oauth_token']
        )
    return http.Http302(location=url)

def twitter_end_auth(request):
    """This is called by Twitter when the user has granted permission
    to the app."""
    # Create a temporary client based on the temporary token data.
    token = oauth.Token(
        request.session['twitter']['token'],
        request.session['twitter']['secret']
        )
    token.set_verifier(request.query_params['oauth_verifier'])
    consumer = oauth.Consumer(
        request.auth.twitter['consumer_key'],
        request.auth.twitter['consumer_secret']
        )
    client = oauth.Client(consumer, token)

    # Get the permanent token data from the above verifier.
    action = TWITTER_OAUTH['access_token']
    host = TWITTER_OAUTH['host']
    url = "http://%s%s" % (host, action['resource'])
    resp, content = client.request(url, action['method'])
    if resp['status'] != "200":
        raise TwitterOAuthError("Invalid response '%s'." % resp['status'])
    else:
        # Finish the authentication process.
        twitter_data = dict(urlparse.parse_qsl(content))
        auth = TwitterAuthChannel(twitter_data)
        auth.complete_authentication(request.db, request.session)

    # Redirect somewhere useful
    return http.Http302(location=request.auth.twitter['complete_uri'])

# Holds all the twitter related authentication urls.
twitter_router = controllers.Router(
    (r"^$", twitter_begin_auth),
    (r"^done/$", twitter_end_auth)
    )


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit9058fcd5f977979999b8826fb6e9a3f8::getLoader();


text:
@interface MNUApiManager : NSObject

- (instancetype)initWithClientId:(NSString *)clientId andHostname:(NSString *)hostname;
- (void)getUserAccessTokenWithUsername:(NSString *)username password:(NSString *)password completion:(void (^)(NSError *error))completion;

- (void)postWithPath:(NSString *)path body:(NSData *)body completion:(void (^)(NSData *data, NSError *error))completion;

- (void)putWithPath:(NSString *)path body:(NSData *)body completion:(void (^)(NSData *data, NSError *error))completion;

- (BOOL)isOwnerAccessTokenPresent;
- (void)removeTokens;
@end


text:
require './spec/rspec_helper.rb'
require './lib/commons/debates_parser'

describe CommonsDebatesParser do
  before(:each) do
    Preamble.any_instance.stubs(:save)
    NonContributionPara.any_instance.stubs(:save)
    ContributionPara.any_instance.stubs(:save)
    Component.any_instance.stubs(:save)
    DailyPart.any_instance.stubs(:save)
    Debate.any_instance.stubs(:save)
    Question.any_instance.stubs(:save)
    Division.any_instance.stubs(:save)
  end

  def stub_page(file)
    html = File.read(file)
    HansardPage.any_instance.stubs(:scrape_metadata)
    HansardPage.any_instance.stubs(:volume).returns("531")
    HansardPage.any_instance.stubs(:part).returns("190")
    HansardPage.any_instance.stubs(:next_url).returns(nil)
    mock_response = mock("response")
    mock_response.expects(:body).at_least_once.returns(html)
    RestClient.expects(:get).at_least_once.returns(mock_response)
    @page = HansardPage.new(@url)
  end

  def stub_part(house, date, part, volume)
    @daily_part = DailyPart.new
    DailyPart.stubs(:find_or_create_by).returns(@daily_part)
    @daily_part.expects(:house=).with(house)
    @daily_part.expects(:date=).with(date)
    if part
      @daily_part.stubs(:part=)
    end
    @daily_part.stubs(:persisted?)
    @daily_part.stubs(:ident)
    @daily_part.stubs(:volume=).with(volume)
    @daily_part.stubs(:save)
    @daily_part.stubs(:components).returns([])
  end

  context "in general" do
    before(:each) do
      @url = "http://www.publications.parliament.uk/pa/cm201011/cmhansrd/cm110719/debtext/110719-0001.htm"
      stub_part("Commons", "2099-01-01", "190", "531")

      @component = Component.new
      @component.stubs(:sections).returns([])
      Component.stubs(:find_or_create_by).returns(@component)

      CommonsDebatesParser.any_instance.stubs(:house=)
      @parser = CommonsDebatesParser.new("2099-01-01")
      @parser.expects(:component_prefix).times(2).returns("d")
      @parser.expects(:link_to_first_page).returns(@url)
    end
  end

  context "when handling Backbench Business subsection" do
    before(:each) do
      @url = "http://www.publications.parliament.uk/pa/cm201011/cmhansrd/cm110719/debtext/110719-0001.htm"
      stub_part("Commons", "2099-01-01", nil, "531")

      @component = Component.new(ident: "2099-01-01_hansard_c_d")
      @component.stubs(:sections).returns([])
      Component.stubs(:find_or_create_by).returns(@component)

      @parser = CommonsDebatesParser.new("2099-01-01")
      @parser.expects(:component_prefix).times(2).returns("d")
      @parser.expects(:link_to_first_page).returns(@url)
    end

    it "should correctly recognise the Backbench Business subsection" do
      stub_page("spec/data/commons/backbench_business_header.html")

      container = Container.new
      Container.expects(:find_or_create_by).returns(container)
      container.expects(:title=).with("Backbench Business")
      container.stubs(:paragraphs).returns([])
      container.expects(:sequence=).with(1)
      container.expects(:url=).with("#{@url}\#11071988000009")

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).returns(ncpara)
      NonContributionPara.any_instance.stubs(:section=)
      ncpara.expects(:content=).with("[30th Allotted Day]")
      ncpara.expects(:sequence=).with(1)
      ncpara.expects(:url=).with("#{@url}\#11071988000020")
      ncpara.expects(:column=).with("831")
      ncpara.expects(:section=).with(container)
      container.paragraphs.expects(:<<).with(ncpara)

      @parser.parse
    end

    it "should handle the Preamble properly and create Debate elements for each debate" do
      stub_page("spec/data/commons/backbench_business_excerpt.html")

      container = Container.new(ident: "2099-01-01_hansard_c_d_000001")
      Container.expects(:find_or_create_by).returns(container)
      container.expects(:title=).with('Backbench Business')
      container.expects(:component=).with(@component)
      container.expects(:url=)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).returns(ncpara)

      ncpara.expects(:content=).with("[30th Allotted Day]")
      container.paragraphs.expects(:<<).with(ncpara)

      debate = Debate.new
      Debate.any_instance.stubs(:paragraphs).returns([])
      Debate.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002').returns(debate)
      debate.expects(:ident).at_least_once.returns('2099-01-01_hansard_c_d_000002')
      debate.expects(:title=).with("Summer Adjournment")
      debate.expects(:parent_section=).with(container)
      container.sections.expects(:<<).with(debate)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).times(4).returns(contribution)

      debate = Debate.new
      Debate.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003').returns(debate)
      debate.expects(:title=).with('Business, innovation and skills')
      debate.expects(:ident).at_least_once.returns('2099-01-01_hansard_c_d_000003')
      debate.expects(:parent_section=).with(container)
      container.sections.expects(:<<).with(debate)

      ContributionPara.expects(:find_or_create_by).twice.returns(contribution)

      @parser.parse
    end
  end

  context "when handling the Oral Answers subsection" do
    before(:each) do
      @url = "http://www.publications.parliament.uk/pa/cm201011/cmhansrd/cm110719/debtext/110719-0001.htm"
      stub_part("Commons", "2099-01-01", nil, "531")

      @parser = CommonsDebatesParser.new("2099-01-01")
      @parser.expects(:component_prefix).times(2).returns("d")
      @parser.expects(:link_to_first_page).returns(@url)
    end

    it "should create the preamble and make a Section for Oral Answers" do
      stub_page("spec/data/commons/debates_and_oral_answers_header.html")
      HansardPage.expects(:new).returns(@page)

      component = Component.new
      Component.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d').returns(component)
      component.expects(:ident).at_least_once.returns('2099-01-01_hansard_c_d')

      preamble = Preamble.new(:ident => '2099-01-01_hansard_c_d_000001')
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001').returns(preamble)
      preamble.expects(:title=).with('House of Commons')
      preamble.expects(:component=).with(component)
      preamble.expects(:url=).with("#{@url}/#11071988000007")
      preamble.expects(:sequence=).with(1)
      preamble.expects(:paragraphs).at_least_once.returns([])

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).twice.returns(ncpara)

      preamble = Preamble.new(:ident => '2099-01-01_hansard_c_d_000002')
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002').returns(preamble)
      preamble.expects(:title=).with('Prayers')
      preamble.expects(:component=).with(component)
      preamble.expects(:url=).with("#{@url}/#11071988000010")
      preamble.expects(:sequence=).with(2)
      preamble.expects(:paragraphs).at_least_once.returns([])

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002_p000001').returns(ncpara)

      section = Container.new
      Container.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003').returns(section)
      section.expects(:component=).with(component)
      section.expects(:title=).with("Oral Answers to Questions")
      section.expects(:url=).with("#{@url}\#11071988000008")
      section.stubs(:paragraphs).returns([])

      @parser.parse
    end

    it "should create a Container for each department" do
      stub_page("spec/data/commons/debates_and_oral_answers.html")

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).times(3).returns(ncpara)
      NonContributionPara.any_instance.stubs(:section=)

      container = Container.new(ident: "_000003")
      container.expects(:title=).with("Oral Answers to Questions")
      Container.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003').returns(container)

      dept_container = Container.new(ident: "_000004")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000004").returns(dept_container)
      dept_container.expects(:title=).with("Foreign and Commonwealth Office")
      dept_container.expects(:parent_section=).with(container)
      container.sections.expects(:<<).with(dept_container)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: "_000004_p000001").returns(ncpara)
      ncpara.expects(:section=).with(dept_container)

      question = Question.new
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).twice.returns(question)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).times(11).returns(contribution)

      @parser.parse
    end

    it "should create a Question for each question found" do
      stub_page("spec/data/commons/debates_and_oral_answers.html")

      component = Component.new(ident: '2099-01-01_hansard_c_d')
      Component.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d').returns(component)

      preamble = Preamble.new
      Preamble.any_instance.stubs(:paragraphs).returns([])
      preamble.stubs(:content=)
      Preamble.expects(:find_or_create_by).twice.returns(preamble)

      ncpara = NonContributionPara.new
      NonContributionPara.any_instance.stubs(:content=)
      NonContributionPara.expects(:find_or_create_by).times(4).returns(ncpara)

      container = Container.new
      Container.expects(:find_or_create_by).times(2).returns(container)

      para = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).times(11).returns(para)

      question = Question.new
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005").returns(question)
      question.expects(:ident).at_least_once.returns("2099-01-01_hansard_c_d_000005")
      question.expects(:department=).with("Foreign and Commonwealth Office")
      question.expects(:title=).with("Syria")
      question.expects(:number=).with("66855")
      question.expects(:asked_by=).with("David Hanson")
      question.expects(:question_type=).with("for oral answer")
      question.expects(:url=).with("#{@url}\#11071988000022")

      question = Question.new
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006").returns(question)
      question.expects(:ident).at_least_once.returns("2099-01-01_hansard_c_d_000006")
      question.expects(:department=).with("Foreign and Commonwealth Office")
      question.expects(:title=).with("Nuclear Non-proliferation and Disarmament")
      question.expects(:number=).with("66858")
      question.expects(:asked_by=).with("Paul Flynn")
      question.expects(:question_type=).with("for oral answer")

      @parser.parse
    end

    it "should capture the member and column data for each Question" do
      stub_page("spec/data/commons/debates_and_oral_answers.html")

      component = Component.new(ident: '2099-01-01_hansard_c_d')
      Component.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d').returns(component)

      preamble = Preamble.new
      Preamble.any_instance.stubs(:paragraphs).returns([])
      preamble.stubs(:content=)
      Preamble.expects(:find_or_create_by).twice.returns(preamble)

      ncpara = NonContributionPara.new
      NonContributionPara.any_instance.stubs(:content=)
      NonContributionPara.expects(:find_or_create_by).times(4).returns(ncpara)

      contribution = ContributionPara.new
      ContributionPara.any_instance.stubs(:content=)
      ContributionPara.expects(:find_or_create_by).times(11).returns(contribution)

      container = Container.new
      Container.expects(:find_or_create_by).twice.returns(container)

      question1 = Question.new(ident: "2099-01-01_hansard_c_d_000005")
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005").returns(question1)

      question2 = Question.new(ident: "2099-01-01_hansard_c_d_000006")
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006").returns(question2)

      @parser.parse

      question1.members.should eq ["David Hanson", "William Hague", "Philip Hollobone", "Stephen Twigg"]
      question2.members.should eq ["Paul Flynn", "Alistair Burt"]

      question1.columns.should eq ["771", "772"]
      question2.columns.should eq ["772"]
    end

    it "should all the paragraph data" do
      stub_page("spec/data/commons/debates_and_oral_answers.html")
      page_url = "http://www.publications.parliament.uk/pa/cm201011/cmhansrd/cm110719/debtext/110719-0001.htm"

      question = Question.new(ident: "2099-01-01_hansard_c_d_000005")
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005").returns(question)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000001").returns(contribution)
      contribution.expects(:content=).with("1. Mr David Hanson (Delyn) (Lab): When he next expects to discuss the situation in Syria with his US counterpart. [66855]")
      contribution.expects(:member=).with("David Hanson")
      contribution.expects(:speaker_printed_name=).with("Mr David Hanson")
      contribution.expects(:url=).with("#{page_url}#11071988000793")
      contribution.expects(:column=).with("771")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000002").returns(contribution)
      contribution.expects(:content=).with("The Secretary of State for Foreign and Commonwealth Affairs (Mr William Hague): I am in regular contact with Secretary Clinton and I last discussed Syria with her on Friday.")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("The Secretary of State for Foreign and Commonwealth Affairs (Mr William Hague)")
      contribution.expects(:url=).with("#{page_url}#11071988000794")
      contribution.expects(:column=).with("771")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000003").returns(contribution)
      contribution.expects(:content=).with("Mr Hanson: I thank the Foreign Secretary for that answer. Given the recent violence, including the reported shooting of unarmed protesters, does he agree with Secretary of State Clinton that the Syrian Government have lost legitimacy? Given the level of violence, particularly the attacks on the US embassy and the French embassy, what steps is he taking to ensure the security of British citizens who work for the United Kingdom and are operating in Syria now?")
      contribution.expects(:member=).with("David Hanson")
      contribution.expects(:speaker_printed_name=).with("Mr Hanson")
      contribution.expects(:url=).with("#{page_url}#11071988000795")
      contribution.expects(:column=).with("771")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000004").returns(contribution)
      contribution.expects(:content=).with("Mr Hague: The right hon. Gentleman raises some important issues in relation to recent events in Syria. We absolutely deplore the continuing violence against protesters. Reports overnight from the city of Homs suggest that between 10 and 14 people were killed, including a 12-year-old child. We have condemned the attacks on the American and French embassies and we called in the Syrian ambassador last Wednesday to deliver our protests and to demand that Syria observes the requirements of the Vienna convention. The US and British Governments are united in saying that President Assad is losing legitimacy and should reform or step aside, and that continues to be our message.")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("Mr Hague")
      contribution.expects(:url=).with("#{page_url}#11071988000796")
      contribution.expects(:column=).with("771")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000005").returns(contribution)
      contribution.expects(:content=).with("Mr Philip Hollobone (Kettering) (Con): Iran has been involved in training Syrian troops and providing materi\303\251l assistance, including crowd-dispersal equipment. What assessment has the Foreign Secretary made of the dark hand of Iran in fomenting trouble in the middle east and in supporting illegitimate regimes?")
      contribution.expects(:member=).with("Philip Hollobone")
      contribution.expects(:speaker_printed_name=).with("Mr Philip Hollobone")
      contribution.expects(:url=).with("#{page_url}#11071988000797")
      contribution.expects(:column=).with("771")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000006").returns(contribution)
      contribution.expects(:content=).with("Mr Hague: Iran has certainly been involved in the way that my hon. Friend describes, and I set out a few weeks ago that I believed it to be involved in that way. It shows the extraordinary hypocrisy of the Iranian leadership")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("Mr Hague")
      contribution.expects(:url=).with("#{page_url}#11071988000798")
      contribution.expects(:column=).with("771")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000007").returns(contribution)
      contribution.expects(:content=).with("on this that it has been prepared to encourage protests in Egypt, Tunisia and other countries while it has brutally repressed protest in its own country and is prepared to connive in doing so in Syria.")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:url=).with("#{page_url}#11071988000798")
      contribution.expects(:column=).with("772")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000008").returns(contribution)
      contribution.expects(:content=).with("Stephen Twigg (Liverpool, West Derby) (Lab/Co-op): Does the Foreign Secretary agree that the world has been far too slow in its response to the appalling abuses of human rights in Syria? Surely, after the events of the weekend and the past few days in particular, there is now an urgent need for a clear and strong United Nations Security Council resolution.")
      contribution.expects(:member=).with("Stephen Twigg")
      contribution.expects(:speaker_printed_name=).with("Stephen Twigg")
      contribution.expects(:url=).with("#{page_url}#11071988000799")
      contribution.expects(:column=).with("772")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000009").returns(contribution)
      contribution.expects(:content=).with("Mr Hague: I think the world has been not so much slow as not sufficiently united on this. It has not been possible for the Arab League to arrive at a clear, strong position, which makes the situation entirely different to that in Libya, where the Arab League called on the international community to assist and intervene. There has not been the necessary unity at the United Nations Security Council and at times Russia has threatened to veto any resolution. Our resolution, which was put forward with our EU partners, remains very much on the table and certainly has the support of nine countries. We would like the support of more than nine countries to be able to put it to a vote in the Security Council, but it is very much on the table and we reserve the right at any time to press it to a vote in the United Nations. The hon. Gentleman is quite right to say that recent events add further to the case for doing so.")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("Mr Hague")
      contribution.expects(:url=).with("#{page_url}#11071988000800")
      contribution.expects(:column=).with("772")

      question = Question.new(ident: "2099-01-01_hansard_c_d_000006")
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006").returns(question)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006_p000001").returns(contribution)
      contribution.expects(:content=).with("3. Paul Flynn (Newport West) (Lab): What recent progress his Department has made on nuclear non-proliferation and disarmament. [66858]")
      contribution.expects(:member=).with("Paul Flynn")
      contribution.expects(:speaker_printed_name=).with("Paul Flynn")
      contribution.expects(:url=).with("#{page_url}#11071988000801")
      contribution.expects(:column=).with("772")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006_p000002").returns(contribution)
      contribution.expects(:content=).with("The Parliamentary Under-Secretary of State for Foreign and Commonwealth Affairs (Alistair Burt): We continue to work across all three pillars of the non-proliferation treaty to build on the success of last year's review conference in New York. I am particularly proud of the work we have done towards ensuring the first conference of nuclear weapon states, which was held recently in Paris - the P5 conference - in which further progress was made, particularly towards disarmament.")
      contribution.expects(:member=).with("Alistair Burt")
      contribution.expects(:speaker_printed_name=).with("The Parliamentary Under-Secretary of State for Foreign and Commonwealth Affairs (Alistair Burt)")
      contribution.expects(:url=).with("#{page_url}#11071988000802")
      contribution.expects(:column=).with("772")

      @parser.parse
    end

    it "should deal with the Topical Questions subsection" do
      stub_page("spec/data/commons/topical_questions.html")

      component = Component.new(ident: '2099-01-01_hansard_c_d')
      Component.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d').returns(component)

      Preamble.any_instance.stubs(:paragraphs).returns([])

      preamble = Preamble.new(ident: "2099-01-01_hansard_c_d_000001")
      preamble.stubs(:content=)
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001').returns(preamble)
      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001_p000001').returns(ncpara)
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001_p000002').returns(ncpara)

      preamble = Preamble.new(ident: "2099-01-01_hansard_c_d_000002")
      preamble.stubs(:content=)
      ncpara = NonContributionPara.new
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002').returns(preamble)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002_p000001').returns(ncpara)

      questions_section = Container.new(ident: "2099-01-01_hansard_c_d_000003")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000003").returns(questions_section)
      questions_section.expects(:title=).with("Oral Answers to Questions")

      dept_container = Container.new(ident: "2099-01-01_hansard_c_d_000004")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000004").returns(dept_container)
      dept_container.expects(:title=).with("Foreign and Commonwealth Office")
      dept_container.expects(:parent_section=).with(questions_section)
      questions_section.sections.expects(:<<).with(dept_container)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000004_p000001").returns(ncpara)
      ncpara.expects(:content=).with("The Secretary of State was asked -")
      ncpara.expects(:section=).with(dept_container)

      question = Question.new(ident: "2099-01-01_hansard_c_d_000005")
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005").returns(question)
      question.expects(:department=).with("Foreign and Commonwealth Office")
      question.expects(:title=).with("Nuclear Non-proliferation and Disarmament")
      question.expects(:asked_by=).with("Paul Flynn")
      question.expects(:question_type=).with("for oral answer")
      question.expects(:number=).with("66858")
      question.expects(:parent_section=).with(dept_container)
      dept_container.sections.expects(:<<).with(question)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000001").returns(contribution)
      contribution.expects(:content=).with("3. Paul Flynn (Newport West) (Lab): What recent progress his Department has made on nuclear non-proliferation and disarmament. [66858]")
      contribution.expects(:member=).with("Paul Flynn")
      contribution.expects(:speaker_printed_name=).with("Paul Flynn")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005_p000002").returns(contribution)
      contribution.expects(:content=).with("The Parliamentary Under-Secretary of State for Foreign and Commonwealth Affairs (Alistair Burt): We continue to work across all three pillars of the non-proliferation treaty to build on the success of last year's review conference in New York. I am particularly proud of the work we have done towards ensuring the first conference of nuclear weapon states, which was held recently in Paris - the P5 conference - in which further progress was made, particularly towards disarmament.")
      contribution.expects(:member=).with("Alistair Burt")
      contribution.expects(:speaker_printed_name=).with("The Parliamentary Under-Secretary of State for Foreign and Commonwealth Affairs (Alistair Burt)")

      topical_section = Container.new(ident: "2099-01-01_hansard_c_d_000006")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006").returns(topical_section)
      topical_section.expects(:title=).with("Topical Questions")
      topical_section.expects(:url=).with("#{@url}\#11071988000034")
      topical_section.expects(:parent_section=).with(dept_container)
      dept_container.sections.expects(:<<).with(topical_section)

      question = Question.new(ident: "2099-01-01_hansard_c_d_000007")
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000007").returns(question)
      question.expects(:department=).with("Foreign and Commonwealth Office")
      question.expects(:title=).with("Topical Questions - T1")
      question.expects(:number=).with("66880")
      question.expects(:asked_by=).with("Harriett Baldwin")
      question.expects(:question_type=).with("for oral answer")
      question.expects(:parent_section=).with(topical_section)
      topical_section.sections.expects(:<<).with(question)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000007_p000001").returns(contribution)
      contribution.expects(:content=).with("T1. [66880] Harriett Baldwin (West Worcestershire) (Con): If he will make a statement on his departmental responsibilities.")
      contribution.expects(:member=).with("Harriett Baldwin")
      contribution.expects(:speaker_printed_name=).with("Harriett Baldwin")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000007_p000002").returns(contribution)
      contribution.expects(:content=).with("The Secretary of State for Foreign and Commonwealth Affairs (Mr William Hague): Statement goes here")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("The Secretary of State for Foreign and Commonwealth Affairs (Mr William Hague)")

      question = Question.new(ident: "2099-01-01_hansard_c_d_000008")
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000008").returns(question)
      question.expects(:department=).with("Foreign and Commonwealth Office")
      question.expects(:title=).with("Topical Questions - T2")
      question.expects(:asked_by=).with("Stephen Mosley")
      question.expects(:number=).with("66881")
      question.expects(:question_type=).with("for oral answer")
      question.expects(:parent_section=).with(topical_section)
      topical_section.sections.expects(:<<).with(question)

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000008_p000001").returns(contribution)
      contribution.expects(:content=).with("T2. [66881] Stephen Mosley (City of Chester) (Con): One of the remaining issues in South Sudan is that of Abyei. Will my right hon. Friend give us an update on what action is being taken to ensure that the promised referendum in Abyei goes ahead successfully?")
      contribution.expects(:member=).with("Stephen Mosley")
      contribution.expects(:speaker_printed_name=).with("Stephen Mosley")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000008_p000002").returns(contribution)
      contribution.expects(:content=).with("Mr Hague: The urgent thing has been to bring peace and order to Abyei, and that is something that I have discussed with those in the north and south in Sudan, as well as with the Ethiopian Prime Minister and Foreign Minister on my visit to Ethiopia 10 days or so ago. Up to 4,200 Ethiopian troops will go to Abyei, and we have been active in quickly passing the necessary United Nations authority for them to do so. That is designed to pave the way for political progress in Abyei, but the most urgent thing has been to get that Ethiopian force there and to prevent continuing violence.")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("Mr Hague")

      @parser.parse
    end

    it "should not treat the first Debate as another Question" do
      stub_page("spec/data/commons/topical_questions_end.html")

      component = Component.new(ident: '2099-01-01_hansard_c_d')
      Component.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d').returns(component)

      preamble = Preamble.new
      Preamble.any_instance.stubs(:paragraphs).returns([])
      preamble.stubs(:content=)
      preamble.stubs(:ident).returns("2099-01-01_hansard_c_d_000001")
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001').returns(preamble)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001_p000001').returns(ncpara)
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001_p000002').returns(ncpara)

      preamble = Preamble.new
      Preamble.any_instance.stubs(:paragraphs).returns([])
      preamble.stubs(:content=)
      preamble.stubs(:ident).returns("2099-01-01_hansard_c_d_000002")
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002').returns(preamble)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000002_p000001').returns(ncpara)

      questions_section = Container.new(ident: "2099-01-01_hansard_c_d_000003")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000003").returns(questions_section)
      questions_section.expects(:title=).with("Oral Answers to Questions")

      dept_section = Container.new(ident: "2099-01-01_hansard_c_d_000004")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000004").returns(dept_section)
      dept_section.expects(:title=).with("Foreign and Commonwealth Office")
      dept_section.expects(:url=).with("#{@url}\#110719-0001.htm_dpthd0")

      topical_section = Container.new(ident: "2099-01-01_hansard_c_d_000005")
      Container.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000005").returns(topical_section)
      topical_section.expects(:title=).with("Topical Questions")
      topical_section.expects(:url=).with("#{@url}\#11071988000034")

      question = Question.new(ident: "2099-01-01_hansard_c_d_000006")
      Question.any_instance.stubs(:paragraphs).returns([])
      Question.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006").returns(question)
      question.expects(:department=).with("Foreign and Commonwealth Office")
      question.expects(:title=).with("Topical Questions - T1")
      question.expects(:asked_by=).with("Harriett Baldwin")
      question.expects(:question_type=).with("for oral answer")
      question.expects(:number=).with("66880")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006_p000001").returns(contribution)
      contribution.expects(:content=).with("T1. [66880] Harriett Baldwin (West Worcestershire) (Con): If he will make a statement on his departmental responsibilities.")
      contribution.expects(:member=).with("Harriett Baldwin")
      contribution.expects(:speaker_printed_name=).with("Harriett Baldwin")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000006_p000002").returns(contribution)
      contribution.expects(:content=).with("The Secretary of State for Foreign and Commonwealth Affairs (Mr William Hague): Statement goes here")
      contribution.expects(:member=).with("William Hague")
      contribution.expects(:speaker_printed_name=).with("The Secretary of State for Foreign and Commonwealth Affairs (Mr William Hague)")

      debate = Debate.new(ident: "2099-01-01_hansard_c_d_000007")
      Debate.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000007").returns(debate)
      debate.stubs(:paragraphs).returns([])

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000007_p000001").returns(contribution)
      contribution.expects(:content=)
      contribution.expects(:member=).with("Hilary Benn")
      contribution.expects(:speaker_printed_name=).with("Hilary Benn")

      @parser.parse
    end
  end

  context "when handling a Debate containing a Division" do
    before(:each) do
      @url = "http://www.publications.parliament.uk/pa/cm201011/cmhansrd/cm110719/debtext/110719-0001.htm"
      stub_part("Commons", "2099-01-01", nil, "531")

      @parser = CommonsDebatesParser.new("2099-01-01")
      @parser.expects(:component_prefix).times(2).returns("d")
      @parser.expects(:link_to_first_page).returns(@url)
    end

    it "should store the Division with Ayes and Noes" do
      stub_page("spec/data/commons/debate_with_division.html")

      component = Component.new
      Component.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d').returns(component)
      component.expects(:ident).at_least_once.returns('2099-01-01_hansard_c_d')

      preamble = Preamble.new(ident: "preamble")
      Preamble.any_instance.stubs(:paragraphs).returns([])
      preamble.stubs(:content=)
      Preamble.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000001').returns(preamble)

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: 'preamble_p000001').returns(ncpara)
      NonContributionPara.expects(:find_or_create_by).with(ident: 'preamble_p000002').returns(ncpara)

      preamble = Preamble.new(ident: "preamble2")
      Preamble.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000002").returns(preamble)

      NonContributionPara.expects(:find_or_create_by).with(ident: 'preamble2_p000001').returns(ncpara)

      debate = Debate.new(ident: "2099-01-01_hansard_c_d_000003", title: "Public Bodies Bill [Lords]")
      Debate.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000003").returns(debate)
      debate.stubs(:paragraphs).returns([])
      debate.expects(:title=).with("Public Bodies Bill [Lords]")
      debate.expects(:url=).with("#{@url}\#11071272000001")
      debate.expects(:bill_title=).with("Public Bodies Bill")
      debate.expects(:bill_stage=).with("Second Reading")

      ncpara = NonContributionPara.new
      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003_p000001').returns(ncpara)
      ncpara.expects(:content=).with("[Relevant documents: The Fifth Report from the Public Administration Select Committee, Smaller Government: Shrinking the Quango State, HC 537, and the Government response, Cm 8044 .]")

      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003_p000002').returns(ncpara)
      ncpara.expects(:content=).with("Second Reading")

      contribution = ContributionPara.new
      ContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003_p000003').returns(contribution)
      contribution.expects(:content=).with("Mr Hurd: In summary, the reforms we have proposed and that have been debated again today will produce a leaner and more effective system of public bodies centred on the principle of ministerial accountability. We have listened intently to the comments and concerns expressed during the debate and recognise that there are areas where the Government can helpfully produce further clarity and assurance, and the Deputy Leader of the House and I look forward to continuing to engage with hon. Members in Committee and elsewhere.")

      ContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003_p000004').returns(contribution)
      contribution.expects(:content=).with("However, I reiterate my hope that the House can come together in support of the belief that ministerial accountability for public functions and the use of public money should be at the heart of how we conduct ourselves. The Government believe that the proposals embodied in the Bill and in our plans for a regular comprehensive review of all public bodies will set a new standard for the management and review of public bodies, and on that basis I commend the Bill to the House.")

      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000003_p000005').returns(ncpara)
      ncpara.expects(:content=).with("Question put, That the amendment be made.")

      division = Division.new(ident: "2099-01-01_hansard_c_d_000004", ayes: [], noes: [], tellers_ayes: [], tellers_noes: [])
      Division.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000004').returns(division)
      division.expects(:number=).with('321')
      division.expects(:title=).with("Division - Public Bodies Bill [Lords]")
      division.expects(:ayes=).with([])
      division.expects(:noes=).with([])
      division.expects(:tellers_ayes=).with([])
      division.expects(:tellers_noes=).with([])
      division.ayes.expects(:<<).with('Abbott, Ms Diane')
      division.ayes.expects(:<<).with('Abrahams, Debbie')
      division.ayes.expects(:<<).with('Ainsworth, rh Mr Bob')
      division.ayes.expects(:<<).with('Morris, Grahame M.')
      division.ayes.expects(:pop).returns('Morris, Grahame M.')
      division.ayes.expects(:<<).with('Morris, Grahame M. (Easington)')

      division.noes.expects(:<<).with('Adams, Nigel')
      division.noes.expects(:<<).with('Afriyie, Adam')
      division.noes.expects(:<<).with('Aldous, Peter')
      division.noes.expects(:<<).with('Alexander, rh Danny')
      division.noes.expects(:<<).with('Davies, David T. C.')
      division.noes.expects(:pop).returns('Davies, David T. C.')
      division.noes.expects(:<<).with('Davies, David T. C. (Monmouth)')

      division.tellers_ayes.expects(:<<).with('Lilian Greenwood')
      division.tellers_ayes.expects(:<<).with('Gregg McClymont')

      division.tellers_noes.expects(:<<).with('James Duddridge')
      division.tellers_noes.expects(:<<).with('Norman Lamb')

      NonContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000004_p000001").returns(ncpara)
      ncpara.expects(:content=).with("The House divided:")

      NonContributionPara.expects(:find_or_create_by).with(ident: "2099-01-01_hansard_c_d_000004_p000002").returns(ncpara)
      ncpara.expects(:content=).with("Ayes 231, Noes 307.")

      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000004_p000003').returns(ncpara)
      ncpara.expects(:content=).with("Question accordingly negatived.")

      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000004_p000004').returns(ncpara)
      ncpara.expects(:content=).with("Question put forthwith (Standing Order No. 62(2)), That the Bill be now read a Second Time.")

      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000004_p000005').returns(ncpara)
      ncpara.expects(:content=).with("Question agreed to .")

      NonContributionPara.expects(:find_or_create_by).with(ident: '2099-01-01_hansard_c_d_000004_p000006').returns(ncpara)
      ncpara.expects(:content=).with("Bill accordingly read a Second time.")

      @parser.parse
    end
  end
end


text:
template <class element_class>
void MaxHeap<element_class>::reserve(size_t reservation_size) {
    heap_array.reserve(reservation_size);
}

template <class element_class>
bool MaxHeap<element_class>::empty() const {
    return (heap_array.empty());
}

template <class element_class>
size_t MaxHeap<element_class>::size() const {
    return (heap_array.size());
}

template <class element_class>
const element_class& MaxHeap<element_class>::top() const {
    return (heap_array.at(0));
}

template <class element_class>
void MaxHeap<element_class>::push(const element_class& new_element) {
    heap_array.push_back(new_element);
    size_t current_index = heap_array.size() - 1;
    // Heapify
    while (heap_array.at(current_index / 2) < heap_array.at(current_index)) {
        swap(current_index, current_index / 2);
        current_index /= 2;
    }
}

template <class element_class>
void MaxHeap<element_class>::pop() {
    heap_array[0] = heap_array.back();
    heap_array.pop_back();
    size_t current_index = 0, next_index;
    while (max((current_index * 2) + 1, (current_index * 2) + 2)) {
        next_index = max((current_index * 2) + 1, (current_index * 2) + 2);
        swap(current_index, next_index);
        current_index = next_index;
    }
}

template <class element_class>
void MaxHeap<element_class>::swap(size_t a, size_t b) {
    element_class temp = heap_array.at(a);
    heap_array[a] = heap_array[b];
    heap_array[b] = temp;
}

template <class element_class>
size_t MaxHeap<element_class>::max(size_t a, size_t b) {
    if (a < heap_array.size()) {
        if (b < heap_array.size()) {
            if (heap_array.at(a) < heap_array.at(b)) {
                return (b);
            } else {
                return (a);
            }
        } else {
            return (a);
        }
    } else if (b < heap_array.size()) {
        return (b);
    } else {
        return (0);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ber. dt. bot. Ges. 36: 53 (1963)

#### Original name
Sebacina dimitica Oberw., 1963

### Remarks
null


text:
class StaticPagesController < ApplicationController

  def show
   if allowed_to?(params[:id])
     render :template => "static_pages/#{params[:id]}"
   elsif !YAML::load(File.open("#{YamledAcl.files_with_permissions_path}/static_pages.yml"))[params[:id]]
     render_404
   else
     raise YamledAcl::AccessDenied
   end
  end

end


text:
DGLE_DYNAMIC_FUNC // Include GetEngine and FreeEngine functions to load engine library at runtime.

#define APP_CAPTION "Pacman"

#define DLL_PATH "..\\DGLE\\bin\\windows\\DGLE.dll"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	IEngineCore *pEngineCore = NULL;

	if (GetEngine(DLL_PATH, pEngineCore))
	{
		// s - standard, l - labyrinth, rl - random labyrinth mode
		Game game(pEngineCore, "s");

		//pEngineCore->ConsoleVisible(true); // show engine console (you can use "~" key to show it in any application)

		if (SUCCEEDED(pEngineCore->InitializeEngine(NULL, APP_CAPTION, TEngineWindow(SCREEN_WIDTH, SCREEN_HEIGHT, false, false, MM_4X), 15u)))
			pEngineCore->StartEngine();

		FreeEngine();
	}
	else
		MessageBox(NULL,"Couldn't load \"" DLL_PATH "\"!", APP_CAPTION, MB_OK | MB_ICONERROR | MB_SETFOREGROUND);

	return 0;
}


text:
package org.apache.accumulo.core.iteratorsImpl.system;

import org.apache.accumulo.core.client.sample.RowSampler;
import org.apache.accumulo.core.client.sample.Sampler;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.Filter;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;

public class SampleIterator extends Filter {

  private Sampler sampler = new RowSampler();

  public SampleIterator(SortedKeyValueIterator<Key,Value> iter, Sampler sampler) {
    setSource(iter);
    this.sampler = sampler;
  }

  @Override
  public boolean accept(Key k, Value v) {
    return sampler.accept(k);
  }

  @Override
  public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) {
    return new SampleIterator(getSource().deepCopy(env), sampler);
  }
}


text:
package connect.view.payment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;

import javax.crypto.spec.DESedeKeySpec;

import connect.db.MemoryDataManager;
import connect.db.SharedPreferenceUtil;
import connect.db.green.DaoHelper.ParamManager;
import connect.ui.activity.R;
import connect.ui.activity.login.bean.UserBean;
import connect.ui.activity.set.PaymentActivity;
import connect.ui.activity.set.bean.PaySetBean;
import connect.ui.adapter.ViewPagerAdapter;
import connect.utils.ActivityUtil;
import connect.utils.ProtoBufUtil;
import connect.utils.StringUtil;
import connect.utils.system.SystemDataUtil;
import connect.utils.system.SystemUtil;
import connect.utils.UriUtil;
import connect.utils.cryption.DecryptionUtil;
import connect.utils.cryption.EncryptionUtil;
import connect.utils.cryption.SupportKeyUril;
import connect.utils.okhttp.OkHttpUtil;
import connect.utils.okhttp.ResultCall;
import connect.view.ControlScrollViewPager;
import connect.view.MdStyleProgress;
import protos.Connect;

/**
 * Pay components
 * Created by Administrator on 2016/12/23.
 */
public class PaymentPwd implements View.OnClickListener{

    private ControlScrollViewPager viewPager;

    private Dialog dialog;

    private MdStyleProgress progressBar;
    private OnTrueListener onTrueListener;
    private PaySetBean paySetBean;
    private VirtualKeyboardView keyboardView;
    private Activity activity;
    private ImageView closeImg;
    /** Text state */
    private TextView statusTv;
    /** The current number of ViewPage pages */
    private int currentIndex;
    /**
     * Pay the password status
     * 0: default 1: no password set 2: set password again input 3: payment success 4: payment failed 5: payment
     */
    private int statusPay = 0;
    private String passFrist = "";
    private PayEditView payEdit;
    private TextView titleTv;

    /**
     * show pay the password box
     */
    public Dialog showPaymentPwd(Activity activity, final OnTrueListener onTrueListener) {
        this.activity = activity;
        paySetBean = ParamManager.getInstance().getPaySet();

        this.onTrueListener = onTrueListener;
        dialog = new Dialog(activity, R.style.Dialog);
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_pay_password, null);
        dialog.setContentView(view);

        viewPager = (ControlScrollViewPager) view.findViewById(R.id.view_pager);
        closeImg = (ImageView) view.findViewById(R.id.close_img);
        closeImg.setOnClickListener(this);
        initViewPage();

        Window mWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = SystemDataUtil.getScreenWidth();
        mWindow.setGravity(Gravity.BOTTOM);
        mWindow.setWindowAnimations(R.style.DialogAnim);
        mWindow.setAttributes(lp);
        dialog.show();

        titleTv = (TextView)view.findViewById(R.id.title_tv);

        if(paySetBean != null && paySetBean.getNoSecretPay()){
            statusChange(5);
            onTrueListener.onTrue();
        }

        if (paySetBean == null || TextUtils.isEmpty(paySetBean.getPayPin())) {
            titleTv.setText(R.string.Set_Set_Payment_Password);
            statusChange(1);
        }

        return dialog;
    }

    private void initViewPage() {
        ArrayList<View> arrayList = new ArrayList<>();
        View editPass = LayoutInflater.from(activity).inflate(R.layout.dialog_pay_edit_pass, null);
        View passForget = LayoutInflater.from(activity).inflate(R.layout.dialog_pay_forget, null);
        View setPay = LayoutInflater.from(activity).inflate(R.layout.dialog_pay_setpay, null);
        arrayList.add(editPass);
        arrayList.add(passForget);
        arrayList.add(setPay);

        viewPager.setAdapter(new ViewPagerAdapter(arrayList));
        viewPager.addOnPageChangeListener(pageChangeListener);
        viewPager.setScrollble(false);

        initEditPay(editPass);
        initPassForget(passForget);
        initSetPay(setPay);
    }

    private void initSetPay(View view) {
        TextView retryTv = (TextView) view.findViewById(R.id.retry_tv);
        retryTv.setOnClickListener(this);
    }

    private void initEditPay(View view) {
        progressBar = (MdStyleProgress) view.findViewById(R.id.progress);
        payEdit = (PayEditView) view.findViewById(R.id.pay_edit);
        statusTv = (TextView)view.findViewById(R.id.status_tv);
        keyboardView = (VirtualKeyboardView) view.findViewById(R.id.virtualKeyboardView);
        keyboardView.setAddNumberListence(new VirtualKeyboardView.AddNumberListence() {
            @Override
            public void changeText(String value) {
                payEdit.setEditText(value);
            }
        });
        payEdit.setEditClosePan();
        payEdit.setInputCompleteListener(completeListener);
    }

    private void initPassForget(View view) {
        TextView forgetTv = (TextView) view.findViewById(R.id.forget_tv);
        TextView retryTv = (TextView) view.findViewById(R.id.retry_tv);
        retryTv.setOnClickListener(this);
        forgetTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.close_img:
                dialog.cancel();
                break;
            case R.id.retry_tv:
                viewPager.setCurrentItem(0);
                break;
            case R.id.forget_tv:
                ActivityUtil.next(activity, PaymentActivity.class);
                break;
            default:
                break;
        }
    }

    private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float offset, int positionOffsetPixels) {

        }
        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    paySetBean = ParamManager.getInstance().getPaySet();
                    if(TextUtils.isEmpty(paySetBean.getPayPin())){
                        statusChange(1);
                    }else{
                        statusChange(0);
                    }
                    break;
                default:
                    break;
            }
            currentIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    /**
     * Password input box to listen
     */
    PayEditView.InputCompleteListener completeListener = new PayEditView.InputCompleteListener(){
        @Override
        public void inputComplete(String pass) {
            if(statusPay == 1 || statusPay == 2){
                setPayPass(pass);
                return;
            }
            // Verify the payment password
            statusChange(5);
            if(TextUtils.isEmpty(paySetBean.getVersionPay()) || paySetBean.getVersionPay().equals("0")){
                viewPager.setCurrentItem(1);
            }else{
                getPayVersion(pass);
            }
        }
    };

    /**
     * set password
     * @param pass
     */
    private void setPayPass(String pass){
        // Set the password flow (record the first password)
        if(statusPay == 1){
            passFrist = pass;
            statusChange(2);
            return;
        }
        // Re-enter the password
        if(statusPay == 2){
            if(passFrist.equals(pass)){
                keyboardView.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.VISIBLE);
                payEdit.setVisibility(View.GONE);
                statusTv.setText(R.string.Wallet_Verifying);
                requestSetPay(pass);
            }else{
                titleTv.setText(R.string.Wallet_PINs_do_not_match);
                viewPager.setCurrentItem(2);
            }
            return;
        }
    }

    /**
     * Verify that the payment password is correct
     * @param pass
     */
    private void decodePass(String pass){
        if(!TextUtils.isEmpty(paySetBean.getPayPin())){
            try {
                byte[] ecdh  = SupportKeyUril.rawECDHkey(MemoryDataManager.getInstance().getPriKey(),
                        MemoryDataManager.getInstance().getPubKey());
                byte[] valueByte = StringUtil.hexStringToBytes(paySetBean.getPayPin());
                byte[] passByte = DecryptionUtil.decodeAESGCM(SupportKeyUril.EcdhExts.NONE,ecdh,Connect.GcmData.parseFrom(valueByte));
                String payPass = new String(passByte,"UTF-8");
                if (pass.equals(payPass)) {// Enter the payment password correctly
                    onTrueListener.onTrue();
                } else {// Incorrect password
                    viewPager.setCurrentItem(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Modify the View display according to the status
     * @param status
     */
    private void statusChange(int status) {
        statusPay = status;
        switch (status){
            case 0:
                keyboardView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                payEdit.setVisibility(View.VISIBLE);
                statusTv.setText("");
                break;
            case 1://There is no set the password
                statusTv.setText(R.string.Wallet_Enter_4_Digits);
                titleTv.setText(R.string.Set_Set_Payment_Password);
                break;
            case 2://Set the password Input again
                statusTv.setText(R.string.Wallet_Enter_again);
                titleTv.setText(R.string.Wallet_Confirm_Payment_password);
                TranslateAnimation animation = new TranslateAnimation(500, 0f, 0f, 0f);
                animation.setDuration(200);
                payEdit.startAnimation(animation);
                break;
            case 3://Pay for success
                statusTv.setText(R.string.Wallet_Payment_Successful);
                break;
            case 4://Pay for failure
                statusTv.setText(R.string.Wallet_Pay_Faied);
                break;
            case 5://In the payment
                keyboardView.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.VISIBLE);
                payEdit.setVisibility(View.GONE);
                statusTv.setText(R.string.Wallet_Verifying);
                break;
        }
    }

    /**
     * The success of the payment failed
     * @param status
     */
    public void closeStatusDialog(MdStyleProgress.Status status) {
        closeStatusDialog(status, null);
    }

    public void closeStatusDialog(final MdStyleProgress.Status status, final OnAnimationListener onAnimationListener) {
        //Sleep 2s Loading
        Handler handler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                if(status == MdStyleProgress.Status.LoadSuccess){
                    statusChange(3);
                    progressBar.setStatus(status);
                    progressBar.startAnima();
                }else if(status == MdStyleProgress.Status.LoadFail){
                    statusChange(4);
                    progressBar.setStatus(status);
                    progressBar.failAnima();
                }
                Handler handler = new Handler(Looper.getMainLooper()){
                    @Override
                    public void handleMessage(Message msg) {
                        dialog.dismiss();
                        if(onAnimationListener != null){
                            onAnimationListener.onComplete();
                        }
                    }
                };
                //Sleep 1.3s (Successful failure time)
                handler.sendEmptyMessageDelayed(1,1300);
            }
        };
        //Sleep 1s (Circle time)
        handler.sendEmptyMessageDelayed(1,1000);
    }

    /**
     * Get the payment password version
     * @param pass
     */
    private void getPayVersion(final String pass){
        Connect.PayPinVersion payPinVersion = Connect.PayPinVersion.newBuilder()
                .setVersion(paySetBean.getVersionPay())
                .build();
        OkHttpUtil.getInstance().postEncrySelf(UriUtil.SETTING_PAY_VERSION, payPinVersion, new ResultCall<Connect.HttpResponse>() {
            @Override
            public void onResponse(Connect.HttpResponse response) {
                try {
                    Connect.IMResponse imResponse = Connect.IMResponse.parseFrom(response.getBody().toByteArray());
                    Connect.StructData structData = DecryptionUtil.decodeAESGCMStructData(imResponse.getCipherData());
                    Connect.PayPinVersion payPinVersion = Connect.PayPinVersion.parseFrom(structData.getPlainData());
                    if(ProtoBufUtil.getInstance().checkProtoBuf(payPinVersion)){
                        if(payPinVersion.getVersion().equals(paySetBean.getVersionPay()) ){
                            decodePass(pass);
                        }else{
                            requestSetPayInfo(pass);
                        }
                        paySetBean.setVersionPay(payPinVersion.getVersion());
                    }
                } catch (InvalidProtocolBufferException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Connect.HttpResponse response) {

            }
        });
    }

    /**
     * Synchronize payment settings
     * @param pass
     */
    public void requestSetPayInfo(final String pass) {
        OkHttpUtil.getInstance().postEncrySelf(UriUtil.SETTING_PAY_SUNC, ByteString.copyFrom(SupportKeyUril.createrBinaryRandom()),
                new ResultCall<Connect.HttpResponse>() {
                    @Override
                    public void onResponse(Connect.HttpResponse response) {
                        try {
                            Connect.IMResponse imResponse = Connect.IMResponse.parseFrom(response.getBody().toByteArray());
                            Connect.StructData structData = DecryptionUtil.decodeAESGCMStructData(imResponse.getCipherData());
                            Connect.PaymentSetting paymentSetting = Connect.PaymentSetting.parseFrom(structData.getPlainData());
                            if(ProtoBufUtil.getInstance().checkProtoBuf(paymentSetting)){
                                paySetBean.setPayPin(paymentSetting.getPayPin());
                                ParamManager.getInstance().putPaySet(paySetBean);
                                decodePass(pass);
                            }
                        } catch (InvalidProtocolBufferException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Connect.HttpResponse response) {

                    }
                });
    }

    /**
     * Set up payment password
     * @param pass
     */
    private void requestSetPay(String pass){
        byte[] ecdh  = SupportKeyUril.rawECDHkey(MemoryDataManager.getInstance().getPriKey(),MemoryDataManager.getInstance().getPubKey());
        try {
            Connect.GcmData gcmData = EncryptionUtil.encodeAESGCM(SupportKeyUril.EcdhExts.NONE, ecdh, pass.getBytes("UTF-8"));
            byte[] gcmDataByte = gcmData.toByteArray();
            final String encryPass = StringUtil.bytesToHexString(gcmDataByte);
            Connect.PayPin payPin = Connect.PayPin.newBuilder()
                    .setPayPin(encryPass)
                    .build();
            OkHttpUtil.getInstance().postEncrySelf(UriUtil.SETTING_PAY_PIN_SETTING, payPin, new ResultCall<Connect.HttpResponse>() {
                @Override
                public void onResponse(Connect.HttpResponse response) {
                    try {
                        Connect.IMResponse imResponse = Connect.IMResponse.parseFrom(response.getBody().toByteArray());
                        Connect.StructData structData = DecryptionUtil.decodeAESGCMStructData(imResponse.getCipherData());
                        Connect.PayPinVersion payPinVersion = Connect.PayPinVersion.parseFrom(structData.getPlainData());
                        if(ProtoBufUtil.getInstance().checkProtoBuf(payPinVersion)){
                            paySetBean.setPayPin(encryPass);
                            paySetBean.setVersionPay(payPinVersion.getVersion());
                            ParamManager.getInstance().putPaySet(paySetBean);
                            onTrueListener.onTrue();
                        }
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Connect.HttpResponse response) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnTrueListener {

        void onTrue();

    }

    public interface OnAnimationListener {
        void onComplete();
    }

}


text:
using System;
using NUnit.Framework;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;

namespace StructureMap.Testing.Graph
{
    [TestFixture]
    public class DefaultConventionScanningTester
    {
        [SetUp]
        public void SetUp()
        {
            PluginCache.ResetAll();
        }

        [Test]
        public void FindPluginType()
        {
            Assert.AreEqual(typeof (IConvention), new DefaultConventionScanner().FindPluginType(typeof (Convention)));
            Assert.IsNull(new DefaultConventionScanner().FindPluginType(GetType()));
        }

        [Test]
        public void Process_to_Container()
        {
            var container = new Container(registry =>
            {
                registry.Scan(x =>
                {
                    x.TheCallingAssembly();
                    x.Convention<DefaultConventionScanner>();
                });
            });

            container.GetInstance<IConvention>().ShouldBeOfType<Convention>();
        }

        [Test]
        public void Process_to_Container_2()
        {
            var container = new Container(registry =>
            {
                registry.Scan(x =>
                {
                    x.TheCallingAssembly();
                    x.With(new DefaultConventionScanner());
                });
            });

            Assert.IsInstanceOfType(typeof (Convention), container.GetInstance<IConvention>());
        }

        [Test]
        public void Process_to_PluginGraph()
        {
            var graph = new PluginGraph();
            var scanner = new DefaultConventionScanner();

            var registry = new Registry();

            scanner.Process(typeof (Convention), registry);

            registry.ConfigurePluginGraph(graph);

            Assert.IsFalse(graph.PluginFamilies.Contains(typeof (IServer)));
            Assert.IsTrue(graph.PluginFamilies.Contains(typeof (IConvention)));

            PluginFamily family = graph.FindFamily(typeof (IConvention));
            family.Seal();
            Assert.AreEqual(1, family.InstanceCount);
        }

        [Test]
        public void can_configure_plugin_families_via_dsl()
        {
            var container = new Container(registry => registry.Scan(x =>
            {
                x.TheCallingAssembly();
                x.WithDefaultConventions().OnAddedPluginTypes(t => t.Singleton());
            }));

            var firstInstance = container.GetInstance<IConvention>();
            var secondInstance = container.GetInstance<IConvention>();
            secondInstance.ShouldBeTheSameAs(firstInstance);
        }

    }

    public interface IConvention
    {
    }

    public interface IServer
    {
    }

    public class Convention : IConvention, IServer
    {
        public void Go()
        {
            throw new NotImplementedException();
        }
    }

    public class Something : IConvention
    {
    }
}


text:
export default {
  NONE: 'none',
  LOADING: 'loading',
  READY: 'ready',
  FAILED: 'failed'
};


text:
namespace Microsoft.Azure.Insights
{
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// MetricDefinitionsOperations operations.
    /// </summary>
    public partial interface IMetricDefinitionsOperations
    {
        /// <summary>
        /// Lists the metric definitions for the resource.
        /// </summary>
        /// <param name='resourceUri'>
        /// The identifier of the resource.
        /// </param>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<MetricDefinition>>> ListWithHttpMessagesAsync(string resourceUri, Microsoft.Rest.Azure.OData.ODataQuery<MetricDefinition> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<MetricDefinition>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
    }
}


text:
<?php
namespace Sac\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="pedidos")
 */
class Pedidos
{
	/**
	 * @ORM\Id
	 * @ORM\GeneratedValue
	 * @ORM\Column(name="id")
	 */
	protected $id;

	/**
	 * @ORM\Column(name="descricao")
	 */
	protected $descricao;

	// Returns ID of this chamados.
	public function getId()
	{
		return $this->id;
	}

	// Sets ID of this chamados.
	public function setId($id)
	{
		$this->id = $id;
	}

	// Returns descricao.
	public function getDescricao()
	{
		return $this->descricao;
	}

	// Sets descricao.
	public function setDescricao($descricao)
	{
		$this->descricao = $descricao;
	}

}