text:
extern "C" {
#include <ovsdb_wrapper.h>
};
#include <ovs_tor_agent/tor_agent_init.h>
#include <ovsdb_client.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <physical_switch_ovsdb.h>
#include <logical_switch_ovsdb.h>
#include <physical_port_ovsdb.h>
#include <vlan_port_binding_ovsdb.h>
#include <vm_interface_ksync.h>

#include <oper/vn.h>
#include <oper/interface_common.h>
#include <oper/physical_device_vn.h>
#include <ovsdb_sandesh.h>
#include <ovsdb_types.h>

using namespace OVSDB;

VlanPortBindingEntry::VlanPortBindingEntry(VlanPortBindingTable *table,
        const std::string &physical_device, const std::string &physical_port,
        uint16_t vlan_tag, const std::string &logical_switch) :
    OvsdbDBEntry(table_), logical_switch_name_(logical_switch),
    physical_port_name_(physical_port), physical_device_name_(physical_device),
    vlan_(vlan_tag), vmi_uuid_(nil_uuid()), old_logical_switch_name_(),
    logical_switch_(NULL, this) {
}

VlanPortBindingEntry::VlanPortBindingEntry(VlanPortBindingTable *table,
        const VlanLogicalInterface *entry) : OvsdbDBEntry(table_),
    logical_switch_name_(), physical_port_name_(entry->phy_intf_display_name()),
    physical_device_name_(entry->phy_dev_display_name()), vlan_(entry->vlan()),
    vmi_uuid_(nil_uuid()), old_logical_switch_name_(),
    logical_switch_(NULL, this) {
}

VlanPortBindingEntry::VlanPortBindingEntry(VlanPortBindingTable *table,
        const VlanPortBindingEntry *key) : OvsdbDBEntry(table),
    logical_switch_name_(key->logical_switch_name_),
    physical_port_name_(key->physical_port_name_),
    physical_device_name_(key->physical_device_name_), vlan_(key->vlan_),
    vmi_uuid_(nil_uuid()), old_logical_switch_name_(),
    logical_switch_(NULL, this) {
}

void VlanPortBindingEntry::PreAddChange() {
    if (!logical_switch_name_.empty()) {
        LogicalSwitchTable *l_table =
            table_->client_idl()->logical_switch_table();
        LogicalSwitchEntry ls_key(l_table, logical_switch_name_.c_str());
        logical_switch_ =
            static_cast<LogicalSwitchEntry *>(l_table->GetReference(&ls_key));
    } else {
        logical_switch_ = NULL;
    }
}

void VlanPortBindingEntry::PostDelete() {
    logical_switch_ = NULL;
}

void VlanPortBindingEntry::AddMsg(struct ovsdb_idl_txn *txn) {
    PhysicalPortTable *p_table = table_->client_idl()->physical_port_table();
    PhysicalPortEntry key(p_table, physical_device_name_, physical_port_name_);
    physical_port_ = p_table->GetReference(&key);
    PhysicalPortEntry *port =
        static_cast<PhysicalPortEntry *>(physical_port_.get());

    // update logical switch name propagated to OVSDB server, this will
    // be used in change Operation to reduce the unncessary computation
    // when there is change which VlanPortBindingEntry is not
    // interested into
    old_logical_switch_name_ = logical_switch_name_;
    if (!logical_switch_name_.empty()) {
        port->AddBinding(vlan_,
                static_cast<LogicalSwitchEntry *>(logical_switch_.get()));
        OVSDB_TRACE(Trace, "Adding port vlan binding port " +
                physical_port_name_ + " vlan " + integerToString(vlan_) +
                " to Logical Switch " + logical_switch_name_);
    } else {
        OVSDB_TRACE(Trace, "Deleting port vlan binding port " +
                physical_port_name_ + " vlan " + integerToString(vlan_));
        port->DeleteBinding(vlan_, NULL);
    }

    // Don't trigger update for stale entries
    if (!stale()) {
        port->TriggerUpdate();
    }
}

void VlanPortBindingEntry::ChangeMsg(struct ovsdb_idl_txn *txn) {
    if (logical_switch_name_ == old_logical_switch_name_) {
        // no change return from here.
        return;
    }
    PhysicalPortEntry *port =
        static_cast<PhysicalPortEntry *>(physical_port_.get());
    OVSDB_TRACE(Trace, "Changing port vlan binding port " +
            physical_port_name_ + " vlan " + integerToString(vlan_));
    port->DeleteBinding(vlan_, NULL);

    AddMsg(txn);
}

void VlanPortBindingEntry::DeleteMsg(struct ovsdb_idl_txn *txn) {
    if (!physical_port_) {
        return;
    }
    PhysicalPortEntry *port =
        static_cast<PhysicalPortEntry *>(physical_port_.get());
    OVSDB_TRACE(Trace, "Deleting port vlan binding port " +
            physical_port_name_ + " vlan " + integerToString(vlan_));
    port->DeleteBinding(vlan_,
            static_cast<LogicalSwitchEntry *>(logical_switch_.get()));
    port->TriggerUpdate();
}

bool VlanPortBindingEntry::Sync(DBEntry *db_entry) {
    VlanLogicalInterface *entry =
        static_cast<VlanLogicalInterface *>(db_entry);
    std::string ls_name;
    boost::uuids::uuid vmi_uuid(nil_uuid());
    bool change = false;

    if (entry->vm_interface()) {
        vmi_uuid = entry->vm_interface()->GetUuid();
    }

    if (entry->vm_interface() && entry->vm_interface()->vn()) {
        ls_name = UuidToString(entry->vm_interface()->vn()->GetUuid());
    }

    if (vmi_uuid_ != vmi_uuid) {
        vmi_uuid_ = vmi_uuid;
        change = true;
    }

    if (ls_name != logical_switch_name_) {
        logical_switch_name_ = ls_name;
        change = true;
    }

    return change;
}

bool VlanPortBindingEntry::IsLess(const KSyncEntry &entry) const {
    const VlanPortBindingEntry &vps_entry =
        static_cast<const VlanPortBindingEntry&>(entry);
    if (vlan_ != vps_entry.vlan_)
        return vlan_ < vps_entry.vlan_;
    if (physical_device_name_ != vps_entry.physical_device_name_)
        return physical_device_name_ < vps_entry.physical_device_name_;
    return physical_port_name_ < vps_entry.physical_port_name_;
}

KSyncEntry *VlanPortBindingEntry::UnresolvedReference() {
    PhysicalSwitchTable *ps_table =
        table_->client_idl()->physical_switch_table();
    PhysicalSwitchEntry ps_key(ps_table, physical_device_name_.c_str());
    PhysicalSwitchEntry *p_switch =
        static_cast<PhysicalSwitchEntry *>(ps_table->GetReference(&ps_key));
    if (!p_switch->IsResolved()) {
        OVSDB_TRACE(Trace, "Physical Switch unavailable for Port Vlan Binding "+
                physical_port_name_ + " vlan " + integerToString(vlan_) +
                " to Logical Switch " + logical_switch_name_);
        return p_switch;
    }

    PhysicalPortTable *p_table = table_->client_idl()->physical_port_table();
    PhysicalPortEntry key(p_table, physical_device_name_, physical_port_name_);
    PhysicalPortEntry *p_port =
        static_cast<PhysicalPortEntry *>(p_table->GetReference(&key));
    if (!p_port->IsResolved()) {
        OVSDB_TRACE(Trace, "Physical Port unavailable for Port Vlan Binding " +
                physical_port_name_ + " vlan " + integerToString(vlan_) +
                " to Logical Switch " + logical_switch_name_);
        return p_port;
    }

    // check for VMI only if entry is not stale marked.
    if (!stale()) {
        VMInterfaceKSyncObject *vm_intf_table =
            table_->client_idl()->vm_interface_table();
        VMInterfaceKSyncEntry vm_intf_key(vm_intf_table, vmi_uuid_);
        VMInterfaceKSyncEntry *vm_intf = static_cast<VMInterfaceKSyncEntry *>(
                vm_intf_table->GetReference(&vm_intf_key));
        if (!vm_intf->IsResolved()) {
            OVSDB_TRACE(Trace, "VM Interface unavailable for Port Vlan Binding " +
                    physical_port_name_ + " vlan " + integerToString(vlan_) +
                    " to Logical Switch " + logical_switch_name_);
            return vm_intf;
        } else if (logical_switch_name_.empty()) {
            // update latest name after resolution.
            logical_switch_name_ = vm_intf->vn_name();
        }
    }

    if (!logical_switch_name_.empty()) {
        // Check only if logical switch name is present.
        LogicalSwitchTable *l_table =
            table_->client_idl()->logical_switch_table();
        LogicalSwitchEntry ls_key(l_table, logical_switch_name_.c_str());
        LogicalSwitchEntry *ls_entry =
            static_cast<LogicalSwitchEntry *>(l_table->GetReference(&ls_key));
        if (!ls_entry->IsResolved()) {
            OVSDB_TRACE(Trace, "Logical Switch  unavailable for Port Vlan "
                    "Binding " + physical_port_name_ + " vlan " +
                    integerToString(vlan_) + " to Logical Switch " +
                    logical_switch_name_);
            return ls_entry;
        }
    }

    return NULL;
}

const std::string &VlanPortBindingEntry::logical_switch_name() const {
    return logical_switch_name_;
}

const std::string &VlanPortBindingEntry::physical_port_name() const {
    return physical_port_name_;
}

const std::string &VlanPortBindingEntry::physical_device_name() const {
    return physical_device_name_;
}

uint16_t VlanPortBindingEntry::vlan() const {
    return vlan_;
}

VlanPortBindingTable::VlanPortBindingTable(OvsdbClientIdl *idl) :
    OvsdbDBObject(idl, true) {
}

VlanPortBindingTable::~VlanPortBindingTable() {
}

KSyncEntry *VlanPortBindingTable::Alloc(const KSyncEntry *key, uint32_t index) {
    const VlanPortBindingEntry *k_entry =
        static_cast<const VlanPortBindingEntry *>(key);
    VlanPortBindingEntry *entry = new VlanPortBindingEntry(this, k_entry);
    return entry;
}

KSyncEntry *VlanPortBindingTable::DBToKSyncEntry(const DBEntry* db_entry) {
    const VlanLogicalInterface *entry =
        static_cast<const VlanLogicalInterface *>(db_entry);
    VlanPortBindingEntry *key = new VlanPortBindingEntry(this, entry);
    return static_cast<KSyncEntry *>(key);
}

KSyncDBObject::DBFilterResp VlanPortBindingTable::OvsdbDBEntryFilter(
        const DBEntry *entry, const OvsdbDBEntry *ovsdb_entry) {
    const VlanLogicalInterface *l_port =
        dynamic_cast<const VlanLogicalInterface *>(entry);
    if (l_port == NULL) {
        // Ignore entries other than VLanLogicalInterface.
        return DBFilterIgnore;
    }

    // Logical interface without vm interface is incomplete entry
    // for ovsdb, trigger delete.
    if (l_port->vm_interface() == NULL) {
        if (ovsdb_entry != NULL) {
            OVSDB_TRACE(Trace, "VM Interface Unavialable, Deleting Logical "
                        "Port " + l_port->name());
        } else {
            OVSDB_TRACE(Trace, "VM Interface Unavialable, Ignoring Logical "
                        "Port " + l_port->name());
        }
        return DBFilterDelete;
    }

    // Since we need physical port name and device name as key, ignore entry
    // if physical port or device is not yet present.
    if (l_port->phy_intf_display_name().empty()) {
        OVSDB_TRACE(Trace, "Ignoring Port Vlan Binding due to physical port "
                "name unavailablity Logical port = " + l_port->name());
        return DBFilterIgnore;
    }

    if (l_port->phy_dev_display_name().empty()) {
        OVSDB_TRACE(Trace, "Ignoring Port Vlan Binding due to device name "
                "unavailablity Logical port = " + l_port->name());
        return DBFilterIgnore;
    }
    return DBFilterAccept;
}

/////////////////////////////////////////////////////////////////////////////
// Sandesh routines
/////////////////////////////////////////////////////////////////////////////
VlanPortBindingSandeshTask::VlanPortBindingSandeshTask(
        std::string resp_ctx, AgentSandeshArguments &args) :
    OvsdbSandeshTask(resp_ctx, args), physical_port_("") {
    if (false == args.Get("physical_port", &physical_port_)) {
        physical_port_ = "";
    }
}

VlanPortBindingSandeshTask::VlanPortBindingSandeshTask(
        std::string resp_ctx, const std::string &ip, uint32_t port,
        const std::string &physical_port) :
    OvsdbSandeshTask(resp_ctx, ip, port), physical_port_(physical_port) {
}

VlanPortBindingSandeshTask::~VlanPortBindingSandeshTask() {
}

void VlanPortBindingSandeshTask::EncodeArgs(AgentSandeshArguments &args) {
    if (!physical_port_.empty()) {
        args.Add("physical_port", physical_port_);
    }
}

OvsdbSandeshTask::FilterResp
VlanPortBindingSandeshTask::Filter(KSyncEntry *kentry) {
    if (!physical_port_.empty()) {
        VlanPortBindingEntry *entry =
            static_cast<VlanPortBindingEntry *>(kentry);
        if (entry->physical_port_name().find(
                    physical_port_) != std::string::npos) {
            return FilterAllow;
        }
        return FilterDeny;
    }
    return FilterAllow;
}

void VlanPortBindingSandeshTask::UpdateResp(KSyncEntry *kentry,
                                            SandeshResponse *resp) {
    VlanPortBindingEntry *entry = static_cast<VlanPortBindingEntry *>(kentry);
    OvsdbVlanPortBindingEntry oentry;
    oentry.set_state(entry->StateString());
    oentry.set_physical_port(entry->physical_port_name());
    oentry.set_physical_device(entry->physical_device_name());
    oentry.set_logical_switch(entry->logical_switch_name());
    oentry.set_vlan(entry->vlan());
    OvsdbVlanPortBindingResp *v_resp =
        static_cast<OvsdbVlanPortBindingResp *>(resp);
    std::vector<OvsdbVlanPortBindingEntry> &bindings =
        const_cast<std::vector<OvsdbVlanPortBindingEntry>&>(
                v_resp->get_bindings());
    bindings.push_back(oentry);
}

SandeshResponse *VlanPortBindingSandeshTask::Alloc() {
    return static_cast<SandeshResponse *>(new OvsdbVlanPortBindingResp());
}

KSyncObject *
VlanPortBindingSandeshTask::GetObject(OvsdbClientSession *session) {
    return static_cast<KSyncObject *>(
            session->client_idl()->vlan_port_table());
}

void OvsdbVlanPortBindingReq::HandleRequest() const {
    VlanPortBindingSandeshTask *task =
        new VlanPortBindingSandeshTask(context(), get_session_remote_ip(),
                                       get_session_remote_port(),
                                       get_physical_port());
    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Enqueue(task);
}


text:
namespace MineAPI.Protocol.Packets.Play.Clientbound
{
    [Packet(0x0A, PacketDirection.Clientbound)]
    public struct HeldItemChangePacket : IPacket
    {
        [PacketField(0, FieldType.Byte)]
        public sbyte Slot;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "core/html/HTMLVideoElement.h"

#include "bindings/core/v8/ExceptionState.h"
#include "core/CSSPropertyNames.h"
#include "core/HTMLNames.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/Settings.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/layout/LayoutImage.h"
#include "core/layout/LayoutVideo.h"
#include "platform/UserGestureIndicator.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/gpu/Extensions3DUtil.h"
#include "public/platform/WebCanvas.h"
#include "public/platform/WebGraphicsContext3D.h"

namespace blink {

using namespace HTMLNames;

inline HTMLVideoElement::HTMLVideoElement(Document& document)
    : HTMLMediaElement(videoTag, document)
{
    if (document.settings())
        m_defaultPosterURL = AtomicString(document.settings()->defaultVideoPosterURL());
}

PassRefPtrWillBeRawPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document)
{
    RefPtrWillBeRawPtr<HTMLVideoElement> video = adoptRefWillBeNoop(new HTMLVideoElement(document));
    video->ensureUserAgentShadowRoot();
    video->suspendIfNeeded();
    return video.release();
}

DEFINE_TRACE(HTMLVideoElement)
{
    visitor->trace(m_imageLoader);
    HTMLMediaElement::trace(visitor);
}

bool HTMLVideoElement::layoutObjectIsNeeded(const ComputedStyle& style)
{
    return HTMLElement::layoutObjectIsNeeded(style);
}

LayoutObject* HTMLVideoElement::createLayoutObject(const ComputedStyle&)
{
    return new LayoutVideo(this);
}

void HTMLVideoElement::attach(const AttachContext& context)
{
    HTMLMediaElement::attach(context);

    updateDisplayState();
    if (shouldDisplayPosterImage()) {
        if (!m_imageLoader)
            m_imageLoader = HTMLImageLoader::create(this);
        m_imageLoader->updateFromElement();
        if (layoutObject())
            toLayoutImage(layoutObject())->imageResource()->setImageResource(m_imageLoader->image());
    }
}

void HTMLVideoElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
    if (name == widthAttr)
        addHTMLLengthToStyle(style, CSSPropertyWidth, value);
    else if (name == heightAttr)
        addHTMLLengthToStyle(style, CSSPropertyHeight, value);
    else
        HTMLMediaElement::collectStyleForPresentationAttribute(name, value, style);
}

bool HTMLVideoElement::isPresentationAttribute(const QualifiedName& name) const
{
    if (name == widthAttr || name == heightAttr)
        return true;
    return HTMLMediaElement::isPresentationAttribute(name);
}

void HTMLVideoElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    if (name == posterAttr) {
        // In case the poster attribute is set after playback, don't update the
        // display state, post playback the correct state will be picked up.
        if (displayMode() < Video || !hasAvailableVideoFrame()) {
            // Force a poster recalc by setting m_displayMode to Unknown directly before calling updateDisplayState.
            HTMLMediaElement::setDisplayMode(Unknown);
            updateDisplayState();
        }
        if (!posterImageURL().isEmpty()) {
            if (!m_imageLoader)
                m_imageLoader = HTMLImageLoader::create(this);
            m_imageLoader->updateFromElement(ImageLoader::UpdateIgnorePreviousError);
        } else {
            if (layoutObject())
                toLayoutImage(layoutObject())->imageResource()->setImageResource(0);
        }
        // Notify the player when the poster image URL changes.
        if (webMediaPlayer())
            webMediaPlayer()->setPoster(posterImageURL());
    } else {
        HTMLMediaElement::parseAttribute(name, value);
    }
}

bool HTMLVideoElement::supportsFullscreen() const
{
    if (!document().page())
        return false;

    if (!webMediaPlayer())
        return false;

    return true;
}

unsigned HTMLVideoElement::videoWidth() const
{
    if (!webMediaPlayer())
        return 0;
    return webMediaPlayer()->naturalSize().width;
}

unsigned HTMLVideoElement::videoHeight() const
{
    if (!webMediaPlayer())
        return 0;
    return webMediaPlayer()->naturalSize().height;
}

bool HTMLVideoElement::isURLAttribute(const Attribute& attribute) const
{
    return attribute.name() == posterAttr || HTMLMediaElement::isURLAttribute(attribute);
}

const AtomicString HTMLVideoElement::imageSourceURL() const
{
    const AtomicString& url = getAttribute(posterAttr);
    if (!stripLeadingAndTrailingHTMLSpaces(url).isEmpty())
        return url;
    return m_defaultPosterURL;
}

void HTMLVideoElement::setDisplayMode(DisplayMode mode)
{
    DisplayMode oldMode = displayMode();
    KURL poster = posterImageURL();

    if (!poster.isEmpty()) {
        // We have a poster path, but only show it until the user triggers display by playing or seeking and the
        // media engine has something to display.
        // Don't show the poster if there is a seek operation or
        // the video has restarted because of loop attribute
        if (mode == Video && oldMode == Poster && !hasAvailableVideoFrame())
            return;
    }

    HTMLMediaElement::setDisplayMode(mode);

    if (layoutObject() && displayMode() != oldMode)
        layoutObject()->updateFromElement();
}

void HTMLVideoElement::updateDisplayState()
{
    if (posterImageURL().isEmpty())
        setDisplayMode(Video);
    else if (displayMode() < Poster)
        setDisplayMode(Poster);
}

void HTMLVideoElement::paintCurrentFrame(SkCanvas* canvas, const IntRect& destRect, const SkPaint* paint) const
{
    if (!webMediaPlayer())
        return;

    SkXfermode::Mode mode;
    if (!paint || !SkXfermode::AsMode(paint->getXfermode(), &mode))
        mode = SkXfermode::kSrcOver_Mode;

    // TODO(junov, philipj): crbug.com/456529 Pass the whole SkPaint instead of only alpha and xfermode
    webMediaPlayer()->paint(canvas, destRect, paint ? paint->getAlpha() : 0xFF, mode);
}

bool HTMLVideoElement::copyVideoTextureToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLenum internalFormat, GLenum type, bool premultiplyAlpha, bool flipY)
{
    if (!webMediaPlayer())
        return false;

    ASSERT(Extensions3DUtil::canUseCopyTextureCHROMIUM(GL_TEXTURE_2D, internalFormat, type, 0));
    return webMediaPlayer()->copyVideoTextureToPlatformTexture(context, texture, internalFormat, type, premultiplyAlpha, flipY);
}

bool HTMLVideoElement::hasAvailableVideoFrame() const
{
    if (!webMediaPlayer())
        return false;

    return webMediaPlayer()->hasVideo() && webMediaPlayer()->readyState() >= WebMediaPlayer::ReadyStateHaveCurrentData;
}

void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& exceptionState)
{
    if (isFullscreen())
        return;

    if (!supportsFullscreen()) {
        exceptionState.throwDOMException(InvalidStateError, "This element does not support fullscreen mode.");
        return;
    }

    enterFullscreen();
}

void HTMLVideoElement::webkitExitFullscreen()
{
    if (isFullscreen())
        exitFullscreen();
}

bool HTMLVideoElement::webkitSupportsFullscreen()
{
    return supportsFullscreen();
}

bool HTMLVideoElement::webkitDisplayingFullscreen()
{
    return isFullscreen();
}

void HTMLVideoElement::didMoveToNewDocument(Document& oldDocument)
{
    if (m_imageLoader)
        m_imageLoader->elementDidMoveToNewDocument();
    HTMLMediaElement::didMoveToNewDocument(oldDocument);
}

unsigned HTMLVideoElement::webkitDecodedFrameCount() const
{
    if (!webMediaPlayer())
        return 0;

    return webMediaPlayer()->decodedFrameCount();
}

unsigned HTMLVideoElement::webkitDroppedFrameCount() const
{
    if (!webMediaPlayer())
        return 0;

    return webMediaPlayer()->droppedFrameCount();
}

KURL HTMLVideoElement::posterImageURL() const
{
    String url = stripLeadingAndTrailingHTMLSpaces(imageSourceURL());
    if (url.isEmpty())
        return KURL();
    return document().completeURL(url);
}

KURL HTMLVideoElement::mediaPlayerPosterURL()
{
    return posterImageURL();
}

PassRefPtr<Image> HTMLVideoElement::getSourceImageForCanvas(SourceImageMode mode, SourceImageStatus* status) const
{
    if (!hasAvailableVideoFrame()) {
        *status = InvalidSourceImageStatus;
        return nullptr;
    }

    IntSize intrinsicSize(videoWidth(), videoHeight());
    OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(intrinsicSize);
    if (!imageBuffer) {
        *status = InvalidSourceImageStatus;
        return nullptr;
    }

    paintCurrentFrame(imageBuffer->canvas(), IntRect(IntPoint(0, 0), intrinsicSize), nullptr);

    *status = (mode == CopySourceImageIfVolatile) ? NormalSourceImageStatus : ExternalSourceImageStatus;
    return imageBuffer->copyImage(mode == CopySourceImageIfVolatile ? CopyBackingStore : DontCopyBackingStore, Unscaled);
}

bool HTMLVideoElement::wouldTaintOrigin(SecurityOrigin* destinationSecurityOrigin) const
{
    return !isMediaDataCORSSameOrigin(destinationSecurityOrigin);
}

FloatSize HTMLVideoElement::elementSize() const
{
    return FloatSize(videoWidth(), videoHeight());
}

} // namespace blink


text:
declare function getSymbolFromCurrency (currencyCode: string): string | undefined
export = getSymbolFromCurrency


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Sự Thật Cần Biết</title>

        <link href="css/bootstrap.min.css" rel="stylesheet">

        <link href="css/grayscale.css" rel="stylesheet">

        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                    </button>

                          suthatcanbiet.com

                                 Facebook

                                 by 500bits.com

Trang blog đang trong thời gian xây dựng.

Mời bạn quay lại sau!


text:
module Faraday
  class Adapter
    class NetHttpPersistent < NetHttp
      dependency 'net/http/persistent'

      private

      def net_http_connection(env)
        @cached_connection ||=
          if Net::HTTP::Persistent.instance_method(:initialize).parameters.first == [:key, :name]
            Net::HTTP::Persistent.new(name: 'Faraday')
          else
            Net::HTTP::Persistent.new('Faraday')
          end

        proxy_uri = proxy_uri(env)
        @cached_connection.proxy = proxy_uri if @cached_connection.proxy_uri != proxy_uri
        @cached_connection
      end

      def proxy_uri(env)
        proxy_uri = nil
        if (proxy = env[:request][:proxy])
          proxy_uri = ::URI::HTTP === proxy[:uri] ? proxy[:uri].dup : ::URI.parse(proxy[:uri].to_s)
          proxy_uri.user = proxy_uri.password = nil
          # awful patch for net-http-persistent 2.8 not unescaping user/password
          (class << proxy_uri; self; end).class_eval do
            define_method(:user) { proxy[:user] }
            define_method(:password) { proxy[:password] }
          end if proxy[:user]
        end
        proxy_uri
      end

      def perform_request(http, env)
        http.request env[:url], create_request(env)
      rescue Errno::ETIMEDOUT => error
        raise Faraday::Error::TimeoutError, error
      rescue Net::HTTP::Persistent::Error => error
        if error.message.include? 'Timeout'
          raise Faraday::Error::TimeoutError, error
        elsif error.message.include? 'connection refused'
          raise Faraday::Error::ConnectionFailed, error
        else
          raise
        end
      end

      def configure_ssl(http, ssl)
        http_set(http, :verify_mode, ssl_verify_mode(ssl))
        http_set(http, :cert_store,  ssl_cert_store(ssl))

        http_set(http, :certificate, ssl[:client_cert]) if ssl[:client_cert]
        http_set(http, :private_key, ssl[:client_key])  if ssl[:client_key]
        http_set(http, :ca_file,     ssl[:ca_file])     if ssl[:ca_file]
        http_set(http, :ssl_version, ssl[:version])     if ssl[:version]
      end

      def http_set(http, attr, value)
        if http.send(attr) != value
          http.send("#{attr}=", value)
        end
      end
    end
  end
end


text:
@interface UIViewController (MASimplestSemiView)

- (void)_presentSemiView:(UIView *)view completion:(void(^)())completionBlock;
- (void)_overlayTapRecognized:(UIGestureRecognizer *)gestureRecognizer;

@end

@implementation UIViewController (MASimplestSemiModal)

#pragma mark - Public Methods

- (void)ma_presentSemiView:(UIView *)view {
    [self _presentSemiView:view completion:NULL];
}

- (void)ma_dismissSemiView {
    UIApplication *app = [UIApplication sharedApplication];

    UIViewController *presentingViewController = objc_getAssociatedObject(app, kSemiModalPresentingViewController);

    UIView *target = presentingViewController.view;
    UIView *container = target.subviews.lastObject;
    UIView *overlay = container.subviews[0];
    UIView *semiModal = container.subviews.lastObject;

    [UIView animateWithDuration:MA_SEMI_MODAL_ANIMATION_DURATION
                          delay:MA_SEMI_MODAL_DISMISS_ANIMATION_DELAY
                        options:MA_SEMI_MODAL_DISMISS_ANIMATION_OPTIONS
                     animations:^{
                         semiModal.frame = CGRectMake(0.f, target.bounds.size.height,
                                                      semiModal.bounds.size.width, semiModal.bounds.size.height);
                         overlay.alpha = 0.f;
                     } completion:^(BOOL finished) {
                         [container removeFromSuperview];
                         objc_setAssociatedObject(app, kSemiModalPresentingViewController, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
                     }];
}

#pragma mark - Private Interface

- (void)_presentSemiView:(UIView *)view completion:(void (^)())completionBlock {
    if (![self.view.subviews containsObject:view]) {
        objc_setAssociatedObject([UIApplication sharedApplication], kSemiModalPresentingViewController,
                                 self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        UIView *container = [[UIView alloc] initWithFrame:self.view.bounds];
        container.backgroundColor = [UIColor clearColor];
        container.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
        overlay.backgroundColor = [UIColor blackColor];
        overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        overlay.alpha = 0.f;
        overlay.gestureRecognizers = @[[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                               action:@selector(_overlayTapRecognized:)]];

        [container addSubview:overlay];

        view.frame = CGRectMake(0.f, self.view.bounds.size.height,
                                view.bounds.size.width, view.bounds.size.height);
        view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;

        [container addSubview:view];

        [self.view addSubview:container];

        [UIView animateWithDuration:MA_SEMI_MODAL_ANIMATION_DURATION
                              delay:MA_SEMI_MODAL_SHOW_ANIMATION_DELAY
                            options:MA_SEMI_MODAL_SHOW_ANIMATION_OPTIONS
                         animations:^{
                             overlay.alpha = MA_SEMI_MODAL_ANIMATION_DURATION;
                             view.frame = CGRectMake(0.f, self.view.bounds.size.height - view.bounds.size.height,
                                                     view.bounds.size.width, view.bounds.size.height);
                         } completion:^(BOOL finished) {
                             if (finished && completionBlock) completionBlock();
                         }];
    }
}

- (void)_overlayTapRecognized:(UIGestureRecognizer *)gestureRecognizer {
    [self ma_dismissSemiView];
}

@end


text:
package chen.testchat.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * 项目名称:    TestChat
 * 创建人:        陈锦军
 * 创建时间:    2017/5/27      10:45
 * QQ:             1981367757
 */

public class ViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> mFragmentList;
        private List<String> mTitleList;

        public ViewPageAdapter(List<Fragment> fragmentList, List<String> titleList, FragmentManager fm) {
                super(fm);
                mFragmentList = fragmentList;
                mTitleList = titleList;
        }

        @Override
        public Fragment getItem(int position) {
                return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
                return mFragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
                return mTitleList.get(position);
        }
}


text:
package org.apache.olingo.odata2.core.edm;

import org.apache.olingo.odata2.api.edm.EdmFacets;
import org.apache.olingo.odata2.api.edm.EdmLiteralKind;
import org.apache.olingo.odata2.api.edm.EdmSimpleType;
import org.apache.olingo.odata2.api.edm.EdmSimpleTypeException;

/**
 * Implementation of the EDM simple type SByte.
 *
 */
public class EdmSByte extends AbstractSimpleType {

  private static final EdmSByte instance = new EdmSByte();

  public static EdmSByte getInstance() {
    return instance;
  }

  @Override
  public boolean isCompatible(final EdmSimpleType simpleType) {
    return simpleType instanceof Bit
        || simpleType instanceof Uint7
        || simpleType instanceof EdmSByte;
  }

  @Override
  public Class<?> getDefaultType() {
    return Byte.class;
  }

  @Override
  protected <T> T internalValueOfString(final String value, final EdmLiteralKind literalKind, final EdmFacets facets,
      final Class<T> returnType) throws EdmSimpleTypeException {
    Byte valueByte;
    try {
      valueByte = Byte.parseByte(value);
    } catch (final NumberFormatException e) {
      throw new EdmSimpleTypeException(EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value), e);
    }

    if (returnType.isAssignableFrom(Byte.class)) {
      return returnType.cast(valueByte);
    } else if (returnType.isAssignableFrom(Short.class)) {
      return returnType.cast(valueByte.shortValue());
    } else if (returnType.isAssignableFrom(Integer.class)) {
      return returnType.cast(valueByte.intValue());
    } else if (returnType.isAssignableFrom(Long.class)) {
      return returnType.cast(valueByte.longValue());
    } else {
      throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType));
    }
  }

  @Override
  protected <T> String internalValueToString(final T value, final EdmLiteralKind literalKind, final EdmFacets facets)
      throws EdmSimpleTypeException {
    if (value instanceof Byte) {
      return value.toString();
    } else if (value instanceof Short || value instanceof Integer || value instanceof Long) {
      if (((Number) value).longValue() >= Byte.MIN_VALUE && ((Number) value).longValue() <= Byte.MAX_VALUE) {
        return value.toString();
      } else {
        throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_ILLEGAL_CONTENT.addContent(value));
      }
    } else {
      throw new EdmSimpleTypeException(EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(value.getClass()));
    }
  }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Vue.js v1.0.21</title>
  <link href="../css/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="../css/main.css" rel="stylesheet"/>

Vue.js v1.0.21

                      <button type="button" class="btn btn-primary btn-block" id="add" v-on:click="add">Add 1000 rows</button>
                      <button type="button" class="btn btn-primary btn-block" id="run" v-on:click="run">Create 1000 rows</button>
                      <button type="button" class="btn btn-primary btn-block" id="update" v-on:click="update">Update every 10th row</button>
                      <button type="button" class="btn btn-primary btn-block" id="hideall" v-on:click="hideAll">HideAll</button>
                      <button type="button" class="btn btn-primary btn-block" id="showall" v-on:click="showAll">ShowAll</button>
                      <button type="button" class="btn btn-primary btn-block" id="runlots" v-on:click="runLots">Create lots of rows</button>
                      <button type="button" class="btn btn-primary btn-block" id="clear" v-on:click="clear">Clear</button>
                      <button type="button" class="btn btn-primary btn-block" id="swaprows" v-on:click="swapRows">Swap Rows</button>

                  {{item.id}}

                      {{item.label}}


text:
module.exports = {
  entry: './index.js',
  output: {
    filename: './public/bundle.js',
    libraryTarget: 'umd',
    library: 'siteweb'
  }
}


text:
FOUNDATION_EXPORT double NumericKeyboardVersionNumber;
FOUNDATION_EXPORT const unsigned char NumericKeyboardVersionString[];


text:
<?php

namespace App\Events;

use App\Events\Event;
use App\BugComment;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewBugComment extends Event
{
    use SerializesModels;

    public $comment;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(BugComment $comment)
    {
        $this->comment = $comment;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}


text:
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

from p4.v1 import p4runtime_pb2 as p4_dot_v1_dot_p4runtime__pb2

class P4RuntimeStub(object):
    """Missing associated documentation comment in .proto file."""

    def __init__(self, channel):
        """Constructor.

        Args:
            channel: A grpc.Channel.
        """
        self.Write = channel.unary_unary(
                '/p4.v1.P4Runtime/Write',
                request_serializer=p4_dot_v1_dot_p4runtime__pb2.WriteRequest.SerializeToString,
                response_deserializer=p4_dot_v1_dot_p4runtime__pb2.WriteResponse.FromString,
                )
        self.Read = channel.unary_stream(
                '/p4.v1.P4Runtime/Read',
                request_serializer=p4_dot_v1_dot_p4runtime__pb2.ReadRequest.SerializeToString,
                response_deserializer=p4_dot_v1_dot_p4runtime__pb2.ReadResponse.FromString,
                )
        self.SetForwardingPipelineConfig = channel.unary_unary(
                '/p4.v1.P4Runtime/SetForwardingPipelineConfig',
                request_serializer=p4_dot_v1_dot_p4runtime__pb2.SetForwardingPipelineConfigRequest.SerializeToString,
                response_deserializer=p4_dot_v1_dot_p4runtime__pb2.SetForwardingPipelineConfigResponse.FromString,
                )
        self.GetForwardingPipelineConfig = channel.unary_unary(
                '/p4.v1.P4Runtime/GetForwardingPipelineConfig',
                request_serializer=p4_dot_v1_dot_p4runtime__pb2.GetForwardingPipelineConfigRequest.SerializeToString,
                response_deserializer=p4_dot_v1_dot_p4runtime__pb2.GetForwardingPipelineConfigResponse.FromString,
                )
        self.StreamChannel = channel.stream_stream(
                '/p4.v1.P4Runtime/StreamChannel',
                request_serializer=p4_dot_v1_dot_p4runtime__pb2.StreamMessageRequest.SerializeToString,
                response_deserializer=p4_dot_v1_dot_p4runtime__pb2.StreamMessageResponse.FromString,
                )
        self.Capabilities = channel.unary_unary(
                '/p4.v1.P4Runtime/Capabilities',
                request_serializer=p4_dot_v1_dot_p4runtime__pb2.CapabilitiesRequest.SerializeToString,
                response_deserializer=p4_dot_v1_dot_p4runtime__pb2.CapabilitiesResponse.FromString,
                )

class P4RuntimeServicer(object):
    """Missing associated documentation comment in .proto file."""

    def Write(self, request, context):
        """Update one or more P4 entities on the target.
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def Read(self, request, context):
        """Read one or more P4 entities from the target.
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def SetForwardingPipelineConfig(self, request, context):
        """Sets the P4 forwarding-pipeline config.
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def GetForwardingPipelineConfig(self, request, context):
        """Gets the current P4 forwarding-pipeline config.
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def StreamChannel(self, request_iterator, context):
        """Represents the bidirectional stream between the controller and the
        switch (initiated by the controller), and is managed for the following
        purposes:
        - connection initiation through client arbitration
        - indicating switch session liveness: the session is live when switch
        sends a positive client arbitration update to the controller, and is
        considered dead when either the stream breaks or the switch sends a
        negative update for client arbitration
        - the controller sending/receiving packets to/from the switch
        - streaming of notifications from the switch
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def Capabilities(self, request, context):
        """Missing associated documentation comment in .proto file."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

def add_P4RuntimeServicer_to_server(servicer, server):
    rpc_method_handlers = {
            'Write': grpc.unary_unary_rpc_method_handler(
                    servicer.Write,
                    request_deserializer=p4_dot_v1_dot_p4runtime__pb2.WriteRequest.FromString,
                    response_serializer=p4_dot_v1_dot_p4runtime__pb2.WriteResponse.SerializeToString,
            ),
            'Read': grpc.unary_stream_rpc_method_handler(
                    servicer.Read,
                    request_deserializer=p4_dot_v1_dot_p4runtime__pb2.ReadRequest.FromString,
                    response_serializer=p4_dot_v1_dot_p4runtime__pb2.ReadResponse.SerializeToString,
            ),
            'SetForwardingPipelineConfig': grpc.unary_unary_rpc_method_handler(
                    servicer.SetForwardingPipelineConfig,
                    request_deserializer=p4_dot_v1_dot_p4runtime__pb2.SetForwardingPipelineConfigRequest.FromString,
                    response_serializer=p4_dot_v1_dot_p4runtime__pb2.SetForwardingPipelineConfigResponse.SerializeToString,
            ),
            'GetForwardingPipelineConfig': grpc.unary_unary_rpc_method_handler(
                    servicer.GetForwardingPipelineConfig,
                    request_deserializer=p4_dot_v1_dot_p4runtime__pb2.GetForwardingPipelineConfigRequest.FromString,
                    response_serializer=p4_dot_v1_dot_p4runtime__pb2.GetForwardingPipelineConfigResponse.SerializeToString,
            ),
            'StreamChannel': grpc.stream_stream_rpc_method_handler(
                    servicer.StreamChannel,
                    request_deserializer=p4_dot_v1_dot_p4runtime__pb2.StreamMessageRequest.FromString,
                    response_serializer=p4_dot_v1_dot_p4runtime__pb2.StreamMessageResponse.SerializeToString,
            ),
            'Capabilities': grpc.unary_unary_rpc_method_handler(
                    servicer.Capabilities,
                    request_deserializer=p4_dot_v1_dot_p4runtime__pb2.CapabilitiesRequest.FromString,
                    response_serializer=p4_dot_v1_dot_p4runtime__pb2.CapabilitiesResponse.SerializeToString,
            ),
    }
    generic_handler = grpc.method_handlers_generic_handler(
            'p4.v1.P4Runtime', rpc_method_handlers)
    server.add_generic_rpc_handlers((generic_handler,))

 # This class is part of an EXPERIMENTAL API.
class P4Runtime(object):
    """Missing associated documentation comment in .proto file."""

    @staticmethod
    def Write(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(request, target, '/p4.v1.P4Runtime/Write',
            p4_dot_v1_dot_p4runtime__pb2.WriteRequest.SerializeToString,
            p4_dot_v1_dot_p4runtime__pb2.WriteResponse.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

    @staticmethod
    def Read(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_stream(request, target, '/p4.v1.P4Runtime/Read',
            p4_dot_v1_dot_p4runtime__pb2.ReadRequest.SerializeToString,
            p4_dot_v1_dot_p4runtime__pb2.ReadResponse.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

    @staticmethod
    def SetForwardingPipelineConfig(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(request, target, '/p4.v1.P4Runtime/SetForwardingPipelineConfig',
            p4_dot_v1_dot_p4runtime__pb2.SetForwardingPipelineConfigRequest.SerializeToString,
            p4_dot_v1_dot_p4runtime__pb2.SetForwardingPipelineConfigResponse.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

    @staticmethod
    def GetForwardingPipelineConfig(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(request, target, '/p4.v1.P4Runtime/GetForwardingPipelineConfig',
            p4_dot_v1_dot_p4runtime__pb2.GetForwardingPipelineConfigRequest.SerializeToString,
            p4_dot_v1_dot_p4runtime__pb2.GetForwardingPipelineConfigResponse.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

    @staticmethod
    def StreamChannel(request_iterator,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.stream_stream(request_iterator, target, '/p4.v1.P4Runtime/StreamChannel',
            p4_dot_v1_dot_p4runtime__pb2.StreamMessageRequest.SerializeToString,
            p4_dot_v1_dot_p4runtime__pb2.StreamMessageResponse.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

    @staticmethod
    def Capabilities(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(request, target, '/p4.v1.P4Runtime/Capabilities',
            p4_dot_v1_dot_p4runtime__pb2.CapabilitiesRequest.SerializeToString,
            p4_dot_v1_dot_p4runtime__pb2.CapabilitiesResponse.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)


text:
package org.scijava.io.location;

import java.net.URI;

import org.scijava.io.handle.DataHandle;

/**
 * A location is a data descriptor, such as a file on disk, a remote
 * URL, or a database connection.
 *

 * Analogous to a uniform
 * resource identifier ({@link URI}), a location identifies where
 * the data resides, without necessarily specifying how to access that
 * data. The {@link DataHandle} interface defines a plugin that knows how to
 * read and/or write bytes for a particular kind of location.
 *

 *
 * @author Curtis Rueden
 * @author Gabriel Einsdorf
 */
public interface Location {

	/**
	 * Gets the location expressed as a {@link URI}, or null if the location
	 * cannot be expressed as such.
	 */
	default URI getURI() {
		return null;
	}

	/**
	 * Gets a (typically short) name expressing this location. This string is not
	 * intended to unambiguously identify the location, but rather act as a
	 * friendly, human-readable name. The precise behavior will depend on the
	 * implementation, but as an example, a file-based location could return the
	 * name of the associated file without its full path.
	 *
	 * @return The name, or an empty string if no name is available.
	 */
	default String getName() {
		return defaultName();
	}

	/**
	 * Gets the default name used when no explicit name is assigned.
	 *

	 * Note: this is mostly intended for debugging, since most kinds of
	 * {@code Location} will assign some non-default name. But in cases where that
	 * does not occur, this value can be useful to detect the situation.
	 *

	 *
	 * @return The default name string.
	 */
	default String defaultName() {
		return "Location.defaultName";
	}
}


text:
=========
scrapelib
=========

A Python library for scraping things.

Features include:

  * HTTP, HTTPS, FTP requests via an identical API
  * HTTP caching, compression and cookies
  * redirect following
  * request throttling
  * robots.txt compliance (optional)
  * robust error handling

scrapelib is a project of Sunlight Labs (c) 2010.
All code is released under a BSD-style license, see LICENSE for details.

Written by Michael Stephens <mstephens@sunlightfoundation.com> and James Turk
<jturk@sunlightfoundation.com>.

Source is available at http://github.com/sunlightlabs/scrapelib.

Requirements
============

python >= 2.6

httplib2 optional but highly recommended.

Installation
============

scrapelib is available on PyPI and thus can be downloaded installed via
``pip install scrapelib`` or ``easy_install scrapelib``.

To install from a source distribution run ``python setup.py install``.

Example Usage
=============

::

  import scrapelib
  s = scrapelib.Scraper(requests_per_minute=10, allow_cookies=True,
                        follow_robots=True)

  # Grab Google front page
  s.urlopen('http://google.com')

  # Will raise RobotExclusionError
  s.urlopen('http://google.com/search')

  # Will be throttled to 10 HTTP requests per minute
  while True:
      s.urlopen('http://example.com')


text:
<?php

namespace PAXB\Xml\Binding\Metadata;

interface ClassMetadataFactory {

    /**
     * @param string $className
     *
     * @return ClassMetadata
     */
    public function getClassMetadata($className);
}


text:
#ifndef MBED_COMMON_OBJECTS_H
#define MBED_COMMON_OBJECTS_H

#include "cmsis.h"
#include "PortNames.h"
#include "PeripheralNames.h"
#include "PinNames.h"

#ifdef __cplusplus
extern "C" {
#endif

struct pwmout_s {
    PWMName pwm;
    PinName pin;
    uint32_t prescaler;
    uint32_t period;
    uint32_t pulse;
    uint8_t channel;
    uint8_t inverted;
};

struct spi_s {
    SPI_HandleTypeDef handle;
    IRQn_Type spiIRQ;
    SPIName spi;
    PinName pin_miso;
    PinName pin_mosi;
    PinName pin_sclk;
    PinName pin_ssel;
#ifdef DEVICE_SPI_ASYNCH
    uint32_t event;
    uint8_t transfer_type;
#endif
};

struct serial_s {
    UARTName uart;
    int index; // Used by irq
    uint32_t baudrate;
    uint32_t databits;
    uint32_t stopbits;
    uint32_t parity;
    PinName pin_tx;
    PinName pin_rx;
#if DEVICE_SERIAL_ASYNCH
    uint32_t events;
#endif
#if DEVICE_SERIAL_FC
    uint32_t hw_flow_ctl;
    PinName pin_rts;
    PinName pin_cts;
#endif
};

struct i2c_s {
    /*  The 1st 2 members I2CName i2c
     *  and I2C_HandleTypeDef handle should
     *  be kept as the first members of this struct
     *  to ensure i2c_get_obj to work as expected
     */
    I2CName  i2c;
    I2C_HandleTypeDef handle;
    uint8_t index;
    int hz;
    PinName sda;
    PinName scl;
    IRQn_Type event_i2cIRQ;
    IRQn_Type error_i2cIRQ;
    uint32_t XferOperation;
    volatile uint8_t event;
    volatile int pending_start;
#if DEVICE_I2CSLAVE
    uint8_t slave;
    volatile uint8_t pending_slave_tx_master_rx;
    volatile uint8_t pending_slave_rx_maxter_tx;
#endif
#if DEVICE_I2C_ASYNCH
    uint32_t address;
    uint8_t stop;
    uint8_t available_events;
#endif
};

struct flash_s {
    /*  nothing to be stored for now */
    uint32_t dummy;
};

struct analogin_s {
    ADC_HandleTypeDef handle;
    PinName pin;
    uint8_t channel;
};

#include "gpio_object.h"

struct dac_s {
    DACName dac;
    PinName pin;
    uint32_t channel;
    DAC_HandleTypeDef handle;
};

#ifdef __cplusplus
}
#endif

#if DEVICE_CAN
struct can_s {
    CAN_HandleTypeDef CanHandle;
    int index;
    int hz;
};
#endif

/* STM32L4 HAL doesn't provide this API called in rtc_api.c */
#define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__)

#endif


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.U4096.html">

Redirecting to type.U4096.html...


text:
USER_DETEAIL_INFO_CLASS = class("USER_DETEAIL_INFO_CLASS", function()
    return display.newNode()
end)

function USER_DETEAIL_INFO_CLASS:ctor(data)
    self:setContentSize(cc.size(400, 300))
    self:init_ui()
    self:set_data(data)
end

function USER_DETEAIL_INFO_CLASS:init_ui()
    local size = self:getContentSize()
    local function touchEvent(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            self:removeFromParent()
        end
    end

    local bg = cc.Scale9Sprite:create("CyanSquare.png")
    bg:setAnchorPoint(cc.p(0, 0))
    bg:setContentSize(size)
    bg:addTo(self)

    local close_btn = ccui.Button:create()
    close_btn:setTouchEnabled(true)
    close_btn:loadTextures("close.png", "", "")
    close_btn:setContentSize(cc.size(close_btn:getVirtualRendererSize().width, close_btn:getVirtualRendererSize().height * 1.5))
    close_btn:setPosition(cc.p(size.width, size.height))
    close_btn:addTouchEventListener(touchEvent)
    self:addChild(close_btn)

    -- self.account = cc.Label:createWithSystemFont("账号:", "Arial", 20):move(100, 50):addTo(self)
    -- self.account:setAnchorPoint(cc.p(0.5, 0.5))

    -- self.account_detail = cc.Label:createWithSystemFont("", "Arial", 20):move(200, 50):addTo(self)
    -- self.account_detail:setAnchorPoint(cc.p(0, 0.5))

    self.all_detail = cc.Label:createWithSystemFont("", "Arial", 20):move(200, 50):addTo(self)
    self.all_detail:setContentSize(self:getContentSize())
    self.all_detail:setAnchorPoint(cc.p(0, 1))
    self.all_detail:setPosition(cc.p(0, self:getContentSize().height))
end

function USER_DETEAIL_INFO_CLASS:get_all_desc()
    local data = self.data
    local ddz_info = data.ddz_info
    trace("data is %o", data)
    return "名称:" .. (data.name or "") ..
           "\n胜场:" .. tostring(ddz_info.win_amount or 0) ..
           "\n负场:" .. tostring(ddz_info.lose_amount or 0) ..
           "\n豆豆:" .. tostring(ddz_info.pea_amount or 0)
end

function USER_DETEAIL_INFO_CLASS:set_data(data)
    self.data = data
    self.all_detail:setString(self:get_all_desc())
end


text:
package audit.jms.consumer;

import audit.domain.Audit;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.inject.Inject;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:/jms/topic/audit"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic")
})
public class AuditMessagingConsumerService implements MessageListener {

    @Inject
    private AuditListener auditListener;

    @Override
    public void onMessage(Message message) {
        try {
            Audit audit = message.getBody(Audit.class);
            auditListener.onMessage(audit);
        } catch (JMSException e) {
            throw new IllegalStateException(e.getLocalizedMessage(), e);
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".ui.Fragments.TableFragment">
    <android.support.v7.widget.Toolbar
        android:id="@+id/table_toolbar"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.Toolbar>
    <android.support.v7.widget.CardView
        android:layout_marginTop="6dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="match_parent"
        android:layout_height="92dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <android.support.v7.widget.CardView
                    app:cardElevation="0dp"
                    app:cardCornerRadius="30dp"
                    app:cardBackgroundColor="@color/colorPrimaryLight"
                    android:layout_margin="16dp"
                    android:layout_gravity="center_vertical"
                    android:layout_width="60dp"
                    android:layout_height="60dp" />
                <TextView
                    android:layout_marginLeft="34dp"
                    android:layout_centerVertical="true"
                    android:textColor="@android:color/white"
                    android:text="TXT"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </RelativeLayout>
            <TextView
                android:alpha="0.75"
                android:textColor="@android:color/black"
                android:lineSpacingExtra="3dp"
                android:layout_weight="1"
                android:layout_gravity="center"
                android:layout_margin="16dp"
                android:text="项目推进报表"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <ImageView
                android:id="@+id/table_image_download1"
                android:layout_gravity="center"
                android:layout_margin="16dp"
                android:src="@drawable/download"
                android:layout_weight="0"
                android:layout_width="23dp"
                android:layout_height="23dp" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:layout_marginTop="6dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="match_parent"
        android:layout_height="92dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <android.support.v7.widget.CardView
                    app:cardElevation="0dp"
                    app:cardCornerRadius="30dp"
                    app:cardBackgroundColor="@color/colorPrimaryLight"
                    android:layout_margin="16dp"
                    android:layout_gravity="center_vertical"
                    android:layout_width="60dp"
                    android:layout_height="60dp" />
                <TextView
                    android:layout_marginLeft="34dp"
                    android:layout_centerVertical="true"
                    android:textColor="@android:color/white"
                    android:text="PDF"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </RelativeLayout>
            <TextView
                android:alpha="0.75"
                android:textColor="@android:color/black"
                android:lineSpacingExtra="3dp"
                android:layout_weight="1"
                android:layout_gravity="center"
                android:layout_margin="16dp"
                android:text="请假审批表"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <ImageView
                android:id="@+id/table_image_download2"
                android:layout_gravity="center"
                android:layout_margin="16dp"
                android:src="@drawable/download"
                android:layout_weight="0"
                android:layout_width="23dp"
                android:layout_height="23dp" />
        </LinearLayout>
    </android.support.v7.widget.CardView>
    <android.support.v7.widget.CardView
        android:layout_marginTop="6dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="match_parent"
        android:layout_height="92dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <android.support.v7.widget.CardView
                    app:cardElevation="0dp"
                    app:cardCornerRadius="30dp"
                    app:cardBackgroundColor="@color/colorPrimaryLight"
                    android:layout_margin="16dp"
                    android:layout_gravity="center_vertical"
                    android:layout_width="60dp"
                    android:layout_height="60dp" />
                <TextView
                    android:layout_marginLeft="34dp"
                    android:layout_centerVertical="true"
                    android:textColor="@android:color/white"
                    android:text="DOC"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </RelativeLayout>
            <TextView
                android:alpha="0.75"
                android:textColor="@android:color/black"
                android:lineSpacingExtra="3dp"
                android:layout_weight="1"
                android:layout_gravity="center"
                android:layout_margin="16dp"
                android:text="项目推进报表"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <ImageView
                android:id="@+id/table_image_download3"
                android:layout_gravity="center"
                android:layout_margin="16dp"
                android:src="@drawable/download"
                android:layout_weight="0"
                android:layout_width="23dp"
                android:layout_height="23dp" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SRFS.Model;
using System.Security.Cryptography;
using SRFS.Model.Clusters;
using SRFS.IO;
using SRFS.Model.Data;

namespace SRFS.Tests.Model.Clusters {

    [TestClass]
    public class VerifyTimesClusterTests {

        [TestMethod]
        public void VerifyTimesClusterSaveLoadTest() {
            ConfigurationTest.Initialize();

            using (var io = ConfigurationTest.CreateMemoryIO()) {
                SimpleClusterIO cio = new SimpleClusterIO(io);

                Random r = new Random();
                VerifyTimesCluster csc = new VerifyTimesCluster(2);
                csc.Initialize();
                for (int i = 0; i < csc.Count; i++) csc[i] = new DateTime(r.Next());
                csc.NextClusterAddress = Constants.NoAddress;
                cio.Save(csc);

                int offset = 0;
                DataBlock b = new DataBlock(io.Bytes, 2 * Configuration.Geometry.BytesPerCluster, Configuration.Geometry.BytesPerCluster);

                byte[] marker = b.ToByteArray(offset, Constants.SrfsMarker.Length);
                Assert.IsTrue(marker.SequenceEqual(Constants.SrfsMarker));
                offset += marker.Length;

                byte[] version = b.ToByteArray(offset, Constants.CurrentVersion.Length);
                Assert.IsTrue(version.SequenceEqual(Constants.CurrentVersion));
                offset += version.Length;

                Guid guid = new Guid(b.ToByteArray(offset, Constants.GuidLength));
                Assert.AreEqual(guid, Configuration.FileSystemID);
                offset += Constants.GuidLength;

                byte[] signatureBytes = b.ToByteArray(offset, Signature.Length);
                offset += Signature.Length;

                byte[] thumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length);
                Assert.IsTrue(thumbprintBytes.SequenceEqual(Configuration.CryptoSettings.SigningKeyThumbprint.Bytes));
                offset += KeyThumbprint.Length;

                byte[] hashBytes = b.ToByteArray(offset, 32);
                offset += 32;

                ClusterType clusterType = (ClusterType)b.ToByte(offset);
                Assert.AreEqual(clusterType, ClusterType.VerifyTimeTable);
                offset += sizeof(ClusterType);

                int nextClusterAddress = b.ToInt32(offset);
                Assert.AreEqual(nextClusterAddress, Constants.NoAddress);
                offset += sizeof(int);

                long[] cs = new long[csc.Count];
                for (int i = 0; i < csc.Count; i++) cs[i] = b.ToInt64(offset + i * sizeof(long));
                Assert.IsTrue(cs.SequenceEqual(from d in csc select d.Ticks));

                VerifyTimesCluster csc2 = new VerifyTimesCluster(2);
                cio.Load(csc2);
                Assert.AreEqual(csc.VolumeID, csc2.VolumeID);
                Assert.AreEqual(csc.Type, csc2.Type);
                Assert.AreEqual(csc.NextClusterAddress, csc2.NextClusterAddress);

                Assert.IsTrue(csc.SequenceEqual(csc2));
            }
        }
    }
}


text:
package org.motechproject.server.messagecampaign.scheduler;

import org.joda.time.LocalDate;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.motechproject.commons.date.model.Time;
import org.motechproject.commons.date.util.DateUtil;
import org.motechproject.scheduler.MotechSchedulerService;
import org.motechproject.scheduler.domain.RunOnceSchedulableJob;
import org.motechproject.server.messagecampaign.builder.CampaignBuilder;
import org.motechproject.server.messagecampaign.builder.EnrollRequestBuilder;
import org.motechproject.server.messagecampaign.contract.CampaignRequest;
import org.motechproject.server.messagecampaign.dao.AllMessageCampaigns;
import org.motechproject.server.messagecampaign.domain.campaign.Campaign;
import org.motechproject.server.messagecampaign.domain.campaign.CampaignEnrollment;
import org.motechproject.server.messagecampaign.domain.campaign.OffsetCampaign;
import org.motechproject.server.messagecampaign.domain.message.OffsetCampaignMessage;

import java.util.Date;
import java.util.List;

import static junit.framework.Assert.assertEquals;
import static org.joda.time.Period.days;
import static org.joda.time.Period.minutes;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.motechproject.commons.date.util.DateUtil.newDateTime;
import static org.motechproject.commons.date.util.DateUtil.today;
import static org.motechproject.testing.utils.TimeFaker.fakeNow;
import static org.motechproject.testing.utils.TimeFaker.stopFakingTime;

public class OffsetCampaignSchedulerServiceTest {

    OffsetCampaignSchedulerService offsetCampaignSchedulerService;

    @Mock
    private MotechSchedulerService schedulerService;
    @Mock
    private AllMessageCampaigns allMessageCampaigns;

    @Before
    public void setup() {
        initMocks(this);
        offsetCampaignSchedulerService = new OffsetCampaignSchedulerService(schedulerService, allMessageCampaigns);
    }

    @Test
    public void shouldScheduleJobForOffsetCampaignMessage() {
        try {
            fakeNow(newDateTime(2010, 10, 1));

            Campaign campaign = new OffsetCampaign();
            campaign.setName("camp");
            when(allMessageCampaigns.getCampaign("camp")).thenReturn(campaign);

            offsetCampaignSchedulerService.scheduleMessageJob(
                new CampaignEnrollment("entity1", "camp").setReferenceDate(new LocalDate(2010, 10, 3)).setReferenceTime(3, 10),
                new OffsetCampaignMessage(days(5)).messageKey("foo").setStartTime(5, 30));

            ArgumentCaptor<RunOnceSchedulableJob> jobCaptor = ArgumentCaptor.forClass(RunOnceSchedulableJob.class);
            verify(schedulerService).scheduleRunOnceJob(jobCaptor.capture());
            RunOnceSchedulableJob job = jobCaptor.getValue();

            assertEquals(newDateTime(2010, 10, 8, 5, 30, 0).toDate(), job.getStartDate());
        } finally {
            stopFakingTime();
        }
    }

    @Test
    public void referenceTimeShouldBeUsedWhenOffsetIsLessThanADay() {
        try {
            fakeNow(newDateTime(2010, 10, 1));

            Campaign campaign = new OffsetCampaign();
            campaign.setName("camp");
            when(allMessageCampaigns.getCampaign("camp")).thenReturn(campaign);

            offsetCampaignSchedulerService.scheduleMessageJob(
                new CampaignEnrollment("entity1", "camp").setReferenceDate(new LocalDate(2010, 10, 3)).setReferenceTime(2, 0).setDeliverTime(8, 20),
                new OffsetCampaignMessage(minutes(5)).messageKey("foo").setStartTime(5, 30));

            ArgumentCaptor<RunOnceSchedulableJob> jobCaptor = ArgumentCaptor.forClass(RunOnceSchedulableJob.class);
            verify(schedulerService).scheduleRunOnceJob(jobCaptor.capture());
            RunOnceSchedulableJob job = jobCaptor.getValue();

            assertEquals(newDateTime(2010, 10, 3, 2, 5, 0).toDate(), job.getStartDate());
        } finally {
            stopFakingTime();
        }
    }

    @Test
    public void userPreferredDeliverTimeShouldOverrideMessageDeliverTime() {
        try {
            fakeNow(newDateTime(2010, 10, 1));

            Campaign campaign = new OffsetCampaign();
            campaign.setName("camp");
            when(allMessageCampaigns.getCampaign("camp")).thenReturn(campaign);

            offsetCampaignSchedulerService.scheduleMessageJob(
                new CampaignEnrollment("entity1", "camp").setReferenceDate(new LocalDate(2010, 10, 3)).setDeliverTime(8, 20),
                new OffsetCampaignMessage(days(3)).messageKey("foo").setStartTime(5, 30));

            ArgumentCaptor<RunOnceSchedulableJob> jobCaptor = ArgumentCaptor.forClass(RunOnceSchedulableJob.class);
            verify(schedulerService).scheduleRunOnceJob(jobCaptor.capture());
            RunOnceSchedulableJob job = jobCaptor.getValue();

            assertEquals(newDateTime(2010, 10, 6, 8, 20, 0).toDate(), job.getStartDate());
        } finally {
            stopFakingTime();
        }
    }

    @Test
    public void shouldScheduleJobsAfterGivenTimeOffsetIntervalFromReferenceDate_WhenCampaignStartOffsetIsZero() {
        // TODO: remove time faking after time gap issues in Offset Scheduler are resolved
        try {
            fakeNow(newDateTime(2010, 10, 1));

            CampaignRequest request = new EnrollRequestBuilder().withDefaults().withReferenceDate(today()).build();
            OffsetCampaign campaign = new CampaignBuilder().defaultOffsetCampaign();

            OffsetCampaignSchedulerService offsetCampaignScheduler = new OffsetCampaignSchedulerService(schedulerService, allMessageCampaigns);

            when(allMessageCampaigns.getCampaign("testCampaign")).thenReturn(campaign);

            CampaignEnrollment enrollment = new CampaignEnrollment("12345", "testCampaign").setReferenceDate(today()).setDeliverTime(new Time(9, 30));
            offsetCampaignScheduler.start(enrollment);
            ArgumentCaptor<RunOnceSchedulableJob> capture = ArgumentCaptor.forClass(RunOnceSchedulableJob.class);
            verify(schedulerService, times(2)).scheduleRunOnceJob(capture.capture());

            List<RunOnceSchedulableJob> allJobs = capture.getAllValues();

            Date startDate1 = DateUtil.newDateTime(DateUtil.today().plusDays(7), request.deliverTime().getHour(), request.deliverTime().getMinute(), 0).toDate();
            Assert.assertEquals(startDate1.toString(), allJobs.get(0).getStartDate().toString());
            Assert.assertEquals("org.motechproject.server.messagecampaign.fired-campaign-message", allJobs.get(0).getMotechEvent().getSubject());
            assertMotechEvent(allJobs.get(0), "MessageJob.testCampaign.12345.child-info-week-1", "child-info-week-1");

            Date startDate2 = DateUtil.newDateTime(DateUtil.today().plusDays(14), request.deliverTime().getHour(), request.deliverTime().getMinute(), 0).toDate();
            Assert.assertEquals(startDate2.toString(), allJobs.get(1).getStartDate().toString());
            Assert.assertEquals("org.motechproject.server.messagecampaign.fired-campaign-message", allJobs.get(1).getMotechEvent().getSubject());
            assertMotechEvent(allJobs.get(1), "MessageJob.testCampaign.12345.child-info-week-1a", "child-info-week-1a");
        } finally {
            stopFakingTime();
        }
    }

    private void assertMotechEvent(RunOnceSchedulableJob runOnceSchedulableJob, String expectedJobId, String messageKey) {
        Assert.assertEquals(expectedJobId, runOnceSchedulableJob.getMotechEvent().getParameters().get("JobID"));
        Assert.assertEquals("testCampaign", runOnceSchedulableJob.getMotechEvent().getParameters().get("CampaignName"));
        Assert.assertEquals("12345", runOnceSchedulableJob.getMotechEvent().getParameters().get("ExternalID"));
        Assert.assertEquals(messageKey, runOnceSchedulableJob.getMotechEvent().getParameters().get("MessageKey"));
    }
}


text:
using System;
using System.Diagnostics;
using TrollRAT.Payloads;

namespace TrollRATPayloads.Payloads
{
    public class PayloadOpen : ExecutablePayload
    {
        protected PayloadSettingString file = new PayloadSettingString("", "File Name or Website");
        protected PayloadSettingString args = new PayloadSettingString("", "Arguments for Programs");

        public PayloadOpen()
        {
            name = "Open Something";
            Settings.Add(file);
            Settings.Add(args);
        }

        protected override void execute()
        {
            try
            {
                Process.Start(file.Value, args.Value);
            }
            catch (Exception) { }
        }
    }
}


text:
package com.github.ppodgorsek.juncacher.manager.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.easymock.EasyMock;
import org.easymock.EasyMockSupport;
import org.easymock.Mock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.github.ppodgorsek.juncacher.collector.InvalidationCollector;
import com.github.ppodgorsek.juncacher.model.InvalidationEntry;
import com.github.ppodgorsek.juncacher.model.impl.SimpleInvalidationEntryType;
import com.github.ppodgorsek.juncacher.model.impl.TypedInvalidationEntry;
import com.github.ppodgorsek.juncacher.processor.InvalidationProcessor;

/**
 * Tests for the {@link ProcessorInvalidationManager} class.
 *
 * @author Paul Podgorsek
 */
public class ProcessorInvalidationManagerTest {

	private ProcessorInvalidationManager processorInvalidationManager;

	@Mock
	private InvalidationCollector collector1;

	@Mock
	private InvalidationCollector collector2;

	@Mock
	private InvalidationProcessor processor1;

	@Mock
	private InvalidationProcessor processor2;

	private InvalidationEntry entry1;
	private InvalidationEntry entry2;
	private InvalidationEntry entry3;
	private Collection<InvalidationEntry> entries;

	@Before
	public void setUp() {

		EasyMockSupport.injectMocks(this);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectors = new LinkedHashMap<>();
		processorsWithCollectors.put(processor1, collector1);
		processorsWithCollectors.put(processor2, collector2);

		processorInvalidationManager = new ProcessorInvalidationManager(processorsWithCollectors);

		entry1 = new TypedInvalidationEntry(new SimpleInvalidationEntryType("type1"));
		entry2 = new TypedInvalidationEntry(new SimpleInvalidationEntryType("type2"));
		entry3 = new TypedInvalidationEntry(new SimpleInvalidationEntryType("type3"));

		entries = new ArrayList<>();
		entries.add(entry1);
		entries.add(entry2);
		entries.add(entry3);
	}

	@After
	public void tearDown() {
		EasyMock.verify(collector1, collector2, processor1, processor2);
	}

	@Test
	public void constructWithCorrectMap() {

		EasyMock.replay(collector1, collector2, processor1, processor2);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectors = new LinkedHashMap<>();
		processorsWithCollectors.put(processor1, collector1);
		processorsWithCollectors.put(processor2, collector2);

		processorInvalidationManager = new ProcessorInvalidationManager(processorsWithCollectors);
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructWithEmptyMap() {

		EasyMock.replay(collector1, collector2, processor1, processor2);

		new ProcessorInvalidationManager(
				new HashMap<InvalidationProcessor, InvalidationCollector>());
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructWithMapHavingNullKey() {

		EasyMock.replay(collector1, collector2, processor1, processor2);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectors = new LinkedHashMap<>();
		processorsWithCollectors.put(null, collector1);

		processorInvalidationManager = new ProcessorInvalidationManager(processorsWithCollectors);
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructWithMapHavingNullValue() {

		EasyMock.replay(collector1, collector2, processor1, processor2);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectors = new LinkedHashMap<>();
		processorsWithCollectors.put(processor1, null);

		processorInvalidationManager = new ProcessorInvalidationManager(processorsWithCollectors);
	}

	@Test
	public void addInvalidationEntries() {

		collector1.addInvalidationEntries(entries);
		EasyMock.expectLastCall();

		EasyMock.replay(collector1, collector2, processor1, processor2);

		processorInvalidationManager.addInvalidationEntries(entries);
	}

	@Test
	public void addInvalidationEntry() {

		collector1.addInvalidationEntry(entry1);
		EasyMock.expectLastCall();

		EasyMock.replay(collector1, collector2, processor1, processor2);

		processorInvalidationManager.addInvalidationEntry(entry1);
	}

	@Test
	public void getProcessorsWithCollectors() {

		EasyMock.replay(collector1, collector2, processor1, processor2);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectors = new LinkedHashMap<>();
		processorsWithCollectors.put(processor1, collector1);
		processorsWithCollectors.put(processor2, collector2);

		processorInvalidationManager = new ProcessorInvalidationManager(processorsWithCollectors);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectorsFetched = processorInvalidationManager
				.getProcessorsWithCollectors();

		assertNotNull("The processor with collector map shouldn't be null",
				processorsWithCollectorsFetched);
		assertNotSame(
				"The processor with collector map should be different from the one given to the constructor",
				processorsWithCollectors, processorsWithCollectorsFetched);
		assertEquals(
				"The contents of the processor with collector map should be equal to the one given to the constructor",
				processorsWithCollectors, processorsWithCollectorsFetched);
	}

	@Test(expected = UnsupportedOperationException.class)
	public void getProcessorsWithCollectorsAndModifyResult() {

		EasyMock.replay(collector1, collector2, processor1, processor2);

		final Map<InvalidationProcessor, InvalidationCollector> processorsWithCollectorsFetched = processorInvalidationManager
				.getProcessorsWithCollectors();

		processorsWithCollectorsFetched.put(processor1, collector2);
	}

	@SuppressWarnings("unchecked")
	@Test
	public void processEntries() {

		final List<InvalidationEntry> entriesFromCollector1 = new ArrayList<>();
		entriesFromCollector1.add(entry2);

		final List<InvalidationEntry> entriesFromCollector2 = new ArrayList<>();
		entriesFromCollector2.add(entry2);

		final List<InvalidationEntry> entriesEvicted = new ArrayList<>();
		entriesEvicted.add(entry2);

		collector1.addInvalidationEntries(EasyMock.anyObject(List.class));
		EasyMock.expectLastCall();

		EasyMock.expect(collector1.getEntries()).andReturn(entriesFromCollector1);
		EasyMock.expect(processor1.invalidateEntries(entriesFromCollector1))
				.andReturn(entriesFromCollector1);

		collector1.consume(entriesFromCollector1);
		EasyMock.expectLastCall();

		collector2.addInvalidationEntries(entriesFromCollector1);
		EasyMock.expectLastCall();

		EasyMock.expect(collector2.getEntries()).andReturn(entriesFromCollector2);
		EasyMock.expect(processor2.invalidateEntries(entriesFromCollector2))
				.andReturn(entriesEvicted);

		collector2.consume(entriesEvicted);
		EasyMock.expectLastCall();

		EasyMock.replay(collector1, collector2, processor1, processor2);

		processorInvalidationManager.processEntries();
	}

	@SuppressWarnings("unchecked")
	@Test
	public void processEntriesImmediately() {

		final Collection<InvalidationEntry> entriesForProcessor1 = new ArrayList<>();
		entriesForProcessor1.add(entry2);
		entriesForProcessor1.add(entry1);
		entriesForProcessor1.add(entry3);

		final List<InvalidationEntry> entriesForProcessor2 = new ArrayList<>();
		entriesForProcessor2.add(entry2);
		entriesForProcessor2.add(entry1);

		EasyMock.expect(processor1.invalidateEntries(entriesForProcessor1))
				.andReturn(entriesForProcessor2);

		collector1.addInvalidationEntries(EasyMock.anyObject(List.class));
		EasyMock.expectLastCall();

		EasyMock.expect(processor2.invalidateEntries(entriesForProcessor2))
				.andReturn(entriesForProcessor2);

		EasyMock.replay(collector1, collector2, processor1, processor2);

		processorInvalidationManager.processEntries(entriesForProcessor1);
	}

	@Test
	public void processEntryImmediately() {

		final Collection<InvalidationEntry> entriesForProcessor1 = new ArrayList<>();
		entriesForProcessor1.add(entry2);

		final List<InvalidationEntry> entriesForProcessor2 = new ArrayList<>();
		entriesForProcessor2.add(entry2);

		EasyMock.expect(processor1.invalidateEntries(entriesForProcessor1))
				.andReturn(entriesForProcessor2);

		EasyMock.expect(processor2.invalidateEntries(entriesForProcessor2))
				.andReturn(entriesForProcessor2);

		EasyMock.replay(collector1, collector2, processor1, processor2);

		processorInvalidationManager.processEntry(entry2);
	}

}


text:
from kibitzr.transformer.jinja_transform import JinjaTransform

from ...helpers import stash_mock

def jinja_transform(code, content, conf=None):
    return JinjaTransform(code, conf or {})(content)

def test_content_is_passed():
    ok, content = jinja_transform('hello {{ content }}!', 'world')
    assert ok is True
    assert content == "hello world!"

def test_lines_are_passed():
    ok, content = jinja_transform('{{ lines[1] }}', 'a\nb')
    assert ok is True
    assert content == "b"

def test_json_is_passed():
    ok, content = jinja_transform('{{ json["a"][1] }}', '{"a": [1, 2, 3]}')
    assert ok is True
    assert content == "2"

def test_css_selector_is_passed():
    ok, content = jinja_transform(
        '{{ css("div p") | text }}',
        '
A
P

',
    )
    assert ok is True
    assert content == "P"

def test_xpath_selector_is_passed():
    ok, content = jinja_transform(
        '{{ xpath("//div/p") | text }}',
        '
A
P

',
    )
    assert ok is True
    assert content == "P"

def test_stash_is_passed():
    with stash_mock() as stash:
        stash.write({'key': 'good'})
        ok, content = jinja_transform('{{ stash.key }} news', '')
        assert ok is True
        assert content == 'good news'


text:
<?php

/**
 * CloudFlare API Library
 * @link http://github.com/okwinza/cloudflare-api
 * @author Oleg Krasavin <okwinza@gmail.com>
 */
namespace okw\CF\Exception;

class CFException extends \Exception {

    const CURL_NOT_FOUND = 1;
    const CURL_ERROR = 3;

}


text:
package com.navercorp.pinpoint.plugin.spring.beans;

import java.security.ProtectionDomain;

import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod;
import com.navercorp.pinpoint.bootstrap.instrument.Instrumentor;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplate;
import com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformTemplateAware;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ObjectFactory;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.ProfilerPluginSetupContext;

import static com.navercorp.pinpoint.common.util.VarArgs.va;

/**
 * @author Jongho Moon
 * @author jaehong.kim
 */
public class SpringBeansPlugin implements ProfilerPlugin, TransformTemplateAware {
    public static final String SPRING_BEANS_MARK_ERROR = "profiler.spring.beans.mark.error";
    public static final String ENABLE = "profiler.spring.beans";

    private final PLogger logger = PLoggerFactory.getLogger(getClass());
    private TransformTemplate transformTemplate;

    @Override
    public void setup(ProfilerPluginSetupContext context) {
        final boolean enable = context.getConfig().readBoolean(ENABLE, true);
        if (!enable) {
            return;
        }

        final SpringBeansConfig config = new SpringBeansConfig(context.getConfig());
        if (logger.isInfoEnabled()) {
            logger.info("SpringBeans targets=" + config.getTargets());
        }

        if (config.hasTarget(SpringBeansTargetScope.COMPONENT_SCAN)) {
            // since spring-context 2.5
            addClassPathDefinitionScannerTransformer(context);
        }

        if (config.hasTarget(SpringBeansTargetScope.POST_PROCESSOR)) {
            addAbstractAutowireCapableBeanFactoryTransformer(context);
        }
    }

    private void addAbstractAutowireCapableBeanFactoryTransformer(final ProfilerPluginSetupContext context) {
        final ProfilerConfig config = context.getConfig();
        final boolean errorMark = config.readBoolean(SPRING_BEANS_MARK_ERROR, false);

        transformTemplate.transform("org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory", new TransformCallback() {

            @Override
            public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
                InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);

                final BeanMethodTransformer beanTransformer = new BeanMethodTransformer(errorMark);
                final ObjectFactory beanFilterFactory = ObjectFactory.byStaticFactory("com.navercorp.pinpoint.plugin.spring.beans.interceptor.TargetBeanFilter", "of", config);

                final InstrumentMethod createBeanInstance = target.getDeclaredMethod("createBeanInstance", "java.lang.String", "org.springframework.beans.factory.support.RootBeanDefinition", "java.lang.Object[]");
                createBeanInstance.addInterceptor("com.navercorp.pinpoint.plugin.spring.beans.interceptor.CreateBeanInstanceInterceptor", va(beanTransformer, beanFilterFactory));

                final InstrumentMethod postProcessor = target.getDeclaredMethod("applyBeanPostProcessorsBeforeInstantiation", "java.lang.Class", "java.lang.String");
                postProcessor.addInterceptor("com.navercorp.pinpoint.plugin.spring.beans.interceptor.PostProcessorInterceptor", va(beanTransformer, beanFilterFactory));

                return target.toBytecode();
            }
        });
    }

    private void addClassPathDefinitionScannerTransformer(final ProfilerPluginSetupContext context) {
        final ProfilerConfig config = context.getConfig();
        final boolean errorMark = config.readBoolean(SPRING_BEANS_MARK_ERROR, false);

        transformTemplate.transform("org.springframework.context.annotation.ClassPathBeanDefinitionScanner", new TransformCallback() {

            @Override
            public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
                InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);

                final BeanMethodTransformer beanTransformer = new BeanMethodTransformer(errorMark);
                final ObjectFactory beanFilterFactory = ObjectFactory.byStaticFactory("com.navercorp.pinpoint.plugin.spring.beans.interceptor.TargetBeanFilter", "of", context.getConfig());

                final InstrumentMethod method = target.getDeclaredMethod("doScan", "java.lang.String[]");
                method.addInterceptor("com.navercorp.pinpoint.plugin.spring.beans.interceptor.ClassPathDefinitionScannerDoScanInterceptor", va(loader, beanTransformer, beanFilterFactory));

                return target.toBytecode();
            }
        });
    }

    @Override
    public void setTransformTemplate(TransformTemplate transformTemplate) {
        this.transformTemplate = transformTemplate;
    }
}


text:
package autoApi.java.xserver.autoapi.constant;

/**
 * 常量包
 */


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    android:paddingRight="16dp"
    android:paddingLeft="16dp"
    android:background="@color/colorPrimaryDark"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profileImage"
        android:layout_width="68dp"
        android:layout_height="68dp"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:id="@+id/fullName"
        android:textColor="@color/White"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:textSize="18sp"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

    <TextView
        android:id="@+id/email"
        android:textColor="@color/White"
        android:textSize="18sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />
</LinearLayout>