text:
set* operations directly put frame values
```swift

blueView.lx.set(x: 10, y: 10)
    .set(width: 100, height: 100)

greenView.lx.set(x: 120, y: 20, width: 50, height: 190)

redView.lx.set(x: 5)
    .set(y: 120)
    .set(width: 45)
    .set(height: 100)
```

#### Center
hcenter (horizontally), vcenter (vertically) and center (both) operations allows to center view in superview. Insets can be used to adjust center point (see green view, 100 pt from bottom). Size of view usually should be set with previous operations
```swift

blueView.lx.set(y: 5)
    .set(width: 100, height: 100)
    .hcenter()

greenView.lx.set(x: 5)
    .set(width: 50, height: 120)
    .vcenter(topInset: 0, bottomInset: 100)

redView.lx.set(width: 45, height: 100)
    .center()
```

#### Fill
hfill (horizontally), vfill (vertically) and fill (both) operations make view to fill its superview. Insets can be used to control how much space to be left unfilled from the superview edges
```swift

redView.lx.fill(inset: 5)

blueView.lx.set(y: 20)
    .set(height: 50)
    .hfill(inset: 10)

greenView.lx.set(x: 25)
    .set(width: 50)
    .vfill(topInset: 100, bottomInset: 15)
```

#### Align
align* operations allow to put view relatively to edges of superview. Inset value can be used to set distance to edge. Size of view usually should be set with previous operations.
```swift

blueView.lx.set(width: 100, height: 100)
    .alignLeft(5)
    .alignTop(5)

greenView.lx.set(width: 50, height: 120)
    .alignLeft(10)
    .alignBottom(15)

redView.lx.set(width: 45, height: 100)
    .alignRight(25)
    .alignTop(25)
```

### SizeToFit
#### .value
sizeToFit operation fits view in defined box using -sizeThatFits: method. Box (width and height) can be defined using different options. .value option sets exact value for box. Result size will be equal or less than it.
```swift

icon.lx.sizeToFit(width: .value(100), height: .value(100))
    .alignTop(10)
    .hcenter()

label.lx.sizeToFit(width: .value(100), height: .value(100))
    .center()

title.lx.sizeToFit(width: .value(100), height: .value(100))
    .alignBottom(10)
    .hcenter()
```

#### .max
.max option sets infinite value for fitting box. Result size will be most comfortable for view to display content. WARNING: multiline labels are comfortable with single line, don't use .max for width
```swift

icon.lx.sizeToFitMax()  //same as view.lx.sizeToFit(width: .Max, height: .Max)
    .alignTop(10)
    .hcenter()

label.lx.sizeToFit(width: .max, height: .max)
    .center()

title.lx.sizeToFit(width: .max, height: .max)
    .alignBottom(10)
    .hcenter()
```

#### .current
.current option sets value for box with current frame's width or height.
```swift

icon.lx.set(size: CGSize(width: 200, height: 200))
    .sizeToFit(width: .current, height: .current)
    .alignTop(10)
    .hcenter()

label.lx.hfill(leftInset: 20, rightInset: 20)
    .sizeToFit() //same as view.lx.sizeToFit(width: .Current, height: .Current)
    .center()

title.lx.hfill(leftInset: 20, rightInset: 20)
    .sizeToFit(width: .current, height: .current)
    .alignBottom(10)
    .hcenter()
```

#### .keepCurrent
.keepCurrent options sets value for box with current frame's width or height, but result size will be still equal to those original frame values. This is usefull to layout multiline labels. First you need to set somehow label width, and then call something like label.lx.sizeToFit(width: .keepCurrent, height: .max).
```swift

icon.lx.set(size: CGSize(width: 200, height: 200))
    .sizeToFit(width: .keepCurrent, height: .max)
    .alignTop(10)
    .hcenter()

label.lx.hfill(leftInset: 20, rightInset: 20)
    .sizeToFit(width: .keepCurrent, height: .max)
    .center()

title.lx.hfill(leftInset: 20, rightInset: 20)
    .sizeToFit(width: .keepCurrent, height: .max)
    .alignBottom(10)
    .hcenter()
```

#### min/max constraints
sizeToFit operation also can have min, max or both constraints to limit resulted width/height.
```swift

label.lx.sizeToFitMax(widthConstraint: .max(100), heightConstraint: .min(300))
    .center()
```

### Follow
#### Corners
Follow operation makes one view's anchor to be the same with others view anchor (+/- inset). Anchors can be horizontal or vertical, and can be followed only with the anchors of same type. Anchor can follow anchors of other views at the same level of hierarchy, or parent anchors
```swift

blueView.lx.set(x: 10, y: 10)
    .set(width: 100, height: 100)

greenView.lx.set(width: 50, height: 190)
greenView.lx.leftAnchor.follow(blueView.lx.rightAnchor)
greenView.lx.topAnchor.follow(blueView.lx.bottomAnchor)

redView.lx.set(width: 30, height: 30)
redView.lx.leftAnchor.follow(blueView.lx.leftAnchor)
redView.lx.bottomAnchor.follow(greenView.lx.bottomAnchor)

heartView.lx.topAnchor.follow(greenView.lx.bottomAnchor)
heartView.lx.rightAnchor.follow(greenView.lx.rightAnchor)
```

#### Center
There are not only edge anchors, but also center anchors
```swift

blueView.lx.set(x: 10, y: 10)
    .set(width: 200)
    .vfill(inset: 20)

greenView.lx.set(width: 50, height: 190)
greenView.lx.leftAnchor.follow(blueView.lx.rightAnchor)
greenView.lx.vcenterAnchor.follow(blueView.lx.vcenterAnchor)

redView.lx.set(width: 30, height: 30)
redView.lx.hcenterAnchor.follow(greenView.lx.hcenterAnchor)
redView.lx.vcenterAnchor.follow(greenView.lx.vcenterAnchor)
```

#### Size
There are also size anchors
```swift

blueView.lx.set(x: 10)
    .set(width: 50)
    .vfill(inset: 100)

greenView.lx.heightAnchor.follow(blueView.lx.widthAnchor)
greenView.lx.widthAnchor.follow(blueView.lx.heightAnchor)
greenView.lx.leftAnchor.follow(blueView.lx.rightAnchor)
greenView.lx.topAnchor.follow(blueView.lx.bottomAnchor)
```

#### Baseline
firstBaselineAnchor/lastBaselineAnchor anchors are special. Only Baselinable views have it. For the moment only UILabel is conforming this protocol
```swift

label.lx.hfill(inset: 20)
    .sizeToFit(width: .keepCurrent, height: .max)
    .center()

blueView.lx.set(height: 30)
    .hfill(inset: 20)

greenView.lx.set(height: 30)
    .hfill(inset: 20)

blueView.lx.bottomAnchor.follow(label.lx.firstBaselineAnchor)
greenView.lx.topAnchor.follow(label.lx.lastBaselineAnchor)
```

### Put
#### Fix
hput and vput operations successively layout views in superview in horizontal or vertical direction using intentions. Fix intention means that view size will take exact value, either directly defined or current one
```swift

self.lx.hput(
    Fix(50),
    Fix(blueView, 120),
    Fix(greenView, 40),
    Fix(10),
    Fix(redView, 60)
)
self.lx.vput(
    Fix(50),
    Fix(blueView, 120),
    Fix(greenView, 40),
    Fix(10),
    Fix(redView, 60)
)
```

#### Flex
hput and vput operations successively layout views in superview in horizontal or vertical direction using intentions. Flex intention means that view size will take value based weight of flex value. Flex operates only with free space left after Fix intentions
```swift

self.lx.hput(
    Flex(blueView, 0.5),
    Flex(greenView, 1.0),
    Flex(redView, 0.5)
)
self.lx.vput(
    Flex(),
    Flex(blueView),
    Flex(greenView),
    Flex(redView),
    Flex()
)
```

#### Fix+Flex
Biggest power comes when we combine Fix and Flex intentions
```swift

self.lx.hput(
    Fix(20),
    Fix(blueView, 100),
    Fix(20),
    Flex(greenView),
    Fix(20),
    Fix(redView, 100),
    Fix(20)
)
blueView.lx.vfill(inset: 40)
greenView.lx.vfill(inset: 40)
redView.lx.vfill(inset: 40)
```

#### Fix+Flex center many views
It is really to easy to center bunch of views all together
```swift

self.lx.hput(
    Flex(),
    Fix(blueView, 70),
    Fix(10),
    Fix(greenView, 40),
    Fix(20),
    Fix(redView, 20),
    Flex()
)
blueView.lx.vfill(inset: 40)
greenView.lx.vfill(inset: 40)
redView.lx.vfill(inset: 40)
```

#### Multi
Single intention can be defined for several views, all calculations are doing for first one, and others use this result as is
```swift

self.lx.hput(
    Flex(),
    Fix(blueView, 70),
    Fix(10),
    Fix(greenView, 40),
    Fix(20),
    Fix(redView, 20),
    Flex()
)
self.lx.vput(
    Fix(40),
    Flex([blueView, greenView, redView]),
    Fix(40)
)
```

#### Fix+Flex grid
Elegant way to layout views in grid using just one hput and one vput
```swift

func putCols() {
    var r = [PutIntention]()
    for i in 0..<8 {

        var row = [Layoutable]()
        for j in 0..<8 {
            row.append(views[i*8 + j])
        }
        r.append(Flex(row))
    }
    self.lx.hput(r)
}

func putRows() {
    var r = [PutIntention]()

    for i in 0..<8 {

        var col = [Layoutable]()
        for j in 0..<8 {
            col.append(views[i + j*8])
        }
        r.append(Flex(col))
    }
    self.lx.vput(r)
}

putCols()
putRows()
```

#### Put labels
hfillvfit is used to fill width and size to fit height for both labels. vput is used to center group of labels
```swift

titleLabel.lx.hfillvfit(inset: 20)
detailsLabel.lx.hfillvfit(inset: 20)
self.lx.vput(
    Flex(),
    Fix(titleLabel),
    Fix(20),
    Fix(detailsLabel),
    Flex()
)
```

#### Digimax
AL Battle
```swift

let topSize = CGSize(width: 60, height: 60)
let topPadding: CGFloat = 10

let topLeftRightPadding: CGFloat = 20

topView1.lx.set(size: topSize)
    .alignTop(topPadding)
topView2.lx.set(size: topSize)
    .alignTop(topPadding)
topView3.lx.set(size: topSize)
    .alignTop(topPadding)

lx.hput(
    Fix(topLeftRightPadding),
    Fix(topView1),
    Flex(),
    Fix(topView2),
    Flex(),
    Fix(topView3),
    Fix(topLeftRightPadding)
)

let cardSize = bounds.width < bounds.height ? CGSize(width: 80, height: 120) : CGSize(width: 60, height: 90)
let cardLeftRightPadding: CGFloat = 25

cardView1.lx.set(size: cardSize)
cardView2.lx.set(size: cardSize)
cardView3.lx.set(size: cardSize)
cardView4.lx.set(size: cardSize)

if bounds.width < bounds.height {
    cardView1.lx.vcenter()
    cardView2.lx.vcenter()

    lx.hput(
        Fix(cardLeftRightPadding),
        Fix(cardView1),
        Flex(),
        Fix(cardView2),
        Fix(cardLeftRightPadding)
    )

    cardView3.lx.hcenter()
    cardView4.lx.hcenter()

    lx.vput(
        Flex(),
        Fix(cardView3),
        Fix(60),
        Fix(cardView4),
        Flex()
    )
} else {
    cardView1.lx.vcenter()
    cardView2.lx.vcenter()
    cardView3.lx.vcenter()
    cardView4.lx.vcenter()

    lx.hput(
        Fix(cardLeftRightPadding),
        Fix(cardView1),
        Flex(),
        Fix(cardView3),
        Flex(),
        Fix(cardView4),
        Flex(),
        Fix(cardView2),
        Fix(cardLeftRightPadding)
    )
}

bottomView.lx.set(height: 40)
    .hfill(inset: 100)
    .alignBottom(15)
```

#### Wrap
Derivative from put operation. Accepts only Fix. Modifies parent frame to wrap childs. Method to perform selfsizing.
```swift

let maxLabelsWidth: CGFloat = 250

title.lx.sizeToFit(width: .value(maxLabelsWidth), height: .max)
details.lx.sizeToFit(width: .value(maxLabelsWidth), height: .max)

container.lx.hwrap(
    Fix(10),
    Fix([title, details], .max), //fixing for view with greatest width
    Fix(10)
)

container.lx.vwrap(
    Fix(10),
    Fix(title),
    Fix(10),
    Fix(details),
    Fix(10)
)

container.lx.center()
```

### Viewport
#### Demo
Viewport can be defined using anchors of any childview, or nil anchor if using superview edges
```swift

blueView.lx.hfill(inset: 20)

self.lx.vput(
    Fix(20),
    Fix(blueView, 20),
    Fix(20),
    Flex(greenView),
    Fix(20)
)

greenView.lx.alignLeft(20)
    .set(width: 20)

self.lx.inViewport(topAnchor: blueView.lx.bottomAnchor.insettedBy(5), leftAnchor: greenView.lx.rightAnchor.insettedBy(5), bottomAnchor: self.lx.bottomAnchor.insettedBy(-5), rightAnchor: self.lx.rightAnchor.insettedBy(-5)) {
    redView.lx.fill()
    heartView.lx.bottomAnchor.follow(self.lx.bottomAnchor)
    heartView.lx.rightAnchor.follow(self.lx.rightAnchor)
}
```


text:
// Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "quiche/quic/core/tls_chlo_extractor.h"

#include <cstring>
#include <memory>

#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/ssl.h"
#include "quiche/quic/core/frames/quic_crypto_frame.h"
#include "quiche/quic/core/quic_data_reader.h"
#include "quiche/quic/core/quic_error_codes.h"
#include "quiche/quic/core/quic_framer.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"

namespace quic {

namespace {
bool HasExtension(const SSL_CLIENT_HELLO* client_hello, uint16_t extension) {
  const uint8_t* unused_extension_bytes;
  size_t unused_extension_len;
  return 1 == SSL_early_callback_ctx_extension_get(client_hello, extension,
                                                   &unused_extension_bytes,
                                                   &unused_extension_len);
}
}  // namespace

TlsChloExtractor::TlsChloExtractor()
    : crypto_stream_sequencer_(this),
      state_(State::kInitial),
      parsed_crypto_frame_in_this_packet_(false) {}

TlsChloExtractor::TlsChloExtractor(TlsChloExtractor&& other)
    : TlsChloExtractor() {
  *this = std::move(other);
}

TlsChloExtractor& TlsChloExtractor::operator=(TlsChloExtractor&& other) {
  framer_ = std::move(other.framer_);
  if (framer_) {
    framer_->set_visitor(this);
  }
  crypto_stream_sequencer_ = std::move(other.crypto_stream_sequencer_);
  crypto_stream_sequencer_.set_stream(this);
  ssl_ = std::move(other.ssl_);
  if (ssl_) {
    std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles();
    int ex_data_index = shared_handles.second;
    const int rv = SSL_set_ex_data(ssl_.get(), ex_data_index, this);
    QUICHE_CHECK_EQ(rv, 1) << "Internal allocation failure in SSL_set_ex_data";
  }
  state_ = other.state_;
  error_details_ = std::move(other.error_details_);
  parsed_crypto_frame_in_this_packet_ =
      other.parsed_crypto_frame_in_this_packet_;
  alpns_ = std::move(other.alpns_);
  server_name_ = std::move(other.server_name_);
  client_hello_bytes_ = std::move(other.client_hello_bytes_);
  return *this;
}

void TlsChloExtractor::IngestPacket(const ParsedQuicVersion& version,
                                    const QuicReceivedPacket& packet) {
  if (state_ == State::kUnrecoverableFailure) {
    QUIC_DLOG(ERROR) << "Not ingesting packet after unrecoverable error";
    return;
  }
  if (version == UnsupportedQuicVersion()) {
    QUIC_DLOG(ERROR) << "Not ingesting packet with unsupported version";
    return;
  }
  if (version.handshake_protocol != PROTOCOL_TLS1_3) {
    QUIC_DLOG(ERROR) << "Not ingesting packet with non-TLS version " << version;
    return;
  }
  if (framer_) {
    // This is not the first packet we have ingested, check if version matches.
    if (!framer_->IsSupportedVersion(version)) {
      QUIC_DLOG(ERROR)
          << "Not ingesting packet with version mismatch, expected "
          << framer_->version() << ", got " << version;
      return;
    }
  } else {
    // This is the first packet we have ingested, setup parser.
    framer_ = std::make_unique<QuicFramer>(
        ParsedQuicVersionVector{version}, QuicTime::Zero(),
        Perspective::IS_SERVER, /*expected_server_connection_id_length=*/0);
    // Note that expected_server_connection_id_length only matters for short
    // headers and we explicitly drop those so we can pass any value here.
    framer_->set_visitor(this);
  }

  // When the framer parses |packet|, if it sees a CRYPTO frame it will call
  // OnCryptoFrame below and that will set parsed_crypto_frame_in_this_packet_
  // to true.
  parsed_crypto_frame_in_this_packet_ = false;
  const bool parse_success = framer_->ProcessPacket(packet);
  if (state_ == State::kInitial && parsed_crypto_frame_in_this_packet_) {
    // If we parsed a CRYPTO frame but didn't advance the state from initial,
    // then it means that we will need more packets to reassemble the full CHLO,
    // so we advance the state here. This can happen when the first packet
    // received is not the first one in the crypto stream. This allows us to
    // differentiate our state between single-packet CHLO and multi-packet CHLO.
    state_ = State::kParsedPartialChloFragment;
  }

  if (!parse_success) {
    // This could be due to the packet being non-initial for example.
    QUIC_DLOG(ERROR) << "Failed to process packet";
    return;
  }
}

// This is called when the framer parsed the unencrypted parts of the header.
bool TlsChloExtractor::OnUnauthenticatedPublicHeader(
    const QuicPacketHeader& header) {
  if (header.form != IETF_QUIC_LONG_HEADER_PACKET) {
    QUIC_DLOG(ERROR) << "Not parsing non-long-header packet " << header;
    return false;
  }
  if (header.long_packet_type != INITIAL) {
    QUIC_DLOG(ERROR) << "Not parsing non-initial packet " << header;
    return false;
  }
  // QuicFramer is constructed without knowledge of the server's connection ID
  // so it needs to be set up here in order to decrypt the packet.
  framer_->SetInitialObfuscators(header.destination_connection_id);
  return true;
}

// This is called by the framer if it detects a change in version during
// parsing.
bool TlsChloExtractor::OnProtocolVersionMismatch(ParsedQuicVersion version) {
  // This should never be called because we already check versions in
  // IngestPacket.
  QUIC_BUG(quic_bug_10855_1) << "Unexpected version mismatch, expected "
                             << framer_->version() << ", got " << version;
  return false;
}

// This is called by the QuicStreamSequencer if it encounters an unrecoverable
// error that will prevent it from reassembling the crypto stream data.
void TlsChloExtractor::OnUnrecoverableError(QuicErrorCode error,
                                            const std::string& details) {
  HandleUnrecoverableError(absl::StrCat(
      "Crypto stream error ", QuicErrorCodeToString(error), ": ", details));
}

void TlsChloExtractor::OnUnrecoverableError(
    QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
    const std::string& details) {
  HandleUnrecoverableError(absl::StrCat(
      "Crypto stream error ", QuicErrorCodeToString(error), "(",
      QuicIetfTransportErrorCodeString(ietf_error), "): ", details));
}

// This is called by the framer if it sees a CRYPTO frame during parsing.
bool TlsChloExtractor::OnCryptoFrame(const QuicCryptoFrame& frame) {
  if (frame.level != ENCRYPTION_INITIAL) {
    // Since we drop non-INITIAL packets in OnUnauthenticatedPublicHeader,
    // we should never receive any CRYPTO frames at other encryption levels.
    QUIC_BUG(quic_bug_10855_2) << "Parsed bad-level CRYPTO frame " << frame;
    return false;
  }
  // parsed_crypto_frame_in_this_packet_ is checked in IngestPacket to allow
  // advancing our state to track the difference between single-packet CHLO
  // and multi-packet CHLO.
  parsed_crypto_frame_in_this_packet_ = true;
  crypto_stream_sequencer_.OnCryptoFrame(frame);
  return true;
}

// Called by the QuicStreamSequencer when it receives a CRYPTO frame that
// advances the amount of contiguous data we now have starting from offset 0.
void TlsChloExtractor::OnDataAvailable() {
  // Lazily set up BoringSSL handle.
  SetupSslHandle();

  // Get data from the stream sequencer and pass it to BoringSSL.
  struct iovec iov;
  while (crypto_stream_sequencer_.GetReadableRegion(&iov)) {
    const int rv = SSL_provide_quic_data(
        ssl_.get(), ssl_encryption_initial,
        reinterpret_cast<const uint8_t*>(iov.iov_base), iov.iov_len);
    if (rv != 1) {
      HandleUnrecoverableError("SSL_provide_quic_data failed");
      return;
    }
    crypto_stream_sequencer_.MarkConsumed(iov.iov_len);
  }

  // Instruct BoringSSL to attempt parsing a full CHLO from the provided data.
  // We ignore the return value since we know the handshake is going to fail
  // because we explicitly cancel processing once we've parsed the CHLO.
  (void)SSL_do_handshake(ssl_.get());
}

// static
TlsChloExtractor* TlsChloExtractor::GetInstanceFromSSL(SSL* ssl) {
  std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles();
  int ex_data_index = shared_handles.second;
  return reinterpret_cast<TlsChloExtractor*>(
      SSL_get_ex_data(ssl, ex_data_index));
}

// static
int TlsChloExtractor::SetReadSecretCallback(
    SSL* ssl, enum ssl_encryption_level_t /*level*/,
    const SSL_CIPHER* /*cipher*/, const uint8_t* /*secret*/,
    size_t /*secret_length*/) {
  GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("SetReadSecretCallback");
  return 0;
}

// static
int TlsChloExtractor::SetWriteSecretCallback(
    SSL* ssl, enum ssl_encryption_level_t /*level*/,
    const SSL_CIPHER* /*cipher*/, const uint8_t* /*secret*/,
    size_t /*secret_length*/) {
  GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("SetWriteSecretCallback");
  return 0;
}

// static
int TlsChloExtractor::WriteMessageCallback(
    SSL* ssl, enum ssl_encryption_level_t /*level*/, const uint8_t* /*data*/,
    size_t /*len*/) {
  GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("WriteMessageCallback");
  return 0;
}

// static
int TlsChloExtractor::FlushFlightCallback(SSL* ssl) {
  GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("FlushFlightCallback");
  return 0;
}

void TlsChloExtractor::HandleUnexpectedCallback(
    const std::string& callback_name) {
  std::string error_details =
      absl::StrCat("Unexpected callback ", callback_name);
  QUIC_BUG(quic_bug_10855_3) << error_details;
  HandleUnrecoverableError(error_details);
}

// static
int TlsChloExtractor::SendAlertCallback(SSL* ssl,
                                        enum ssl_encryption_level_t /*level*/,
                                        uint8_t desc) {
  GetInstanceFromSSL(ssl)->SendAlert(desc);
  return 0;
}

void TlsChloExtractor::SendAlert(uint8_t tls_alert_value) {
  if (tls_alert_value == SSL3_AD_HANDSHAKE_FAILURE && HasParsedFullChlo()) {
    // This is the most common scenario. Since we return an error from
    // SelectCertCallback in order to cancel further processing, BoringSSL will
    // try to send this alert to tell the client that the handshake failed.
    return;
  }
  HandleUnrecoverableError(absl::StrCat(
      "BoringSSL attempted to send alert ", static_cast<int>(tls_alert_value),
      " ", SSL_alert_desc_string_long(tls_alert_value)));
  if (state_ == State::kUnrecoverableFailure) {
    tls_alert_ = tls_alert_value;
  }
}

// static
enum ssl_select_cert_result_t TlsChloExtractor::SelectCertCallback(
    const SSL_CLIENT_HELLO* client_hello) {
  GetInstanceFromSSL(client_hello->ssl)->HandleParsedChlo(client_hello);
  // Always return an error to cancel any further processing in BoringSSL.
  return ssl_select_cert_error;
}

// Extracts the server name and ALPN from the parsed ClientHello.
void TlsChloExtractor::HandleParsedChlo(const SSL_CLIENT_HELLO* client_hello) {
  const char* server_name =
      SSL_get_servername(client_hello->ssl, TLSEXT_NAMETYPE_host_name);
  if (server_name) {
    server_name_ = std::string(server_name);
  }

  resumption_attempted_ =
      HasExtension(client_hello, TLSEXT_TYPE_pre_shared_key);
  early_data_attempted_ = HasExtension(client_hello, TLSEXT_TYPE_early_data);

  QUICHE_DCHECK(client_hello_bytes_.empty());
  client_hello_bytes_.assign(
      client_hello->client_hello,
      client_hello->client_hello + client_hello->client_hello_len);

  const uint8_t* alpn_data;
  size_t alpn_len;
  int rv = SSL_early_callback_ctx_extension_get(
      client_hello, TLSEXT_TYPE_application_layer_protocol_negotiation,
      &alpn_data, &alpn_len);
  if (rv == 1) {
    QuicDataReader alpns_reader(reinterpret_cast<const char*>(alpn_data),
                                alpn_len);
    absl::string_view alpns_payload;
    if (!alpns_reader.ReadStringPiece16(&alpns_payload)) {
      HandleUnrecoverableError("Failed to read alpns_payload");
      return;
    }
    QuicDataReader alpns_payload_reader(alpns_payload);
    while (!alpns_payload_reader.IsDoneReading()) {
      absl::string_view alpn_payload;
      if (!alpns_payload_reader.ReadStringPiece8(&alpn_payload)) {
        HandleUnrecoverableError("Failed to read alpn_payload");
        return;
      }
      alpns_.emplace_back(std::string(alpn_payload));
    }
  }

  // Update our state now that we've parsed a full CHLO.
  if (state_ == State::kInitial) {
    state_ = State::kParsedFullSinglePacketChlo;
  } else if (state_ == State::kParsedPartialChloFragment) {
    state_ = State::kParsedFullMultiPacketChlo;
  } else {
    QUIC_BUG(quic_bug_10855_4)
        << "Unexpected state on successful parse " << StateToString(state_);
  }
}

// static
std::pair<SSL_CTX*, int> TlsChloExtractor::GetSharedSslHandles() {
  // Use a lambda to benefit from C++11 guarantee that static variables are
  // initialized lazily in a thread-safe manner. |shared_handles| is therefore
  // guaranteed to be initialized exactly once and never destructed.
  static std::pair<SSL_CTX*, int>* shared_handles = []() {
    CRYPTO_library_init();
    SSL_CTX* ssl_ctx = SSL_CTX_new(TLS_with_buffers_method());
    SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION);
    SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);
    static const SSL_QUIC_METHOD kQuicCallbacks{
        TlsChloExtractor::SetReadSecretCallback,
        TlsChloExtractor::SetWriteSecretCallback,
        TlsChloExtractor::WriteMessageCallback,
        TlsChloExtractor::FlushFlightCallback,
        TlsChloExtractor::SendAlertCallback};
    SSL_CTX_set_quic_method(ssl_ctx, &kQuicCallbacks);
    SSL_CTX_set_select_certificate_cb(ssl_ctx,
                                      TlsChloExtractor::SelectCertCallback);
    int ex_data_index =
        SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
    return new std::pair<SSL_CTX*, int>(ssl_ctx, ex_data_index);
  }();
  return *shared_handles;
}

// Sets up the per-instance SSL handle needed by BoringSSL.
void TlsChloExtractor::SetupSslHandle() {
  if (ssl_) {
    // Handles have already been set up.
    return;
  }

  std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles();
  SSL_CTX* ssl_ctx = shared_handles.first;
  int ex_data_index = shared_handles.second;

  ssl_ = bssl::UniquePtr<SSL>(SSL_new(ssl_ctx));
  const int rv = SSL_set_ex_data(ssl_.get(), ex_data_index, this);
  QUICHE_CHECK_EQ(rv, 1) << "Internal allocation failure in SSL_set_ex_data";
  SSL_set_accept_state(ssl_.get());

  // Make sure we use the right TLS extension codepoint.
  int use_legacy_extension = 0;
  if (framer_->version().UsesLegacyTlsExtension()) {
    use_legacy_extension = 1;
  }
  SSL_set_quic_use_legacy_codepoint(ssl_.get(), use_legacy_extension);
}

// Called by other methods to record any unrecoverable failures they experience.
void TlsChloExtractor::HandleUnrecoverableError(
    const std::string& error_details) {
  if (HasParsedFullChlo()) {
    // Ignore errors if we've parsed everything successfully.
    QUIC_DLOG(ERROR) << "Ignoring error: " << error_details;
    return;
  }
  QUIC_DLOG(ERROR) << "Handling error: " << error_details;

  state_ = State::kUnrecoverableFailure;

  if (error_details_.empty()) {
    error_details_ = error_details;
  } else {
    error_details_ = absl::StrCat(error_details_, "; ", error_details);
  }
}

// static
std::string TlsChloExtractor::StateToString(State state) {
  switch (state) {
    case State::kInitial:
      return "Initial";
    case State::kParsedFullSinglePacketChlo:
      return "ParsedFullSinglePacketChlo";
    case State::kParsedFullMultiPacketChlo:
      return "ParsedFullMultiPacketChlo";
    case State::kParsedPartialChloFragment:
      return "ParsedPartialChloFragment";
    case State::kUnrecoverableFailure:
      return "UnrecoverableFailure";
  }
  return absl::StrCat("Unknown(", static_cast<int>(state), ")");
}

std::ostream& operator<<(std::ostream& os,
                         const TlsChloExtractor::State& state) {
  os << TlsChloExtractor::StateToString(state);
  return os;
}

}  // namespace quic

redpajama_set_name: RedPajamaGithub


text:
@protocol  ABFloatingTabsDelegate <NSObject>

- (void)clickedTabAtIndex:(NSInteger)index;

@end

//

@interface ABFloatingTabs : UXBar

@property (nonatomic, strong) NSArray<NSString*> *titles;
@property (nonatomic, assign) NSInteger selectedIndex;
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, weak) id<ABFloatingTabsDelegate> delegate;

@end


text:
package org.jikesrvm.ia32;

import org.jikesrvm.Constants;
import org.vmmagic.unboxed.Offset;

/**
 * Registers used by baseline compiler implementation of virtual machine.
 */
public interface BaselineConstants extends Constants, ArchConstants {

  int WORDSIZE = 4; // bytes
  int LG_WORDSIZE = 2;

  // Dedicated registers.
  //
  RegisterConstants.GPR SP = ESP;
  RegisterConstants.GPR PR = PROCESSOR_REGISTER;

  // Volatile (parameter) registers.
  //
  RegisterConstants.GPR T0 = EAX;  // DO NOT CHANGE THIS ASSIGNMENT
  RegisterConstants.GPR T1 = EDX;

  // scratch register
  RegisterConstants.GPR S0 = ECX;
  RegisterConstants.GPR S1 = EDI;

  // Mnemonics corresponding to the above constants.
  // These are some alternate names that can be used in the debugger
  //
  String[] RVM_GPR_NAMES = {"eax", "ecx", "edx", "ebx", "esp", "ebp", "PR", "JT"};

  // Constants describing baseline compiler conventions for
  // saving registers in stackframes.
  //
  int STACKFRAME_REG_SAVE_OFFSET = STACKFRAME_BODY_OFFSET;
  // offset from FP of the saved registers.
  // Some registers are saved in all baseline
  // frames, and most register as saved in the
  // dynamic bridge frames.
  int STACKFRAME_FIRST_PARAMETER_OFFSET = STACKFRAME_REG_SAVE_OFFSET - 8;
  // bridge frames save 3 additional GPRs
  int BRIDGE_FRAME_EXTRA_SIZE = (SSE2_FULL ? XMM_STATE_SIZE : FPU_STATE_SIZE) + 8;

  int SAVED_GPRS = 2; // EDI and EBX are nonvolatile registers used by baseline compiler
  Offset EDI_SAVE_OFFSET = Offset.fromIntSignExtend(STACKFRAME_REG_SAVE_OFFSET);
  Offset EBX_SAVE_OFFSET = Offset.fromIntSignExtend(STACKFRAME_REG_SAVE_OFFSET).minus(4);
  Offset T0_SAVE_OFFSET = Offset.fromIntSignExtend(STACKFRAME_FIRST_PARAMETER_OFFSET);
  Offset T1_SAVE_OFFSET = Offset.fromIntSignExtend(STACKFRAME_FIRST_PARAMETER_OFFSET).minus(4);
  Offset FPU_SAVE_OFFSET = T1_SAVE_OFFSET.minus(FPU_STATE_SIZE);
  Offset XMM_SAVE_OFFSET = T1_SAVE_OFFSET.minus(XMM_STATE_SIZE);

}


text:
#pragma once

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <map>

#ifndef __CUDACC__
#include <cmath>

#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

#ifndef __CUDACC__
namespace gpu {
#include <cuda_runtime.h>
}
#endif

namespace gpu {
#include <curand_kernel.h>
}
typedef gpu::curandState RNG;

#include "config.h"


text:
package org.hd.d.edh;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

/**Graphics utilities, eg generating Web-friendly output icons/buttons/etc.
 */
public final class GraphicsUtils
    {
    /**Prevent creation of an instance. */
    private GraphicsUtils() { }

    /**Minimum simple icon size (both dimensions) in pixels; strictly positive. */
    public static final int MIN_ICON_SIZE_PX = 32;

    /**Target icon border (around text) in pixels; strictly positive. */
    private static final int ICON_BORDER_PX = 1;

    /**Background colour for unknown traffic-light status; non-null. */
    public static final Color TL_UNKNOWN_ICON_BG = Color.WHITE;
    /**Background colour for yellow traffic-light status; non-null. */
    public static final Color TL_YELLOW_ICON_BG = new Color(0xffffcc);
    /**Background colour for green traffic-light status; non-null. */
    public static final Color TL_GREEN_ICON_BG = new Color(0xccffcc);
    /**Background colour for red traffic-light status; non-null. */
    public static final Color TL_RED_ICON_BG = new Color(0xffcccc);

    /**If true, aim to minimise PNG icon size, immediately or after (say) zopflipng post-processing.
     * This may be using a palette, skipping anti-aliasing, and other techniques.
     * <p>
     * In practice this seems to make for a less-readable icon.
     */
    public static final boolean MINIMISE_PNG_ICON_SIZE = false;

    /**Write a simple PNG icon containing the current intensity and with the current traffic-light colour; never null.
     * This attempts to update the output atomically and leaving it globally readable at all times.
     *
     * The current intensity is usually expected to be (well) within the range [0,1000],
     * but this routine will attempt to behave gracefully for values ≥1000.
     *
     * @param basename  base path including file name stub at which icon is to be written; never null
     * @param sizePX  icon output size (each side) in pixels; strictly positive and no less than MIN_ICON_SIZE_PX
     * @param timestamp  timestamp of underlying data, or 0 if none
     * @param status  traffic-light status; null for unknown
     * @param currentIntensity  current grid intensity in gCO2/kWh (kgCO2/MWh); non-negative
     * @return URL-friendly pure-printable-ASCII (no-'/') extension to add to basename for where PNG is written (does not vary with status/intensity arguments); never null nor empty.
     */
    public static String writeSimpleIntensityIconPNG(final String basename, final int sizePX, final long timestamp, final TrafficLight status, final int currentIntensity)
        throws IOException
        {
        if(null == basename) { throw new IllegalArgumentException(); }
        if(sizePX < MIN_ICON_SIZE_PX) { throw new IllegalArgumentException(); }
        if(currentIntensity < 0) { throw new IllegalArgumentException(); }

        // Basic text to show in the icon.
        final String basicIconText = String.valueOf(currentIntensity);

        // Get font set up...
        final Font fontTmp = Font.decode(null); // Use system default font...

        final BufferedImage buffer = new BufferedImage(sizePX, sizePX,
        		MINIMISE_PNG_ICON_SIZE ? BufferedImage.TYPE_BYTE_INDEXED : BufferedImage.TYPE_INT_RGB);
        final Graphics2D g = buffer.createGraphics();
        try
            {
            Color bgColour = TL_UNKNOWN_ICON_BG;
            if(null != status)
                {
                switch(status)
                    {
                    case RED: bgColour = TL_RED_ICON_BG; break;
                    case GREEN: bgColour = TL_GREEN_ICON_BG; break;
                    case YELLOW: bgColour = TL_YELLOW_ICON_BG; break;
                    }
                }
            g.setColor(bgColour);
            g.fillRect(0, 0, sizePX, sizePX);

            // The text looks very rough without anti-aliasing.
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // Size the main intensity number text to fit the icon (width).
            final FontRenderContext fc = g.getFontRenderContext();
            final Rectangle2D boundsTmp = fontTmp.getStringBounds(basicIconText, fc);
            final double wTmp = boundsTmp.getWidth();
            final double hTmp = boundsTmp.getHeight();
            final float sTmp = fontTmp.getSize2D();
            final int fitToWidth = sizePX - (2*ICON_BORDER_PX);
            final int fitToHeight = ((2*sizePX)/3) - (2*ICON_BORDER_PX); // Allow text to take 2/3rds of height.
            assert(fitToWidth > 0);
            assert(fitToHeight > 0);
//            System.out.println("initial width and height with font size "+sTmp+": " + wTmp + ", " + hTmp);
            final float fontMainScaleFactor = Math.min(fitToWidth / (float) wTmp, fitToHeight / (float) hTmp);
            final Font fontMain = fontTmp.deriveFont(sTmp * fontMainScaleFactor);
            final Rectangle2D boundsMain = fontMain.getStringBounds(basicIconText, fc);
            final double hMain = boundsMain.getHeight();
//            final double wMain = boundsMain.getWidth();
//            final float sMain = fontMain.getSize2D();
//            System.out.println("scaled ("+fontMainScaleFactor+") width and height with font size "+sMain+": " + wMain + ", " + hMain);
            g.setFont(fontMain);
            g.setColor(Color.BLACK);
            g.drawString(basicIconText, (int) (-boundsMain.getCenterX() + (sizePX/2.0)), (int) ((-boundsMain.getY() + (sizePX/2.0)) - (hMain/2.0))); // Centre vertically.

            // Only add time and units lines when larger than the minimum dimensions.
            // At minimum size these extra lines are essentially unreadable.
            if(sizePX > MIN_ICON_SIZE_PX)
	            {
	            // Show units at the bottom of the icon, ie under the number.
	            final String units = "gCO2/kWh";
	            final Rectangle2D boundsUTmp = fontTmp.getStringBounds(units, fc);
	            final double wUTmp = boundsUTmp.getWidth();
	            final double hUTmp = boundsUTmp.getHeight();
	            final int fitUToWidth = sizePX - (2*ICON_BORDER_PX);
	            final float fitUToHeight = (float) (((sizePX - hMain)/2.0) - 1); // Allow a 1-pixel extra border/gap; don't round prematurely.
	            final float fontUScaleFactor = Math.min(fitUToWidth / (float) wUTmp, fitUToHeight / (float) hUTmp);
	            final Font fontU = fontTmp.deriveFont(sTmp * fontUScaleFactor);
	            final Rectangle2D boundsU = fontU.getStringBounds(units, fc);
	            g.setFont(fontU);
	            g.setColor(Color.BLACK);
	            g.drawString(units, (int) (-boundsU.getCenterX() + (sizePX/2.0)), sizePX - ((int)(boundsU.getY() + boundsU.getHeight())) - ICON_BORDER_PX); // At bottom (with margin).

	            // If a timestamp is supplied
	            // then squeeze it into the display above the intensity (in grey).
	            if(0 != timestamp)
	                {
	                final SimpleDateFormat fmt = FUELINSTUtils.getHHMMTimestampParser();
	                final String ts = "@" + fmt.format(new Date(timestamp)) + "Z";
	                final Rectangle2D boundsTSTmp = fontTmp.getStringBounds(ts, fc);
	                final double wTSTmp = boundsTSTmp.getWidth();
	                final double hTSTmp = boundsTSTmp.getHeight();
	                final int fitTSToWidth = sizePX - (2*ICON_BORDER_PX);
	                final float fitTSToHeight = (float) (((sizePX - hMain)/2.0) - 1); // Allow a 1-pixel extra border/gap; don't round prematurely.
	                final float fontTSScaleFactor = Math.min(fitTSToWidth / (float) wTSTmp, fitTSToHeight / (float) hTSTmp);
	                final Font fontTS = fontTmp.deriveFont(sTmp * fontTSScaleFactor);
	                final Rectangle2D boundsTS = fontTS.getStringBounds(ts, fc);
	                g.setFont(fontTS);
	                g.setColor(Color.GRAY);
	                g.drawString(ts, (int) (-boundsTS.getCenterX() + (sizePX/2.0)), ((int)(-boundsTS.getY())) + ICON_BORDER_PX); // At top (with margin).
	                }
	            }
            }
        finally { g.dispose(); }

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(buffer, "png", baos);

        final String suffix = "intico1-" + sizePX + ".png";
        DataUtils.replacePublishedFile(basename + suffix, baos.toByteArray());

        return(suffix);
        }
    }


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.contrib.postgres.fields
from django.conf import settings
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('editorial', '0042_auto_20171115_1207'),
    ]

    operations = [
        migrations.CreateModel(
            name='FacetTemplate',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=50)),
                ('description', models.CharField(max_length=100, blank=True)),
                ('fields', django.contrib.postgres.fields.ArrayField(default=list, help_text=b'Fields used by this template.', size=None, base_field=models.CharField(max_length=50), blank=True)),
                ('creation_date', models.DateTimeField(help_text=b'When template was created.', auto_now_add=True)),
                ('is_active', models.BooleanField(default=True)),
                ('organization', models.ForeignKey(blank=True, to='editorial.Organization', null=True)),
                ('owner', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
            ],
        ),
        migrations.AddField(
            model_name='facet',
            name='template',
            field=models.ForeignKey(default=None, to='editorial.FacetTemplate'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='historicalfacet',
            name='template',
            field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.DO_NOTHING, db_constraint=False, blank=True, to='editorial.FacetTemplate', null=True),
        ),
    ]


text:
require 'active_support/concern'

module UserScopesConcern
  extend ActiveSupport::Concern

  included do
    scope :by_user, ->(user) { where(user_id: user.id) }
  end
end


text:
package org.apache.lucene.search.vectorhighlight;

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

import org.apache.lucene.search.vectorhighlight.FieldFragList.WeightedFragInfo.SubInfo;
import org.apache.lucene.search.vectorhighlight.FieldPhraseList.WeightedPhraseInfo;

/**
 * A simple implementation of {@link FieldFragList}.
 */
public class SimpleFieldFragList extends FieldFragList {

  /**
   * a constructor.
   *
   * @param fragCharSize the length (number of chars) of a fragment
   */
  public SimpleFieldFragList( int fragCharSize ) {
    super( fragCharSize );
  }

  /* (non-Javadoc)
   * @see org.apache.lucene.search.vectorhighlight.FieldFragList#add( int startOffset, int endOffset, List<WeightedPhraseInfo> phraseInfoList )
   */
  @Override
  public void add( int startOffset, int endOffset, List<WeightedPhraseInfo> phraseInfoList ) {
    float totalBoost = 0;
    List<SubInfo> subInfos = new ArrayList<>();
    for( WeightedPhraseInfo phraseInfo : phraseInfoList ){
      subInfos.add( new SubInfo( phraseInfo.getText(), phraseInfo.getTermsOffsets(), phraseInfo.getSeqnum(), phraseInfo.getBoost() ) );
      totalBoost += phraseInfo.getBoost();
    }
    getFragInfos().add( new WeightedFragInfo( startOffset, endOffset, subInfos, totalBoost ) );
  }

}


text:
<?php

namespace TrajetsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TrajetType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //->add('origine')
            //->add('dateDepart', 'datetime')
            //->add('dateArriveePrevue', 'datetime')
            //->add('dateArrivee', 'datetime')
            ->add('estActif', 'choice',
                ['label' => 'Trajet en cours ?',
                    'attr' => ['class' => 'form-control'],
                    'choices' => [
                        true => 'Oui',
                        false => 'Non'
                    ]])
            ->add('estEffectue', 'choice',
                ['label' => 'Trajet clôturé ?',
                    'attr' => ['class' => 'form-control'],
                    'choices' => [
                        true => 'Oui',
                        false => 'Non'
                    ]])
            //->add('destination')
            //->add('etapes')
            //->add('utilisateur')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'TrajetsBundle\Entity\Trajet'
        ));
    }
}


text:
from zeit.cms.i18n import MessageFactory as _
import lxml.etree
import zeit.cms.browser.view
import zeit.edit.browser.view
import zeit.edit.interfaces
import zope.component
import zope.interface
import zope.security.proxy
import zope.viewlet.manager

class BlockViewletManager(
        zeit.edit.browser.view.ErrorPreventingViewletManager):

    def __init__(self, context, request, view):
        super(BlockViewletManager, self).__init__(context, request, view)
        self.validation_class, self.validation_messages = (
            zeit.edit.browser.view.validate(self.context))

    @property
    def css_class(self):
        classes = ['block', 'type-' + self.context.type,
                   'represents-content-object']
        for interface in zope.interface.providedBy(self.context):
            name = '%s.%s' % (interface.__module__, interface.__name__)
            classes.append(name.replace('.', '-'))
        if self.validation_class:
            classes.append(self.validation_class)
        return ' '.join(classes)

class Add(zeit.edit.browser.view.Action):

    type = zeit.edit.browser.view.Form('type')

    def update(self):
        self.undo_description = _(
            "add '${type}' block",
            mapping=dict(type=self.type))
        factory = zope.component.getAdapter(
            self.context, zeit.edit.interfaces.IElementFactory,
            name=self.type)
        created = factory()
        self.reload()
        self.signal('after-reload', 'added', created.__name__)

class Delete(zeit.edit.browser.view.Action):

    key = zeit.edit.browser.view.Form('key')

    def update(self):
        self.undo_description = _(
            "delete '${type}' block",
            mapping=dict(type=self.context[self.key].type))
        del self.context[self.key]
        self.signal('before-reload', 'deleted', self.key)
        self.reload()

class View(zeit.cms.browser.view.Base):

    @property
    def factory(self):
        return zope.component.getAdapter(
            zeit.edit.interfaces.IArea(self.context),
            zeit.edit.interfaces.IElementFactory,
            name=self.context.type)

    def title(self):
        return self.factory.title

class Unknown(zeit.cms.browser.view.Base):

    title = _('Unknown block')

    @property
    def xml(self):
        return lxml.etree.tostring(
            zope.security.proxy.getObject(self.context.xml), pretty_print=True)


text: <input inputmode="email" />


text:
//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2016 Michael Fink
//
/// \file DevicePropertyView.hpp View for device properties
//
#pragma once

// includes
#include "IPhotoModeView.hpp"

// forward references
class IPhotoModeViewHost;
class SourceDevice;

/// win traits for device property view
typedef CWinTraitsOR<LVS_REPORT | LVS_SHOWSELALWAYS, WS_EX_CLIENTEDGE, CControlWinTraits>
   DevicePropertyViewWinTraits;

/// devie property view
class DevicePropertyView :
   public CWindowImpl<DevicePropertyView, CListViewCtrl, DevicePropertyViewWinTraits>,
   public IPhotoModeView
{
   /// base class type
   typedef CWindowImpl<DevicePropertyView, CListViewCtrl, DevicePropertyViewWinTraits> BaseClass;

public:
   /// ctor
   DevicePropertyView(IPhotoModeViewHost& host)
      :m_host(host) {}
   /// dtor
   virtual ~DevicePropertyView() {}

   DECLARE_WND_SUPERCLASS(NULL, CListViewCtrl::GetWndClassName())

private:
   /// column indices
   enum T_enDevicePropertyViewColumns
   {
      columnName = 0,
      columnValue = 1,
      columnType = 2,
      columnReadOnly = 3,
      columnId = 4,
      columnRaw = 5,
   };

private:
   /// inits view
   void Init();

   /// refreshes property list
   void RefreshList();

   // virtual methods from IPhotoModeView

   virtual HWND CreateView(HWND hWndParent) override
   {
      HWND hwnd = BaseClass::Create(hWndParent, rcDefault);

      Init();

      return hwnd;
   }

   virtual BOOL PreTranslateMessage(MSG* /*pMsg*/) override
   {
      return FALSE;
   }

   virtual void DestroyView() override
   {
      ATLVERIFY(TRUE == DestroyWindow());
   }

private:
   BEGIN_MSG_MAP(DevicePropertyView)
   END_MSG_MAP()

// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
// LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& bHandled)

private:
   /// host access
   IPhotoModeViewHost& m_host;
};


text:
	#define DISABLESTEAMWORKS
#endif

#if !DISABLESTEAMWORKS

using System.Runtime.InteropServices;
using IntPtr = System.IntPtr;

namespace Steamworks {
	[System.Serializable]
	public struct UGCFileWriteStreamHandle_t : System.IEquatable<UGCFileWriteStreamHandle_t>, System.IComparable<UGCFileWriteStreamHandle_t> {
		public static readonly UGCFileWriteStreamHandle_t Invalid = new UGCFileWriteStreamHandle_t(0xffffffffffffffff);
		public ulong m_UGCFileWriteStreamHandle;

		public UGCFileWriteStreamHandle_t(ulong value) {
			m_UGCFileWriteStreamHandle = value;
		}

		public override string ToString() {
			return m_UGCFileWriteStreamHandle.ToString();
		}

		public override bool Equals(object other) {
			return other is UGCFileWriteStreamHandle_t && this == (UGCFileWriteStreamHandle_t)other;
		}

		public override int GetHashCode() {
			return m_UGCFileWriteStreamHandle.GetHashCode();
		}

		public static bool operator ==(UGCFileWriteStreamHandle_t x, UGCFileWriteStreamHandle_t y) {
			return x.m_UGCFileWriteStreamHandle == y.m_UGCFileWriteStreamHandle;
		}

		public static bool operator !=(UGCFileWriteStreamHandle_t x, UGCFileWriteStreamHandle_t y) {
			return !(x == y);
		}

		public static explicit operator UGCFileWriteStreamHandle_t(ulong value) {
			return new UGCFileWriteStreamHandle_t(value);
		}

		public static explicit operator ulong(UGCFileWriteStreamHandle_t that) {
			return that.m_UGCFileWriteStreamHandle;
		}

		public bool Equals(UGCFileWriteStreamHandle_t other) {
			return m_UGCFileWriteStreamHandle == other.m_UGCFileWriteStreamHandle;
		}

		public int CompareTo(UGCFileWriteStreamHandle_t other) {
			return m_UGCFileWriteStreamHandle.CompareTo(other.m_UGCFileWriteStreamHandle);
		}
	}
}

#endif // !DISABLESTEAMWORKS


text:
/**
 *
 * The Get Element Rect command returns the dimensions and coordinates of the given web element.
 * The returned value is a dictionary with `x`. `y`, `width` and `height` properties.
 *
 * Note: this command was recently added to the official Webdriver protocol and might not be
 * working with current Selenium driver.
 *
 * @param {String} ID ID of a WebElement JSON object to route the command to
 *
 * @see  https://w3c.github.io/webdriver/webdriver-spec.html#dfn-get-element-rect
 * @type protocol
 *
 */

let elementIdRect = function (id) {
    return this.requestHandler.create({
        path: `/session/:sessionId/element/${id}/rect`,
        method: 'GET'
    })
}

export default elementIdRect


text:
using System.Linq;

namespace Diversion.Triggers
{
    /// <summary>
    /// A version trigger that triggers when a new type is added to an assembly.
    /// </summary>
    public class NewTypeTrigger : IVersionTrigger
    {
        public bool IsTriggered(IAssemblyDiversion diversion)
        {
            return diversion.TypeDiversions.Added.Any(t => t.IsOnApiSurface) || diversion.TypeDiversions.Diverged.Any(t => !t.Old.IsOnApiSurface && t.New.IsOnApiSurface);
        }
    }
}


text:
package filodb.core.store

import com.typesafe.scalalogging.slf4j.StrictLogging
import java.nio.ByteBuffer
import java.util.concurrent.{ConcurrentSkipListMap, ConcurrentNavigableMap}
import javax.xml.bind.DatatypeConverter
import scala.collection.mutable.HashMap
import scala.concurrent.{ExecutionContext, Future}
import spray.caching._

import filodb.core._
import filodb.core.metadata.{Column, Projection, RichProjection}

/**
 * A ColumnStore implementation which is entirely in memory for speed.
 * Good for testing or performance.
 *
 * NOTE: This implementation effectively only works on a single node.
 * We would need, for example, a Spark-specific implementation which can
 * know how to distribute data, or at least keep track of different nodes,
 * TODO: use thread-safe structures
 */
class InMemoryColumnStore(val readEc: ExecutionContext)(implicit val ec: ExecutionContext)
extends CachedMergingColumnStore with InMemoryColumnStoreScanner with StrictLogging {
  import Types._
  import collection.JavaConversions._

  logger.info("Starting InMemoryColumnStore...")

  val segmentCache = LruCache[Segment](100)
  val chunkBatchSize = 256

  val mergingStrategy = new AppendingChunkMergingStrategy(this)

  val chunkDb = new HashMap[(DatasetRef, BinaryPartition, Int), ChunkTree]
  val rowMaps = new HashMap[(DatasetRef, BinaryPartition, Int), RowMapTree]

  def initializeProjection(projection: Projection): Future[Response] = Future.successful(Success)

  def clearProjectionDataInner(projection: Projection): Future[Response] = Future {
    chunkDb.keys.collect { case key @ (ds, _, _) if ds == projection.dataset => chunkDb remove key }
    rowMaps.keys.collect { case key @ (ds, _, _) if ds == projection.dataset => rowMaps remove key }
    Success
  }

  def dropDataset(dataset: DatasetRef): Future[Response] = {
    chunkDb.synchronized {
      chunkDb.retain { case ((ds, _, _), _) => ds != dataset }
    }
    rowMaps.synchronized {
      rowMaps.retain { case ((ds, _, _), _) => ds != dataset }
    }
    Future.successful(Success)
  }

  def writeChunks(dataset: DatasetRef,
                  partition: BinaryPartition,
                  version: Int,
                  segmentId: SegmentId,
                  chunks: Iterator[(ColumnId, ChunkID, ByteBuffer)]): Future[Response] = Future {
    val chunkTree = chunkDb.synchronized {
      chunkDb.getOrElseUpdate((dataset, partition, version), new ChunkTree(Ordering[ChunkKey]))
    }
    chunks.foreach { case (colId, chunkId, bytes) =>
      chunkTree.put((colId, segmentId, chunkId), bytes)
    }
    Success
  }

  def writeChunkRowMap(dataset: DatasetRef,
                       partition: BinaryPartition,
                       version: Int,
                       segmentId: SegmentId,
                       chunkRowMap: ChunkRowMap): Future[Response] = Future {
    val rowMapTree = rowMaps.synchronized {
      rowMaps.getOrElseUpdate((dataset, partition, version), new RowMapTree(Ordering[SegmentId]))
    }
    val (chunkIds, rowNums) = chunkRowMap.serialize()
    rowMapTree.put(segmentId, (chunkIds, rowNums, chunkRowMap.nextChunkId))
    Success
  }

  // Add an efficient scanSegments implementation here, which can avoid much of the async
  // cruft unnecessary for in-memory stuff
  override def scanSegments(projection: RichProjection,
                            columns: Seq[Column],
                            version: Int,
                            method: ScanMethod): Future[Iterator[Segment]] = {
    for { indices <- scanChunkRowMaps(projection, version, method) }
    yield {
      indices.map { case SegmentIndex(binPart, segId, part, segmentKey, binChunkRowMap) =>
        val segInfo = SegmentInfo(part, segmentKey)
        val segment = new RowReaderSegment(projection, segInfo, binChunkRowMap, columns)
        for { column <- columns } {
          val colName = column.name
          val chunkTree = chunkDb.getOrElse((projection.datasetRef, binPart, version), EmptyChunkTree)
          chunkTree.subMap((colName, segId, 0), true, (colName, segId, Int.MaxValue), true)
                   .entrySet.iterator.foreach { entry =>
            val (_, _, chunkId) = entry.getKey
            // NOTE: extremely important to duplicate the ByteBuffer, because of mutable state / multi threading
            segment.addChunk(chunkId, colName, entry.getValue.duplicate)
          }
        }
        segment
      }
    }
  }

  def shutdown(): Unit = {}

  // InMemoryColumnStore is just on one node, so return no splits for now.
  // TODO: achieve parallelism by splitting on a range of partitions.
  def getScanSplits(dataset: DatasetRef, splitsPerNode: Int): Seq[ScanSplit] =
    Seq(InMemoryWholeSplit)

  def bbToHex(bb: ByteBuffer): String = DatatypeConverter.printHexBinary(bb.array)
}

// TODO(velvia): Implement real splits?
case object InMemoryWholeSplit extends ScanSplit {
  def hostnames: Set[String] = Set.empty
}

trait InMemoryColumnStoreScanner extends ColumnStoreScanner {
  import Types._
  import collection.JavaConversions._

  type ChunkKey = (ColumnId, SegmentId, ChunkID)
  type ChunkTree = ConcurrentSkipListMap[ChunkKey, ByteBuffer]
  type RowMapTree = ConcurrentSkipListMap[SegmentId, (ByteBuffer, ByteBuffer, Int)]
  type RowMapTreeLike = ConcurrentNavigableMap[SegmentId, (ByteBuffer, ByteBuffer, Int)]

  val EmptyChunkTree = new ChunkTree(Ordering[ChunkKey])
  val EmptyRowMapTree = new RowMapTree(Ordering[SegmentId])

  def chunkDb: HashMap[(DatasetRef, BinaryPartition, Int), ChunkTree]
  def rowMaps: HashMap[(DatasetRef, BinaryPartition, Int), RowMapTree]

  def readChunks(dataset: DatasetRef,
                 columns: Set[ColumnId],
                 keyRange: BinaryKeyRange,
                 version: Int)(implicit ec: ExecutionContext): Future[Seq[ChunkedData]] = {
    val chunkTree = chunkDb.getOrElse((dataset, keyRange.partition, version),
                                      EmptyChunkTree)
    logger.debug(s"Reading chunks from columns $columns, keyRange $keyRange, version $version")
    val chunks = for { column <- columns.toSeq } yield {
      val startKey = (column, keyRange.start, 0)
      val endKey   = if (keyRange.endExclusive) { (column, keyRange.end, 0) }
                     else                       { (column, keyRange.end, Int.MaxValue) }
      val it = chunkTree.subMap(startKey, true, endKey, !keyRange.endExclusive).entrySet.iterator
      val chunkList = it.toSeq.map { entry =>
        val (colId, segmentId, chunkId) = entry.getKey
        // NOTE: extremely important to duplicate the ByteBuffer, because of mutable state / multi threading
        (segmentId, chunkId, entry.getValue.duplicate)
      }
      ChunkedData(column, chunkList)
    }
    Future.successful(chunks)
  }

  def singlePartScan(projection: RichProjection, version: Int, partition: Any):
    Iterator[(BinaryPartition, RowMapTreeLike)] = {
    val binPart = projection.partitionType.toBytes(partition.asInstanceOf[projection.PK])
    Seq((binPart, rowMaps.getOrElse((projection.datasetRef, binPart, version), EmptyRowMapTree))).
      toIterator
  }

  def multiPartScan(projection: RichProjection, version: Int, partitions: Seq[Any]):
    Iterator[(BinaryPartition, RowMapTreeLike)] = {
    partitions.toIterator.collect { case (partition)  => {
      val binPart = projection.partitionType.toBytes(partition.asInstanceOf[projection.PK])
       (binPart, rowMaps.getOrElse((projection.datasetRef, binPart, version), EmptyRowMapTree))
    }}
  }

  def multiPartRangeScan(projection: RichProjection, version: Int, keyRanges: Seq[KeyRange[_, _]]):
    Iterator[(BinaryPartition, RowMapTreeLike)] = {
    keyRanges.toIterator.collect { case (range) => {
      val binKR = projection.toBinaryKeyRange(range)
      val rowMapTree = rowMaps.getOrElse((projection.datasetRef, binKR.partition, version),
                                        EmptyRowMapTree)
      val subMap = rowMapTree.subMap(binKR.start, true, binKR.end, !binKR.endExclusive)
      (binKR.partition, subMap)
    }}
  }

  def singlePartRangeScan(projection: RichProjection, version: Int, k: KeyRange[_, _]):
    Iterator[(BinaryPartition, RowMapTreeLike)] = {
    val binKR = projection.toBinaryKeyRange(k)
    val rowMapTree = rowMaps.getOrElse((projection.datasetRef, binKR.partition, version),
                                       EmptyRowMapTree)
    val subMap = rowMapTree.subMap(binKR.start, true, binKR.end, !binKR.endExclusive)
    Iterator.single((binKR.partition, subMap))
  }

  def filteredPartScan(projection: RichProjection,
                       version: Int,
                       split: ScanSplit,
                       filterFunc: Any => Boolean): Iterator[(BinaryPartition, RowMapTreeLike)] = {
    val binParts = rowMaps.keysIterator.collect { case (ds, binPart, ver) if
      ds == projection.datasetRef && ver == version => binPart }
    binParts.filter { binPart => filterFunc(projection.partitionType.fromBytes(binPart))
            }.map { binPart => (binPart, rowMaps((projection.datasetRef, binPart, version))) }
  }

  def scanChunkRowMaps(projection: RichProjection,
                       version: Int,
                       method: ScanMethod)
                      (implicit ec: ExecutionContext):
    Future[Iterator[SegmentIndex[projection.PK, projection.SK]]] = {
    val partAndMaps = method match {
      case SinglePartitionScan(partition) => singlePartScan(projection, version, partition)
      case SinglePartitionRangeScan(k)    => singlePartRangeScan(projection, version, k)

      case MultiPartitionScan(partitions) => multiPartScan(projection, version, partitions)
      case MultiPartitionRangeScan(keyRanges) => multiPartRangeScan(projection, version, keyRanges)

      case FilteredPartitionScan(split, filterFunc) =>
        filteredPartScan(projection, version, split, filterFunc)

      case FilteredPartitionRangeScan(split, segRange, filterFunc) =>
        val binSegRange = projection.toBinarySegRange(segRange)
        filteredPartScan(projection, version, split, filterFunc).map { case (binPart, rowMap) =>
          (binPart, rowMap.subMap(binSegRange.start, true, binSegRange.end, true))
        }
    }
    val segIndices = partAndMaps.flatMap { case (binPart, rowMap) =>
      rowMap.entrySet.iterator.map { entry =>
        val (chunkIds, rowNums, nextChunkId) = entry.getValue
        val info = (binPart, entry.getKey, new BinaryChunkRowMap(chunkIds.duplicate,
                                                                 rowNums.duplicate, nextChunkId))
        toSegIndex(projection, info)
      }
    }
    Future.successful(segIndices)
  }
}


text:
package org.pentaho.di.trans;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.steps.loadsave.MemoryRepository;
import org.pentaho.di.trans.steps.loadsave.validator.FieldLoadSaveValidator;
import org.pentaho.di.base.LoadSaveBase;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.xml.XMLHandler;

public class LoadSaveTester<T extends Partitioner> extends LoadSaveBase<T> {

  public LoadSaveTester( Class<T> clazz, List<String> commonAttributes, List<String> xmlAttributes,
      List<String> repoAttributes, Map<String, String> getterMap, Map<String, String> setterMap,
      Map<String, FieldLoadSaveValidator<?>> fieldLoadSaveValidatorAttributeMap,
      Map<String, FieldLoadSaveValidator<?>> fieldLoadSaveValidatorTypeMap ) {
    super( clazz, commonAttributes, xmlAttributes, repoAttributes, getterMap, setterMap,
        fieldLoadSaveValidatorAttributeMap, fieldLoadSaveValidatorTypeMap );
  }

  public LoadSaveTester( Class<T> clazz, List<String> commonAttributes ) {
    super( clazz, commonAttributes );
  }

  public void testSerialization() throws KettleException {
    testXmlRoundTrip();
    testRepoRoundTrip();
    testClone();
  }

  public void testXmlRoundTrip() throws KettleException {
    T metaToSave = createMeta();
    Map<String, FieldLoadSaveValidator<?>> validatorMap =
        createValidatorMapAndInvokeSetters( xmlAttributes, metaToSave );
    T metaLoaded = createMeta();
    String xml = "<step>" + metaToSave.getXML() + "</step>";
    InputStream is = new ByteArrayInputStream( xml.getBytes() );
    metaLoaded.loadXML( XMLHandler.getSubNode( XMLHandler.loadXMLFile( is, null, false, false ), "step" ) );
    validateLoadedMeta( xmlAttributes, validatorMap, metaToSave, metaLoaded );
  }

  public void testRepoRoundTrip() throws KettleException {
    T metaToSave = createMeta();
    Map<String, FieldLoadSaveValidator<?>> validatorMap =
        createValidatorMapAndInvokeSetters( repoAttributes, metaToSave );
    T metaLoaded = createMeta();
    Repository rep = new MemoryRepository();
    metaToSave.saveRep( rep, null, null );
    metaLoaded.loadRep( rep, null );
    validateLoadedMeta( repoAttributes, validatorMap, metaToSave, metaLoaded );
  }

  protected void testClone() {
    T metaToSave = createMeta();
    Map<String, FieldLoadSaveValidator<?>> validatorMap =
        createValidatorMapAndInvokeSetters( xmlAttributes, metaToSave );

    @SuppressWarnings( "unchecked" )
    T metaLoaded = (T) metaToSave.clone();
    validateLoadedMeta( xmlAttributes, validatorMap, metaToSave, metaLoaded );
  }
}


text:
<?php

namespace TransactPRO\Gate\Exceptions;

class NotImplementedAction extends \Exception
{
}


text:
<?php

namespace Riak\Client\Core\Query;

/**
 * Bucket properties used for buckets and bucket types.
 *
 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
 */
class BucketProperties
{
    const R = 'r';
    const W = 'w';
    const PR = 'pr';
    const PW = 'pw';
    const DW = 'dw';
    const RW = 'rw';
    const NAME = 'name';
    const N_VAL = 'nVal';
    const ALLOW_MULT = 'allowMult';
    const LAST_WRITE_WINS = 'lastWriteWins';
    const LINKWALK_FUNCTION = 'linkwalkFunction';
    const CHASH_KEY_FUNCTION = 'chashKeyFunction';
    const PRECOMMIT_HOOKS = 'precommitHooks';
    const POSTCOMMIT_HOOKS = 'postcommitHooks';
    const PRECOMMIT = 'precommit';
    const POSTCOMMIT = 'postcommit';
    const OLD_VCLOCK = 'oldVclock';
    const YOUNG_VCLOCK = 'youngVclock';
    const BIG_VCLOCK = 'bigVclock';
    const SMALL_VCLOCK = 'smallVclock';
    const BASIC_QUORUM = 'basicQuorum';
    const NOTFOUND_OK = 'notfoundOk';
    const SEARCH_INDEX = 'searchIndex';
    const BACKEND = 'backend';
    const SEARCH = 'search';
    const DATATYPE = 'datatype';
    const CONSISTENT = 'consistent';

    /**
     * @var string $name
     */
    private $name;

    /**
     * @var mixed $rw
     */
    private $rw;

    /**
     * @var mixed $rw
     */
    private $dw;

    /**
     * @var mixed $rw
     */
    private $w;

    /**
     * @var mixed $rw
     */
    private $r;

    /**
     * @var mixed $rw
     */
    private $pr;

    /**
     * @var mixed $rw
     */
    private $pw;

    /**
     * @var boolean $notFoundOk
     */
    private $notfoundOk;

    /**
     * @var boolean $basicQuorum
     */
    private $basicQuorum;

    /**
     * @var \Riak\Client\Core\Query\Func\RiakFunction $linkwalkFunction
     */
    private $linkwalkFunction;

    /**
     * @var \Riak\Client\Core\Query\Func\RiakFunction $chashKeyFunction
     */
    private $chashKeyFunction;

    /**
     * @var \Riak\Client\Core\Query\Func\RiakFunction[] $precommitHooks
     */
    private $precommitHooks = [];

    /**
     * @var \Riak\Client\Core\Query\Func\RiakFunction[] $postcommitHooks
     */
    private $postcommitHooks = [];

    /**
     * @var integer $oldVClock
     */
    private $oldVclock;

    /**
     * @var integer $youngVClock
     */
    private $youngVclock;

    /**
     * @var integer $bigVClock
     */
    private $bigVclock;

    /**
     * @var integer $smallVClock
     */
    private $smallVclock;

    /**
     * @var string $backend
     */
    private $backend;

    /**
     * @var integer $nVal
     */
    private $nVal;

    /**
     * @var boolean $lastWriteWins
     */
    private $lastWriteWins;

    /**
     * @var boolean $allowMult
     */
    private $allowMult;

    /**
     * @var boolean $lastWriteWins
     */
    private $search;

    /**
     * @var string $searchIndex
     */
    private $searchIndex;

    /**
     * @var string $datatype
     */
    private $datatype;

    /**
     * @var boolean $consistent
     */
    private $consistent;

    /**
     * @param array $props
     */
    public function __construct(array $props = [])
    {
        foreach ($props as $name => $value) {
            $this->{$name} = $value;
        }
    }

    /**
     * Error handler for unknown property mutator.
     *
     * @param string $name  Unknown property name.
     * @param mixed  $value Property value.
     *
     * @throws \BadMethodCallException
     */
    public function __set($name, $value)
    {
        throw new \InvalidArgumentException(
            sprintf("Unknown property '%s' on '%s'.", $name, get_class($this))
        );
    }

    /**
     * @return integer
     */
    public function getRw()
    {
        return $this->rw;
    }

    /**
     * @return integer
     */
    public function getDw()
    {
        return $this->dw;
    }

    /**
     * @return integer
     */
    public function getW()
    {
        return $this->w;
    }

    /**
     * @return integer
     */
    public function getR()
    {
        return $this->r;
    }

    /**
     * @return integer
     */
    public function getPr()
    {
        return $this->pr;
    }

    /**
     * @return integer
     */
    public function getPw()
    {
        return $this->pw;
    }

    /**
     * @return boolean
     */
    public function getNotFoundOk()
    {
        return $this->notfoundOk;
    }

    /**
     * @return boolean
     */
    public function getBasicQuorum()
    {
        return $this->basicQuorum;
    }

    /**
     * @return \Riak\Client\Core\Query\Func\RiakFunction
     */
    public function getLinkwalkFunction()
    {
        return $this->linkwalkFunction;
    }

    /**
     * @return \Riak\Client\Core\Query\Func\RiakFunction
     */
    public function getChashKeyFunction()
    {
        return $this->chashKeyFunction;
    }

    /**
     * @return array
     */
    public function getPreCommitHooks()
    {
        return $this->postcommitHooks;
    }

    /**
     * @return array
     */
    public function getPostCommitHooks()
    {
        return $this->precommitHooks;
    }

    /**
     * @return integer
     */
    public function getOldVClock()
    {
        return $this->oldVclock;
    }

    /**
     * @return integer
     */
    public function getYoungVClock()
    {
        return $this->youngVclock;
    }

    /**
     * @return integer
     */
    public function getBigVClock()
    {
        return $this->bigVclock;
    }

    /**
     * @return integer
     */
    public function getSmallVClock()
    {
        return $this->smallVclock;
    }

    /**
     * @return string
     */
    public function getBackend()
    {
        return $this->backend;
    }

    /**
     * @return integer
     */
    public function getNVal()
    {
        return $this->nVal;
    }

    /**
     * @return boolean
     */
    public function getLastWriteWins()
    {
        return $this->lastWriteWins;
    }

    /**
     * @return boolean
     */
    public function getAllowMult()
    {
        return $this->allowMult;
    }

    /**
     * @return boolean
     */
    public function getSearch()
    {
        return $this->search;
    }

    /**
     * @return string
     */
    public function getSearchIndex()
    {
        return $this->searchIndex;
    }

    /**
     * @return string
     */
    public function getDatatype()
    {
        return $this->datatype;
    }

    /**
     * @return string
     */
    public function getConsistent()
    {
        return $this->consistent;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}


text:
title: Deploying to Netlify
---

In this guide, we'll walk through how to host & publish your next Gatsby site to [Netlify](https://www.netlify.com/).

Netlify is an excellent option for deploying Gatsby sites. Netlify is a unified
platform that automates your code to create high-performant, easily maintainable
sites and web apps. They provide continuous deployment (Git-triggered builds),
an intelligent, global CDN, full DNS (including custom domains), automated
HTTPS, asset acceleration, and a lot more.

Their free tier includes unlimited personal and commercial projects, HTTPS,
continuous deployment from public or private repos and more.

**NOTE**: There is no need to build the site, Netlify can handle that for us.

## Getting Started - Netlify

Now, that the Gatsby site is running, we need to upload your Gatsby site to [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/) or [Bitbucket](https://bitbucket.org/).

Now, go to Netlify and signup if you haven't already.
We connect to GitHub (or GitLab/Bitbucket) and select the repository.

We can change how Netlify builds and deploys the site.
If we change nothing, Netlify will build the `master` branch of the repository and will invoke the build command after we clicked deploy.
If you would have previously built the site and pushed the build to Git, Netlify would publish the directory selected (`/public`).

After Netlify now finished the build, we can see the website on the given url.

## Continuous Deployment

Now that your site is connected to your repository, Netlify will deploy the site and publish it whenever you push to your Git repo.

## References

- [Introduction to Gatsby](/blog/2017-05-31-introduction-to-gatsby/#deployment)
- [Escalade Sports: From $5000 to \$5/month in Hosting With Gatsby](/blog/2018-06-14-escalade-sports-from-5000-to-5-in-hosting/)
- [Why I created my blog with Gatsby and Contentful](/blog/2017-11-09-why-i-created-my-blog-with-gatsby-and-contentful/#hosting-with-netlify)
- [Gatsby + Contentful + Netlify (and Algolia)](/blog/2017-12-06-gatsby-plus-contentful-plus-netlify/#solution-netlify--gatsby)


text:
using Dapper;
using Template.DataLayer.Auth;
using Template.Domain.Auth;
using log4net;
using Microsoft.AspNet.Identity;
using System;
using System.Data;
using System.Linq;

namespace Template.DataLayer.Startup
{
    /// <summary>
    /// Handles updating the schema when necessary
    /// </summary>
    public sealed class Startup
    {
        private readonly ILog _log = LogManager.GetLogger(typeof(Startup));
        private readonly IConnectionFactory _connectionFactory;
        private readonly bool _isTest = false;
        public string UserId { get; set; }

        public Startup()
        {
            _connectionFactory = new ConnectionFactory();
        }

        public Startup(IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _isTest = true;
        }

        private IDbConnection _connection
        {
            get
            {
                return _connectionFactory.GetConnection();
            }
        }

        /// <summary>
        /// Checks conditions and pre-processes as necessary
        ///
        /// Throws: Database Inaccessible Exception
        ///         InvalidSchemaVersionException
        /// </summary>
        public void Init()
        {
            try
            {
                // The update scrips count should always equal the current schema version.
                // If it does not, rectify it.  If it is higher than the update scripts version,
                // something is wrong and we must throw an invalid schema version exception.
                var currentSchemaVersion = GetDatabaseSchemaVersion();
                if (currentSchemaVersion < Scripts.UpdateScripts.Count)
                {
                    // Set up the identity tables if this is a fresh database
                    if (currentSchemaVersion == 0)
                    {
                        ConfigureIdentityTables();
                    }

                    // Update the schema starting with the appropriate index
                    for (var i = currentSchemaVersion; i < Scripts.UpdateScripts.Count; i++)
                    {
                        RunSchemaUpdateScript(i);
                    }
                }
                else if (currentSchemaVersion > Scripts.UpdateScripts.Count)
                {
                    _log.ErrorFormat("Schema version is higher than application code.  Current Application Code Schema: {0} - Current Database Schmea: {1}",
                        Scripts.UpdateScripts.Count, currentSchemaVersion);
                    throw new ApplicationException("Database schema version is higher than code base version.");
                }
            }
            catch (Exception ex)
            {
                _log.Fatal(ex);
                throw;
            }
        }

        private void ConfigureIdentityTables()
        {
            if (_isTest)
            {
                using (var db = _connection)
                {
                    db.Execute(_identitySqlForTest);
                    CreateUserForTest(db);
                }
                return;
            }
            var context = new ApplicationDbContext();
            var UserManager = new ApplicationUserManager(new UserStore(context));
            var user = new ApplicationUser() { UserName = "test@applicationally.com", Email = "test@applicationally.com" };
            user.Token = new BearerTokenModel();

            // The user will be deleted immediate, so the strength of the password and it being in plaintext should
            // be a relatively low risk.  Alternatively, you could use System.Web.Security.Membership.CreatePassword,
            // however, that is not guaranteed to meet the password strength requirements, which would then throw an error.
            var result = UserManager.Create(user, "alkASDFlkja23894902@#$Q90asdfm!");
            UserManager.Delete(user);
        }

        private void CreateUserForTest(IDbConnection conn)
        {
            var userId = Guid.NewGuid().ToString();
            conn.Execute(@"
INSERT INTO         AspNetUsers
VALUES              (@userId,
                        NULL,
	                    NULL,
                        NULL,
	                    NULL,
                        NULL,
                        NULL,
	                    NULL,
	                    0,
	                    NULL,
                        NULL,
                        NULL,
	                    0,
                        0,
                        NULL,
	                    0,
                        0,
	                    'TestUser');
", new { userId = userId });
            UserId = userId;
        }

        /// <summary>
        /// Mock identity table for testing purposes only
        /// </summary>
        private const string _identitySqlForTest = @"CREATE TABLE AspNetUsers(
	Id int NOT NULL PRIMARY KEY,
	Token_access_token nvarchar(256) NULL,
	Token_token_type nvarchar(256) NULL,
	Token_expires_in bigint NULL,
	Token_UserName nvarchar(256) NULL,
	Token_issued datetime NULL,
	Token_expires datetime NULL,
	Email nvarchar(256) NULL,
	EmailConfirmed bit NOT NULL,
	PasswordHash nvarchar(256) NULL,
	SecurityStamp nvarchar(256) NULL,
	PhoneNumber nvarchar(256) NULL,
	PhoneNumberConfirmed bit NOT NULL,
	TwoFactorEnabled bit NOT NULL,
	LockoutEndDateUtc datetime NULL,
	LockoutEnabled bit NOT NULL,
	AccessFailedCount int NOT NULL,
	UserName nvarchar(256) NOT NULL
);

CREATE TABLE        AspNetRoles
(
    Id int NOT NULL PRIMARY KEY,
    Name NVARCHAR(MAX) NOT NULL
);

";
        /// <summary>
        /// Gets the database schema version.  Returns 0 if it does not exist.
        /// </summary>
        /// <returns></returns>
        private int GetDatabaseSchemaVersion()
        {
            var schemaVersion = 0;
            if (SchemaExists())
            {
                schemaVersion = GetSchemaVersion();
            }
            return schemaVersion;
        }

        /// <summary>
        /// Checks the schema version against the count of the schema updates collection to determine if an update is required.
        /// </summary>
        /// <remarks>
        /// Throws ApplicationException if it cannot connect to the database using the DefaultConnection connection string as defined in the web.config
        /// </remarks>
        /// <returns></returns>
        private bool SchemaExists()
        {
            bool schemaExists = false;
            try
            {
                using (var db = _connection)
                {
                    schemaExists = db.Query<bool>(@"
SELECT				CASE
						WHEN		OBJECT_ID('dbo._SchemaVersion') IS NOT NULL
						THEN		1
						ELSE		0
					END
").FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Unable to connect to sql database using the default connection string set in the web.config.  Please ensure that there is a connection string named \"Default Connection\" with the appropriate permissions.", ex);
            }
            return schemaExists;
        }

        /// <summary>
        /// Gets the database's current schema version.
        /// Check to see that the schema is set up before calling this method.
        /// </summary>
        /// <returns></returns>
        private int GetSchemaVersion()
        {
            using (var db = _connection)
            {
                return db.Query<int>(@"
SELECT              Version
FROM                _SchemaVersion
").FirstOrDefault();
            }
        }

        /// <summary>
        /// Runs an update script based on the index of the script to run.
        /// Rather than accepting raw text to run as a sql script, we are adding
        /// another layer of control by enforcing the use of the Scripts object
        /// </summary>
        /// <param name="SchemaUpdateScriptIndex">The index of the schema update script to run</param>
        /// <returns></returns>
        private void RunSchemaUpdateScript(int SchemaUpdateScriptIndex)
        {
            var UpdateScripts = Scripts.UpdateScripts[SchemaUpdateScriptIndex];
            using (var db = _connection)
            {
                // Scripts are lists of strings to allow for the separation of batch executions
                foreach (var script in UpdateScripts)
                {
                    db.Execute(script);
                }
            }
        }
    }
}


text:
package org.algorithmdb.util;

public class NumberGenerator {
	/**
	 * This method will return an array of size N and values in a
	 * sequence from 0...N
	 *
	 * @param length <int>
	 * @return array <int[]>
	 */
	public static Integer[] getSequenceNumbers(int length) {
		Integer[] array = new Integer[length];
		for (int i=0 ; i<length; i++) {
			array[i] = i;
		}
		return array;
	}

	/**
	 * This method will return an array of size N and values in a
	 * sequence from N...M
	 *
	 * @param initial <int>
	 * @param finish <int>
	 * @return array <int[]>
	 */
	public static Integer[] getSequenceNumbers(int initial, int finish) {
		Integer[] array = new Integer[(finish+1) - initial];
		for(int i = 0; i < array.length;i++){
			array[i] = initial++;
		}
		return array;
	}

	/**
	 * This method will return an array of size N and values in
	 * reverse sequence from N...0
	 *
	 * @param length <int>
	 * @return array <int[]>
	 */
	public static Integer[] getReverseSequenceNumbers(int length) {
		Integer[] array = new Integer[length];
		int temp = length;
		for (int i=0 ; i<length; i++) {
			array[i] = temp-1;
			temp--;
		}
		return array;
	}

	/**
	 * This method will return an array of size N and values in
	 * Random order.
	 *
	 * @param length <int>
	 * @return array <int[]>
	 */
	public static Integer[] getRandomNumbers(int length) {
		Integer[] array = new Integer[length];
		for (int i=0 ; i<length; i++) {
			array[i] = (int) (Math.random() * 1000000);
		}
		return array;
	}
}


text:
var express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser');

// Express components
var routes = require('./routes/index');

// Main Apps
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// TODO uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));

app.use('/', routes);

// error handlers

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler will print stacktrace
var printStack = (app.get('env') === 'development');

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.sendFile('/error.html');
//   res.render('error', {
//     message: err.message,
//     error: printStack ? err : {}
//   });
});

module.exports = app;


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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using HurriyetHaberMobile.CustomRenderer;
using HurriyetHaberMobile.Droid.CustomRenderer;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Text;

[assembly: Xamarin.Forms.ExportRenderer(typeof(HtmlLabel), typeof(HtmlLabelRenderer))]
namespace HurriyetHaberMobile.Droid.CustomRenderer
{
    public class HtmlLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var element = (HtmlLabel)e.NewElement;
            if (element != null && Control != null)
            {
                Control.SetText(Html.FromHtml(element.Text), TextView.BufferType.Spannable);
            }
        }
    }
}


text:
kohana-bundles
==============

Adds bundles to Kohana app


text:
<?php

namespace ZfcUser\Service;

use Zend\Authentication\AuthenticationServiceInterface as AuthenticationService;
use Zend\Form\FormInterface as Form;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use ZfcBase\EventManager\EventProvider;
use ZfcUser\Mapper\HydratorInterface as Hydrator;
use ZfcUser\Mapper\UserInterface as UserMapper;
use ZfcUser\Options\UserServiceOptionsInterface as ServiceOptions;

class User extends EventProvider implements ServiceManagerAwareInterface
{
    /**
     * @var UserMapper
     */
    protected $userMapper;

    /**
     * @var AuthenticationService
     */
    protected $authService;

    /**
     * @var Form
     */
    protected $loginForm;

    /**
     * @var Form
     */
    protected $registerForm;

    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    /**
     * @var ServiceOptions
     */
    protected $options;

    /**
     * @var Hydrator
     */
    protected $formHydrator;

    /**
     * createFromForm
     *
     * @param array $data
     * @return \ZfcUser\Entity\UserInterface
     * @throws Exception\InvalidArgumentException
     */
    public function register(array $data)
    {
        $entityClass = $this->getOptions()->getUserEntityClass();
        $form        = $this->getRegisterForm();

        $form->setHydrator($this->getFormHydrator());
        $form->bind(new $entityClass);
        $form->setData($data);

        if ($form->isValid()) {
            $user   = $form->getData();
            $events = $this->getEventManager();

            $user->setPassword($this->getFormHydrator()->getCryptoService()->create($user->getPassword()));

            $events->trigger(__FUNCTION__, $this, compact('user', 'form'));
            $this->getUserMapper()->insert($user);
            $events->trigger(__FUNCTION__.'.post', $this, compact('user', 'form'));

            return $user;
        }
        return false;
    }

    /**
     * getUserMapper
     *
     * @return UserMapper
     */
    public function getUserMapper()
    {
        if (null === $this->userMapper) {
            $this->setUserMapper($this->serviceManager->get('zfcuser_user_mapper'));
        }
        return $this->userMapper;
    }

    /**
     * setUserMapper
     *
     * @param UserMapperInterface $userMapper
     * @return User
     */
    public function setUserMapper(UserMapper $userMapper)
    {
        $this->userMapper = $userMapper;
        return $this;
    }

    /**
     * getAuthService
     *
     * @return AuthenticationService
     */
    public function getAuthService()
    {
        if (null === $this->authService) {
            $this->setAuthService($this->serviceManager->get('zfcuser_auth_service'));
        }
        return $this->authService;
    }

    /**
     * setAuthenticationService
     *
     * @param AuthenticationService $authService
     * @return User
     */
    public function setAuthService(AuthenticationService $authService)
    {
        $this->authService = $authService;
        return $this;
    }

    /**
     * @return Form
     */
    public function getRegisterForm()
    {
        if (null === $this->registerForm) {
            $this->setRegisterForm($this->serviceManager->get('zfcuser_register_form'));
        }
        return $this->registerForm;
    }

    /**
     * @param Form $registerForm
     * @return User
     */
    public function setRegisterForm(Form $registerForm)
    {
        $this->registerForm = $registerForm;
        return $this;
    }

    /**
     * get service options
     *
     * @return UserServiceOptionsInterface
     */
    public function getOptions()
    {
        if (!$this->options instanceof ServiceOptions) {
            $this->setOptions($this->serviceManager->get('zfcuser_module_options'));
        }
        return $this->options;
    }

    /**
     * set service options
     *
     * @param ServiceOptions $options
     */
    public function setOptions(ServiceOptions $options)
    {
        $this->options = $options;
    }

    /**
     * Retrieve service manager instance
     *
     * @return ServiceManager
     */
    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set service manager instance
     *
     * @param ServiceManager $serviceManager
     * @return User
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }

    /**
     * Return the Form Hydrator
     *
     * @return Hydrator
     */
    public function getFormHydrator()
    {
        if (!$this->formHydrator instanceof Hydrator) {
            $this->setFormHydrator(
                $this->serviceManager->get('zfcuser_user_hydrator')
            );
        }

        return $this->formHydrator;
    }

    /**
     * Set the Form Hydrator to use
     *
     * @param Hydrator $formHydrator
     * @return User
     */
    public function setFormHydrator(Hydrator $formHydrator)
    {
        $this->formHydrator = $formHydrator;
        return $this;
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool
//     Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/// <summary>
/// Новость
/// </summary>
public class News : Component, INews
{
	public virtual void GetAllAnnouncements()
	{
		throw new System.NotImplementedException();
	}

	public virtual void GetAnnouncement(int Id)
	{
		throw new System.NotImplementedException();
	}

}


text:
<?php
/**
 * List view based controls state.
 */

/**
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

declare(strict_types = 1);

namespace Google\Web_Stories\Renderer\Stories\FieldState;

use Google\Web_Stories\Renderer\Stories\Fields\BaseField;

/**
 * Class ListView.
 */
final class ListView extends BaseFieldState {

	/**
	 * Excerpt field.
	 *
	 * @since 1.5.0
	 *
	 * @return \Google\Web_Stories\Interfaces\Field|BaseField
	 */
	public function excerpt() {
		$label = parent::excerpt()->label();

		return $this->prepare_field(
			[
				'label'  => $label,
				'show'   => true,
				'hidden' => false,
			]
		);
	}

	/**
	 * Author field.
	 *
	 * @since 1.5.0
	 *
	 * @return \Google\Web_Stories\Interfaces\Field|BaseField
	 */
	public function date() {
		$label = parent::date()->label();

		return $this->prepare_field(
			[
				'label'  => $label,
				'show'   => true,
				'hidden' => false,
			]
		);
	}

	/**
	 * Image alignment field.
	 *
	 * @since 1.5.0
	 *
	 * @return \Google\Web_Stories\Interfaces\Field|BaseField
	 */
	public function image_alignment() {
		$label = parent::image_alignment()->label();

		return $this->prepare_field(
			[
				'label'  => $label,
				'show'   => true,
				'hidden' => false,
			]
		);
	}
}


text:
namespace BirdNest.Nodes
{

	public class EntireTreeNode : Decorator, IEntireTreeNode {
		public Tree ExistingTree {get;set;}

		public EntireTreeNode(Tree bTree)
		{
			this.ExistingTree = bTree;
		}

		#region implemented abstract members of Decorator

		public override INodeExaminer CreateNodeExaminer ()
		{
			return new EntireTreeNodeExaminer<EntireTreeNode> (this);
		}

		#endregion
	}

}


text:
layout: "alicloud"
page_title: "Alicloud: alicloud_slb"
sidebar_current: "docs-alicloud-resource-slb."
description: |-
  Provides an Application Load Banlancer resource.
---

# alicloud_slb

Provides an Application Load Balancer resource.

## Example Usage

```hcl
# Create a new load balancer for classic
resource "alicloud_slb" "classic" {
  name                 = "test-slb-tf"
  internet             = true
  internet_charge_type = "paybybandwidth"
  bandwidth            = 5

  listener = [
    {
      "instance_port" = "2111"
      "lb_port"       = "21"
      "lb_protocol"   = "tcp"
      "bandwidth"     = "5"
    },
    {
      "instance_port" = "8000"
      "lb_port"       = "80"
      "lb_protocol"   = "http"
      "bandwidth"     = "5"
    },
    {
      "instance_port" = "1611"
      "lb_port"       = "161"
      "lb_protocol"   = "udp"
      "bandwidth"     = "5"
    },
  ]
}

# Create a new load balancer for VPC
resource "alicloud_vpc" "default" {
  # ...
}

resource "alicloud_vswitch" "default" {
  # ...
}

resource "alicloud_slb" "vpc" {
  name       = "test-slb-tf"
  vswitch_id = "${alicloud_vswitch.default.id}"
}
```

## Argument Reference

The following arguments are supported:

* `name` - (Optional) The name of the SLB. This name must be unique within your AliCloud account, can have a maximum of 80 characters,
must contain only alphanumeric characters or hyphens, such as "-","/",".","\_", and must not begin or end with a hyphen. If not specified,
Terraform will autogenerate a name beginning with `tf-lb`.
* `internet` - (Optional, Forces New Resource) If true, the SLB addressType will be internet, false will be intranet, Default is false. If load balancer launched in VPC, this value must be "false".
* `internet_charge_type` - (Optional, Forces New Resource) Valid
  values are `paybybandwidth`, `paybytraffic`. If this value is "paybybandwidth", then argument "internet" must be "true". Default is "paybytraffic". If load balancer launched in VPC, this value must be "paybytraffic".
* `bandwidth` - (Optional) Valid
  value is between 1 and 1000, If argument "internet_charge_type" is "paybytraffic", then this value will be ignore.
* `listener` - (Optional) Additional SLB listener. See [Block listener](#block-listener) below for details.
* `vswitch_id` - (Required for a VPC SLB, Forces New Resource) The VSwitch ID to launch in.

## Block listener

The listener mapping supports the following:

* `instance_port` - (Required) The port on which the backend servers are listening. Valid value is between 1 to 65535.
* `lb_port` - (Required) The port on which the load balancer is listening. Valid value is between 1 to 65535.
* `lb_protocol` - (Required) The protocol to listen on. Valid values are `http` and and `tcp` and `udp`.
* `bandwidth` - (Required) The bandwidth on which the load balancer is  listening. Valid values is -1 or between 1 and 1000. If -1, the bindwidth will haven't upper limit.

## Attributes Reference

The following attributes are exported:

* `id` - The ID of the load balancer.
* `name` - The name of the load balancer.
* `internet` - The internet of the load balancer.
* `internet_charge_type` - The internet_charge_type of the load balancer.
* `bandwidth` - The bandwidth of the load balancer.
* `vswitch_id` - The VSwitch ID of the load balancer. Only available on SLB launched in a VPC.
* `address` - The IP address of the load balancer.


text:
"use strict";

var utils = require('./../../../utils');
var schema = require('./../../schema');

// yamb.prototype.update()

module.exports = function() {
  return function update(params) {
    if (!utils.is.obj(params)) {
      return this;
    }

    for (var param in params) {
      if (!params.hasOwnProperty(param) || utils.is.und(schema[param])) {
        continue;
      }

      this[param] = params[param];
    }

    return this;
  };
};


text:
class EventTag < ActiveRecord::Base
  include Activatable

  validates :event_id, presence: true
  validates :tag_id, presence: true

  belongs_to :tag
  belongs_to :event

  after_save :index_event
  after_destroy :index_event

  private

  def index_event
    event.reload.__elasticsearch__.index_document
  end
end