text:
#ifdef HAVE_CONFIG_H
#  include <dtn-config.h>
#endif

#include <queue>

#include <oasys/util/OptParser.h>
#include <oasys/util/StringBuffer.h>
#include <oasys/util/TokenBucket.h>

#include "SimConvergenceLayer.h"
#include "Connectivity.h"
#include "Node.h"
#include "Simulator.h"
#include "Topology.h"
#include "bundling/Bundle.h"
#include "bundling/BundleEvent.h"
#include "bundling/BundleList.h"
#include "contacts/ContactManager.h"

namespace dtnsim {

class InFlightBundle;

//----------------------------------------------------------------------
class SimLink : public CLInfo,
                public oasys::Logger {
	// Note although this is derived from CLInfo (and hence SerializableObject
	// we don't define serialize and it defaults to the empty routine in CLInfo.
	// Since the simulator uses the memory 'persistent' data store, there is never
	// anything to read back in on restart, so it is irrelevant what is serialized
	// the cl_info field of any Links.
public:
    struct Params;

    SimLink(const LinkRef& link,
            const SimLink::Params& params)
        : Logger("SimLink", "/dtn/cl/sim/%s", link->name()),
          link_(link.object(), "SimLink"),
          params_(params),
          tb_(((std::string)logpath_ + "/tb").c_str(),
              params_.capacity_,
              0xffffffff  /* unlimited rate -- overridden by Connectivity */),
          inflight_timer_(this, PendingEventTimer::INFLIGHT),
          arrival_timer_(this, PendingEventTimer::ARRIVAL),
          transmitted_timer_(this, PendingEventTimer::TRANSMITTED)
    {
    }

    ~SimLink() {};

    void start_next_bundle();
    void timeout(const oasys::Time& now);
    void handle_pending_inflight(const oasys::Time& now);
    void handle_arrival_events(const oasys::Time& now);
    void handle_transmitted_events(const oasys::Time& now);
    void reschedule_timers();

    /// The dtn Link
    LinkRef link_;

    struct Params {
        /// if contact closes in the middle of a transmission, deliver
        /// the partially received bytes to the router.
        bool deliver_partial_;

        /// for bundles sent over the link, signal to the router
        /// whether or not they were delivered reliably by the
        /// convergence layer
        bool reliable_;

        /// burst capacity of the link (default 0)
        u_int capacity_;

        /// automatically infer the remote eid when the link connects
        bool set_remote_eid_;

        /// set the previous hop when bundles arrive
        bool set_prevhop_;

    } params_;

    /// The sending node
    Node* src_node_;

    /// The receiving node
    Node* peer_node_;

    /// Token bucket to track the link rate
    oasys::TokenBucket tb_;

    /// Temp buffer
    u_char buf_[65536];

    /// Helper class to track bundle transmission or reception events
    /// that need to be delivered in the future
    struct PendingEvent {
        PendingEvent(Bundle*            bundle,
                     size_t             total_len,
                     const oasys::Time& time)
            : bundle_(bundle, "SimCL::PendingEvent"),
              total_len_(total_len),
              time_(time) {}

        BundleRef   bundle_;
        size_t      total_len_;
        oasys::Time time_;
    };

    /// Pending event (at most one) to put the next bundle in flight
    PendingEvent* pending_inflight_;

    /// Pending bundle arrival events
    std::queue<PendingEvent*> arrival_events_;

    /// Pending bundle transmitted events
    std::queue<PendingEvent*> transmitted_events_;

    /// Timer class to manage pending events
    class PendingEventTimer : public oasys::Timer {
    public:
        typedef enum { INFLIGHT, ARRIVAL, TRANSMITTED } type_t;

        PendingEventTimer(SimLink* link, type_t type)
            : link_(link), type_(type) {}

        void timeout(const timeval& now);

    protected:
        SimLink* link_;
        type_t   type_;
    };

    /// @{ Three timer instances to independently schedule the timers,
    /// though each class can itself be managed with a FIFO queue.
    PendingEventTimer inflight_timer_;
    PendingEventTimer arrival_timer_;
    PendingEventTimer transmitted_timer_;
    /// @}
};

//----------------------------------------------------------------------
void
SimLink::start_next_bundle()
{
    ASSERT(!link_->queue()->empty());
    ASSERT(pending_inflight_ == NULL);

    // Remember the node that was active on entry
    // Have to control the active node so that operations are done
    // on either the source or destination node as appropriate.
    // Since this routine is called via the (single) timer system,
    // there is no guarantee what node is active when it is called.
    // and we have to force the active node first to the link source
    // and later to the link destination.  The active node is set back
    // to the same as on entry at the end.
    // These considerations also apply to handle_arrival_events and
    // handle_transmitted_events
    Node * orig_node = Node::active_node();

    src_node_->set_active();

    const ConnState* cs = Connectivity::instance()->lookup(src_node_, peer_node_);
    ASSERT(cs);

    BundleRef src_bundle("SimLink::start_next_bundle");
    src_bundle = link_->queue()->front();

    BlockInfoVec* blocks = src_bundle->xmit_blocks()->find_blocks(link_);
    ASSERT(blocks != NULL);

    // since we don't really have any payload to send, we find the
    // payload block and overwrite the data_length to be zero, then
    // adjust the payload_ on the new bundle
    if (src_bundle->payload().location() == BundlePayload::NODATA) {
        BlockInfo* payload = const_cast<BlockInfo*>(
            blocks->find_block(BundleProtocol::PAYLOAD_BLOCK));
        ASSERT(payload != NULL);
        payload->set_data_length(0);
    }

    bool complete = false;
    size_t len = BundleProtocol::produce(src_bundle.object(), blocks,
                                         buf_, 0, sizeof(buf_),
                                         &complete);
    ASSERTF(complete, "BundleProtocol non-payload blocks must fit in "
            "65 K buffer size");

    size_t total_len = len;

    if (src_bundle->payload().location() == BundlePayload::NODATA)
        total_len += src_bundle->payload().length();

    complete = false;
    peer_node_->set_active();
    Bundle* dst_bundle = new Bundle(src_bundle->payload().location());
    int cc = BundleProtocol::consume(dst_bundle, buf_, len, &complete);
    ASSERT(cc == (int)len);
    ASSERT(complete);

    if (src_bundle->payload().location() == BundlePayload::NODATA) {
        dst_bundle->mutable_payload()->set_length(src_bundle->payload().length());
    }

    tb_.drain(total_len * 8);

    oasys::Time bw_delay = tb_.time_to_level(0);
    oasys::Time inflight_time = oasys::Time(Simulator::time()) + bw_delay;
    oasys::Time arrival_time = inflight_time + cs->latency_;
    oasys::Time transmitted_time;

    // the transmitted event either occurs after the "ack" comes back
    // (when in reliable mode) or immediately after we send the bundle
    if (params_.reliable_) {
        transmitted_time = inflight_time + (cs->latency_ * 2);
    } else {
        transmitted_time = inflight_time;
    }

    log_debug("send_bundle src %d dst %d: total len %zu, "
              "inflight_time %u.%u arrival_time %u.%u transmitted_time %u.%u",
              src_bundle->bundleid(), dst_bundle->bundleid(), total_len,
              inflight_time.sec_, inflight_time.usec_,
              arrival_time.sec_, arrival_time.usec_,
              transmitted_time.sec_, transmitted_time.usec_);

    pending_inflight_ = new PendingEvent(src_bundle.object(), total_len, inflight_time);
    arrival_events_.push(new PendingEvent(dst_bundle, total_len, arrival_time));
    transmitted_events_.push(new PendingEvent(src_bundle.object(), total_len, transmitted_time));

    reschedule_timers();
    orig_node->set_active();
}

//----------------------------------------------------------------------
void
SimLink::reschedule_timers()
{
    // if the timer is already pending, there's no need to reschedule
    // since the channel is FIFO and latency changes don't take effect
    // mid-flight

    if (! inflight_timer_.pending() && pending_inflight_ != NULL)
    {
        inflight_timer_.schedule_at(pending_inflight_->time_);
    }

    if (! arrival_timer_.pending() && !arrival_events_.empty())
    {
        arrival_timer_.schedule_at(arrival_events_.front()->time_);
    }

    if (! transmitted_timer_.pending() && !transmitted_events_.empty())
    {
        transmitted_timer_.schedule_at(transmitted_events_.front()->time_);
    }
}

//----------------------------------------------------------------------
void
SimLink::PendingEventTimer::timeout(const timeval& tv)
{
    oasys::Time now(tv.tv_sec, tv.tv_usec);
    switch (type_) {
    case INFLIGHT:
        link_->handle_pending_inflight(now);
        break;
    case ARRIVAL:
        link_->handle_arrival_events(now);
        break;
    case TRANSMITTED:
        link_->handle_transmitted_events(now);
        break;
    default:
        NOTREACHED;
    }
}

//----------------------------------------------------------------------
void
SimLink::handle_pending_inflight(const oasys::Time& now)
{
    ASSERT(pending_inflight_ != NULL);

    // deliver any bundles that have arrived
    if (pending_inflight_->time_ <= now) {
        const BundleRef& bundle = pending_inflight_->bundle_;

        log_debug("putting *%p in flight", bundle.object());
        link_->add_to_inflight(bundle, pending_inflight_->total_len_);
        link_->del_from_queue(bundle, pending_inflight_->total_len_);

        // XXX/demmer maybe there should be an event for this??

        delete pending_inflight_;
        pending_inflight_ = NULL;

        if (! link_->queue()->empty()) {
            start_next_bundle();
        }
    }

    reschedule_timers();
}

//----------------------------------------------------------------------
void
SimLink::handle_arrival_events(const oasys::Time& now)
{
    ASSERT(! arrival_events_.empty());

    Node * orig_node = Node::active_node();

    // deliver any bundles that have arrived
	peer_node_->set_active();
    while (! arrival_events_.empty()) {
        PendingEvent* next = arrival_events_.front();
        if (next->time_ <= now) {
            const BundleRef& bundle = next->bundle_;
            arrival_events_.pop();

            log_debug("*%p arrived", bundle.object());

            BundleReceivedEvent* rcv_event =
                new BundleReceivedEvent(bundle.object(),
                                        EVENTSRC_PEER,
                                        next->total_len_,
                                        params_.set_prevhop_ ?
                                        Node::active_node()->local_eid() :
                                        EndpointID::NULL_EID());
            peer_node_->post_event(rcv_event);

            delete next;

        } else {
            break;
        }
    }

    reschedule_timers();
    orig_node->set_active();
}

//----------------------------------------------------------------------
void
SimLink::handle_transmitted_events(const oasys::Time& now)
{
    ASSERT(! transmitted_events_.empty());

    Node * orig_node = Node::active_node();

    // deliver any bundles that have arrived
	src_node_->set_active();
    while (! transmitted_events_.empty()) {
        PendingEvent* next = transmitted_events_.front();
        if (next->time_ <= now) {
            const BundleRef& bundle = next->bundle_;
            transmitted_events_.pop();

            log_debug("*%p transmitted", bundle.object());

            ASSERT(link_->contact() != NULL);

            BundleTransmittedEvent* xmit_event =
                new BundleTransmittedEvent(bundle.object(), link_->contact(), link_,
                                           next->total_len_,
                                           params_.reliable_ ? next->total_len_ : 0);
            BundleDaemon::post(xmit_event);

            delete next;
        } else {
            break;
        }
    }

    reschedule_timers();
    orig_node->set_active();
}

//----------------------------------------------------------------------
SimConvergenceLayer* SimConvergenceLayer::instance_;

SimConvergenceLayer::SimConvergenceLayer()
    : ConvergenceLayer("SimConvergenceLayer", "sim")
{
}

//----------------------------------------------------------------------
bool
SimConvergenceLayer::init_link(const LinkRef& link,
                               int argc, const char* argv[])
{
    ASSERT(link != NULL);
    ASSERT(!link->isdeleted());
    ASSERT(link->cl_info() == NULL);

    oasys::OptParser p;
    SimLink::Params params;

    params.deliver_partial_ = true;
    params.reliable_        = true;
    params.capacity_        = 0;
    params.set_remote_eid_  = true;
    params.set_prevhop_     = true;

    p.addopt(new oasys::BoolOpt("deliver_partial", &params.deliver_partial_));
    p.addopt(new oasys::BoolOpt("reliable", &params.reliable_));
    p.addopt(new oasys::UIntOpt("capacity", &params.capacity_));
    p.addopt(new oasys::BoolOpt("set_remote_eid", &params.set_remote_eid_));
    p.addopt(new oasys::BoolOpt("set_prevhop", &params.set_prevhop_));

    const char* invalid;
    if (! p.parse(argc, argv, &invalid)) {
        log_err("error parsing link options: invalid option %s", invalid);
        return false;
    }

    SimLink* sl = new SimLink(link, params);
    sl->src_node_ = Node::active_node();
    sl->peer_node_ = Topology::find_node(link->nexthop());

    ASSERT (sl->peer_node_);
    ASSERT (sl->src_node_ != sl->peer_node_);

    link->set_cl_info(sl);

    return true;
}

//----------------------------------------------------------------------
void
SimConvergenceLayer::delete_link(const LinkRef& link)
{
    ASSERT(link != NULL);
    ASSERT(!link->isdeleted());
    ASSERT(link->cl_info() != NULL);

    log_debug("SimConvergenceLayer::delete_link: "
              "deleting link %s", link->name());

    delete link->cl_info();
    link->set_cl_info(NULL);
}

//----------------------------------------------------------------------
bool
SimConvergenceLayer::open_contact(const ContactRef& contact)
{
    log_debug("opening contact for link [*%p]", contact.object());

    SimLink* sl = (SimLink*)contact->link()->cl_info();
    ASSERT(sl);

    const ConnState* cs = Connectivity::instance()->
                          lookup(Node::active_node(), sl->peer_node_);
    if (cs != NULL && cs->open_) {
        log_debug("opening contact");
        if (sl->params_.set_remote_eid_) {
            contact->link()->set_remote_eid(sl->peer_node_->local_eid());
        }
        update_connectivity(Node::active_node(), sl->peer_node_, *cs);
        BundleDaemon::post(new ContactUpEvent(contact));

        // if there is a queued bundle on the link, start sending it
        if (! contact->link()->queue()->empty()) {
            sl->start_next_bundle();
        }

    } else {
        log_debug("connectivity is down when trying to open contact");
        BundleDaemon::post(
            new LinkStateChangeRequest(contact->link(),
                                       Link::CLOSED,
                                       ContactEvent::BROKEN));
    }

    return true;
}

//----------------------------------------------------------------------
void
SimConvergenceLayer::bundle_queued(const LinkRef& link, const BundleRef& bundle)
{
    (void)bundle;

    ASSERT(!link->isdeleted());
    ASSERT(link->cl_info() != NULL);

    log_debug("bundle_queued *%p on link *%p", bundle.object(), link.object());

    SimLink* sl = (SimLink*)link->cl_info();
    ASSERT(sl);

    if (link->isopen() && (sl->pending_inflight_ == NULL)) {
        sl->start_next_bundle();
    }
}

//----------------------------------------------------------------------
void
SimConvergenceLayer::update_connectivity(Node* n1, Node* n2, const ConnState& cs)
{
    ASSERT(n1 != NULL);
    ASSERT(n2 != NULL);

    n1->set_active();

    ContactManager* cm = n1->contactmgr();;

    oasys::ScopeLock l(cm->lock(), "SimConvergenceLayer::update_connectivity");
    const LinkSet* links = cm->links();

    for (LinkSet::iterator iter = links->begin();
         iter != links->end();
         ++iter)
    {
        LinkRef link = *iter;
        SimLink* sl = (SimLink*)link->cl_info();
        ASSERT(sl);

        // update the token bucket
        sl->tb_.set_rate(cs.bw_);

        if (sl->peer_node_ != n2)
            continue;

        log_debug("update_connectivity: checking node %s link %s",
                  n1->name(), link->name());

        if (cs.open_ == false && link->state() == Link::OPEN) {
            log_debug("update_connectivity: closing link %s", link->name());
            n1->post_event(
                new LinkStateChangeRequest(link, Link::CLOSED,
                                           ContactEvent::BROKEN));
        }
    }
}

} // namespace dtnsim


text:
import unittest

from apache_beam.metrics.cells import CellCommitState
from apache_beam.metrics.execution import MetricKey
from apache_beam.metrics.execution import MetricsContainer
from apache_beam.metrics.execution import MetricsEnvironment
from apache_beam.metrics.execution import ScopedMetricsContainer
from apache_beam.metrics.metric import Metrics
from apache_beam.metrics.metricbase import MetricName

class TestMetricsContainer(unittest.TestCase):
  def test_create_new_counter(self):
    mc = MetricsContainer('astep')
    self.assertFalse(mc.counters.has_key(MetricName('namespace', 'name')))
    mc.get_counter(MetricName('namespace', 'name'))
    self.assertTrue(mc.counters.has_key(MetricName('namespace', 'name')))

  def test_scoped_container(self):
    c1 = MetricsContainer('mystep')
    c2 = MetricsContainer('myinternalstep')
    with ScopedMetricsContainer(c1):
      self.assertEqual(c1, MetricsEnvironment.current_container())
      counter = Metrics.counter('ns', 'name')
      counter.inc(2)

      with ScopedMetricsContainer(c2):
        self.assertEqual(c2, MetricsEnvironment.current_container())
        counter = Metrics.counter('ns', 'name')
        counter.inc(3)
        self.assertEqual(
            c2.get_cumulative().counters.items(),
            [(MetricKey('myinternalstep', MetricName('ns', 'name')), 3)])

      self.assertEqual(c1, MetricsEnvironment.current_container())
      counter = Metrics.counter('ns', 'name')
      counter.inc(4)
      self.assertEqual(
          c1.get_cumulative().counters.items(),
          [(MetricKey('mystep', MetricName('ns', 'name')), 6)])

  def test_add_to_counter(self):
    mc = MetricsContainer('astep')
    counter = mc.get_counter(MetricName('namespace', 'name'))
    counter.inc()
    counter = mc.get_counter(MetricName('namespace', 'name'))
    self.assertEqual(counter.value, 1)

  def test_get_cumulative_or_updates(self):
    mc = MetricsContainer('astep')

    clean_values = []
    dirty_values = []
    for i in range(1, 11):
      counter = mc.get_counter(MetricName('namespace', 'name{}'.format(i)))
      distribution = mc.get_distribution(
          MetricName('namespace', 'name{}'.format(i)))
      counter.inc(i)
      distribution.update(i)
      if i % 2 == 0:
        # Some are left to be DIRTY (i.e. not yet committed).
        # Some are left to be CLEAN (i.e. already committed).
        dirty_values.append(i)
        continue
      # Assert: Counter/Distribution is DIRTY or COMMITTING (not CLEAN)
      self.assertEqual(distribution.commit.before_commit(), True)
      self.assertEqual(counter.commit.before_commit(), True)
      distribution.commit.after_commit()
      counter.commit.after_commit()
      # Assert: Counter/Distribution has been committed, therefore it's CLEAN
      self.assertEqual(counter.commit.state, CellCommitState.CLEAN)
      self.assertEqual(distribution.commit.state, CellCommitState.CLEAN)
      clean_values.append(i)

    # Retrieve NON-COMMITTED updates.
    logical = mc.get_updates()
    self.assertEqual(len(logical.counters), 5)
    self.assertEqual(len(logical.distributions), 5)
    self.assertEqual(set(dirty_values),
                     set([v for _, v in logical.counters.items()]))
    # Retrieve ALL updates.
    cumulative = mc.get_cumulative()
    self.assertEqual(len(cumulative.counters), 10)
    self.assertEqual(len(cumulative.distributions), 10)
    self.assertEqual(set(dirty_values + clean_values),
                     set([v for _, v in cumulative.counters.items()]))

class TestMetricsEnvironment(unittest.TestCase):
  def test_uses_right_container(self):
    c1 = MetricsContainer('step1')
    c2 = MetricsContainer('step2')
    counter = Metrics.counter('ns', 'name')
    MetricsEnvironment.set_current_container(c1)
    counter.inc()
    MetricsEnvironment.set_current_container(c2)
    counter.inc(3)
    MetricsEnvironment.unset_current_container()

    self.assertEqual(
        c1.get_cumulative().counters.items(),
        [(MetricKey('step1', MetricName('ns', 'name')), 1)])

    self.assertEqual(
        c2.get_cumulative().counters.items(),
        [(MetricKey('step2', MetricName('ns', 'name')), 3)])

  def test_no_container(self):
    self.assertEqual(MetricsEnvironment.current_container(),
                     None)

if __name__ == '__main__':
  unittest.main()

redpajama_set_name: RedPajamaGithub


text:
namespace swift {

class BeginAccessInst;
class LoadBorrowInst;
class SILValue;
class Operand;

namespace silverifier {

class LoadBorrowImmutabilityAnalysis {
  SmallMultiMapCache<AccessPath, Operand *> cache;
  DeadEndBlocks &deadEndBlocks;

public:
  LoadBorrowImmutabilityAnalysis(DeadEndBlocks &deadEndBlocks,
                                 const SILFunction *f);

  /// Returns true if exhaustively lbi is guaranteed to never be invalidated by
  /// local writes.
  bool isImmutable(LoadBorrowInst *lbi);

private:
  bool isImmutableInScope(LoadBorrowInst *lbi,
                          AccessPathWithBase accessPathWithBase);
};

} // namespace silverifier
} // namespace swift

#endif


text:
document.writeln("<!DOCTYPE html>");
document.writeln("");
document.writeln("	");
document.writeln("		<meta charset=\"utf-8\">");
document.writeln("		<title>关于我们</title>");
document.writeln("		<link rel=\"stylesheet\" href=\"../css/public.css\" />");
document.writeln("		");
document.writeln("		");
document.writeln("	");
document.writeln("	");
document.writeln("
");
document.writeln("			");
document.writeln("
");
document.writeln("
");
document.writeln("
公司简介
");
document.writeln("
创始团队
");
document.writeln("
合作伙伴
");
document.writeln("
网站公告
");
document.writeln("
行业新闻
");
//document.writeln("
资费说明
");
document.writeln("
招贤纳士
");
document.writeln("
联系我们
");
document.writeln("
");
document.writeln("
");
document.writeln("
");
document.writeln("	");
document.writeln("");
$(function(){

	if(!BASE.versions().mobile){
		leftMenuFloat();
	};
	function leftMenuFloat(){
		var styleNode = document.createElement("style");
		var timeOut;
		styleNode.innerHTML = "#about_menu .toin_left_menu .float{position: fixed;top: 50px;background: #faf9f3;z-index:0} .footer{position: relative;} #zb_footer{position: relative;}";
		document.getElementsByTagName("body")[0].appendChild(styleNode);

		$(window).scroll(function(e){
		    if($(this).scrollTop() > 130){
	        	$(".toin_left_menu ul").addClass("float");
	        }else{
	        	$(".toin_left_menu ul").removeClass("float");
	        };
		});
	}

})


text:
package com.michalsadel.service.mappers;

import io.swagger.annotations.*;

import javax.validation.constraints.*;

@ApiModel
public class PasswordDefinition {
    private String oldPassword;
    @NotNull
    private String newPassword;

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }
}


text:
pub mod cstore;
pub mod csearch;


text:
(function () {
  'use strict';

  angular.module('exceptionless.stack-dialog', [
    'ui.bootstrap',

    'dialogs.main',

    'exceptionless.autofocus',
    'exceptionless.semver',
    'exceptionless.validators'
  ]);
}());


text:
namespace MayBee.Serialization.JsonNet
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    using Newtonsoft.Json;

    public class MaybeAsNullableConverter : JsonConverter
    {
        private static readonly Type _markerType = typeof(IMaybe);

        private static readonly MethodInfo _emptyCreatorMethod = typeof(Maybe).GetTypeInfo().GetDeclaredMethod("Empty");
        private static readonly MethodInfo _existingCreatorMethod = typeof(Maybe).GetTypeInfo().GetDeclaredMethod("Is");

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var maybe = (IMaybe)value;

            if (maybe.Exists)
            {
                var innerValue = maybe.GetType().GetTypeInfo().GetDeclaredProperty("It").GetValue(maybe);
                serializer.Serialize(writer, innerValue);
            }
            else
            {
                writer.WriteNull();
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var innerMaybeType = objectType.GenericTypeArguments.Single();

            // For value types, we must deserialize into the nullable variant, otherwise deserializing 'null' will fail
            var deserializationType = innerMaybeType.IsValueType
                ? typeof(Nullable<>).MakeGenericType(innerMaybeType)
                : innerMaybeType;

            var innerValue = serializer.Deserialize(reader, deserializationType);

            return innerValue == null
                ? _emptyCreatorMethod.MakeGenericMethod(innerMaybeType).Invoke(null, new object[] { })
                : _existingCreatorMethod.MakeGenericMethod(innerMaybeType).Invoke(null, new[] { innerValue });
        }

        public override bool CanConvert(Type objectType)
        {
            return _markerType.GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
    }
}


text:
package bosphorus;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;
import com.dyuproject.protostuff.Schema;

public final class CDURATION implements Externalizable, Message<CDURATION>, Schema<CDURATION>
{

    public static Schema<CDURATION> getSchema()
    {
        return DEFAULT_INSTANCE;
    }

    public static CDURATION getDefaultInstance()
    {
        return DEFAULT_INSTANCE;
    }

    static final CDURATION DEFAULT_INSTANCE = new CDURATION();

    private String pattern;
    private IntervalOfDuration range;
    private String assumedvalue;

    public CDURATION()
    {

    }

    // getters and setters

    // pattern

    public String getPattern()
    {
        return pattern;
    }

    public void setPattern(String pattern)
    {
        this.pattern = pattern;
    }

    // range

    public IntervalOfDuration getRange()
    {
        return range;
    }

    public void setRange(IntervalOfDuration range)
    {
        this.range = range;
    }

    // assumedvalue

    public String getAssumedvalue()
    {
        return assumedvalue;
    }

    public void setAssumedvalue(String assumedvalue)
    {
        this.assumedvalue = assumedvalue;
    }

    // java serialization

    public void readExternal(ObjectInput in) throws IOException
    {
        GraphIOUtil.mergeDelimitedFrom(in, this, this);
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        GraphIOUtil.writeDelimitedTo(out, this, this);
    }

    // message method

    public Schema<CDURATION> cachedSchema()
    {
        return this;
    }

    // schema methods

    public CDURATION newMessage()
    {
        return new CDURATION();
    }

    public Class<CDURATION> typeClass()
    {
        return CDURATION.class;
    }

    public String messageName()
    {
        return CDURATION.class.getSimpleName();
    }

    public String messageFullName()
    {
        return CDURATION.class.getName();
    }

    public boolean isInitialized(CDURATION message)
    {
        return true;
    }

    public void mergeFrom(Input input, CDURATION message) throws IOException
    {
        for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
        {
            switch(number)
            {
                case 0:
                    return;
                case 1:
                    message.pattern = input.readString();
                    break;
                case 2:
                    message.range = input.mergeObject(message.range, IntervalOfDuration.getSchema());
                    break;

                case 3:
                    message.assumedvalue = input.readString();
                    break;
                default:
                    input.handleUnknownField(number, this);
            }
        }
    }

    public void writeTo(Output output, CDURATION message) throws IOException
    {
        if(message.pattern != null)
            output.writeString(1, message.pattern, false);

        if(message.range != null)
             output.writeObject(2, message.range, IntervalOfDuration.getSchema(), false);

        if(message.assumedvalue != null)
            output.writeString(3, message.assumedvalue, false);
    }

    public String getFieldName(int number)
    {
        return Integer.toString(number);
    }

    public int getFieldNumber(String name)
    {
        return Integer.parseInt(name);
    }

}


text:
package org.java_websocket.framing;

import java.nio.ByteBuffer;

import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.exceptions.InvalidFrameException;
import org.java_websocket.util.Charsetfunctions;

public class CloseFrameBuilder extends FramedataImpl1 implements CloseFrame
{

    public CloseFrameBuilder()
    {
        super(Opcode.CLOSING);
        setFin(true);
    }

    public CloseFrameBuilder(int code) throws InvalidDataException
    {
        super(Opcode.CLOSING);
        setFin(true);
        setCodeAndMessage(code, "");
    }

    public CloseFrameBuilder(int code, String m) throws InvalidDataException
    {
        super(Opcode.CLOSING);
        setFin(true);
        setCodeAndMessage(code, m);
    }

    static final ByteBuffer emptybytebuffer = ByteBuffer.allocate(0);

    private int             code;

    private String          reason;

    private void initCloseCode() throws InvalidFrameException
    {
        code = CloseFrame.NOCODE;
        ByteBuffer payload = super.getPayloadData();
        payload.mark();
        if (payload.remaining() >= 2)
        {
            ByteBuffer bb = ByteBuffer.allocate(4);
            bb.position(2);
            bb.putShort(payload.getShort());
            bb.position(0);
            code = bb.getInt();

            if (code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR || code == CloseFrame.NOCODE
                || code > 4999 || code < 1000 || code == 1004)
            {
                throw new InvalidFrameException("closecode must not be sent over the wire: " + code);
            }
        }
        payload.reset();
    }

    private void initMessage() throws InvalidDataException
    {
        if (code == CloseFrame.NOCODE)
        {
            reason = Charsetfunctions.stringUtf8(super.getPayloadData());
        }
        else
        {
            ByteBuffer b = super.getPayloadData();
            int mark = b.position();// because stringUtf8 also creates a mark
            try
            {
                b.position(b.position() + 2);
                reason = Charsetfunctions.stringUtf8(b);
            }
            catch (IllegalArgumentException e)
            {
                throw new InvalidFrameException(e);
            }
            finally
            {
                b.position(mark);
            }
        }
    }

    private void setCodeAndMessage(int code, String m) throws InvalidDataException
    {
        if (m == null)
        {
            m = "";
        }
        // CloseFrame.TLS_ERROR is not allowed to be transfered over the wire
        if (code == CloseFrame.TLS_ERROR)
        {
            code = CloseFrame.NOCODE;
            m = "";
        }
        if (code == CloseFrame.NOCODE)
        {
            if (0 < m.length())
            {
                throw new InvalidDataException(PROTOCOL_ERROR,
                    "A close frame must have a closecode if it has a reason");
            }
            return;// empty payload
        }

        byte[] by = Charsetfunctions.utf8Bytes(m);
        ByteBuffer buf = ByteBuffer.allocate(4);
        buf.putInt(code);
        buf.position(2);
        ByteBuffer pay = ByteBuffer.allocate(2 + by.length);
        pay.put(buf);
        pay.put(by);
        pay.rewind();
        setPayload(pay);
    }

    @Override
    public int getCloseCode()
    {
        return code;
    }

    @Override
    public String getMessage()
    {
        return reason;
    }

    @Override
    public ByteBuffer getPayloadData()
    {
        if (code == NOCODE)
        {
            return emptybytebuffer;
        }
        return super.getPayloadData();
    }

    @Override
    public void setPayload(ByteBuffer payload) throws InvalidDataException
    {
        super.setPayload(payload);
        initCloseCode();
        initMessage();
    }

    @Override
    public String toString()
    {
        return super.toString() + "code: " + code;
    }

}


text:
#include "ProxyMcReply.h"

#include "mcrouter/lib/McReply.h"

namespace facebook { namespace memcache { namespace mcrouter {

ProxyMcReply::ProxyMcReply(McReplyBase reply)
  : McReplyBase(std::move(reply)) {}

void ProxyMcReply::setDestination(
    std::shared_ptr<const ProxyClientCommon> dest) {
  dest_ = std::move(dest);
}

std::shared_ptr<const ProxyClientCommon> ProxyMcReply::getDestination() const {
  return dest_;
}

McReply ProxyMcReply::moveToMcReply(ProxyMcReply&& proxyMcReply) {
  return McReply(std::move(*static_cast<McReplyBase*>(&proxyMcReply)));
}

}}}


text:
package io;

import java.util.Formatter;

/** Demonstrate some usage patterns and format-code examples
 * of the Formatter class and PrintStream/PrintWriter
 * printf() methods introduced way back in Java 5.
 */
// BEGIN main
public class FormatterDemo {
    public static void main(String[] args) {

        // The arguments to all these format methods consist of
        // a format code String and 1 or more arguments.
        // Each format code consists of the following:
        // % - code lead-in
        // N$ - which parameter number (1-based) after the code - OPTIONAL
        // N - field width
        // L - format letter (d: decimal(int); f: float; s: general; many more)
        // For the full(!) story, see javadoc for java.util.Formatter.

        // Most general (cumbersome) way of proceding.
        Formatter fmtr = new Formatter();
        Object result = fmtr.format("%1$04d - the year of %2$f", 1956, Math.PI);
        System.out.println(result);

        // Shorter way using static String.format(), and
        // default parameter numbering.
        Object stringResult = String.format("%04d - the year of %f", 1956, Math.PI);
        System.out.println(stringResult);

        // A shorter way using PrintStream/PrintWriter.format, more in line with
        // other languages. But this way you must provide the newline delimiter
        // using %n (do NOT use \n as that is platform-dependent!).
        System.out.printf("%04d - the year of %f%n", 1956, Math.PI);

        // Format doubles with more control
        System.out.printf("PI is approximately %4.2f%n", Math.PI);
    }
}
// END main


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Plenom.Components.Busylight.Sdk;

namespace RecordingLight
{
  public partial class frmMain : Form
  {
    private BusylightLyncController device;
    private bool die;

    public frmMain()
    {
      InitializeComponent();
      device = new BusylightLyncController();
      if (!device.IsDeviceAttached())
      {
        MessageBox.Show("You don't have a Busylight connected, or I can't see it");
      }
    }

    private void Pulse(BusylightColor color, int delayInMiliseconds = 50)
    {
      if (delayInMiliseconds < 30) delayInMiliseconds = 30;

      die = false;
      int holdblue = color.BlueRgbValue;
      int holdred = color.RedRgbValue;
      int holdgreen = color.GreenRgbValue;

      while (true)
      {
        color.BlueRgbValue -= 10;
        color.RedRgbValue -= 10;
        color.GreenRgbValue -= 10;

        if (color.BlueRgbValue < 0)
          color.BlueRgbValue = holdblue;
        if (color.RedRgbValue < 0)
          color.RedRgbValue = holdred;
        if (color.GreenRgbValue < 0)
          color.GreenRgbValue = holdgreen;

        device.Light(color);
        System.Threading.Thread.Sleep(delayInMiliseconds);
        Application.DoEvents();
        if (die) break;
      }
      device.Light(BusylightColor.Yellow);
    }

    private void Pulse(List<BusylightColor> colors, int delayInMiliseconds = 50)
    {
      if (delayInMiliseconds < 30) delayInMiliseconds = 30;

      die = false;
      while (true)
      {
        foreach (BusylightColor color in colors)
        {
          device.Light(color);
          System.Threading.Thread.Sleep(delayInMiliseconds);

          Application.DoEvents();
          if (die) break;
        }
        if (die) break;
      }
      device.Light(BusylightColor.Yellow);
    }

    private void btnAlert_Click(object sender, EventArgs e)
    {
      //Pulse(BusylightColor.Green);
      //Pulse(new BusylightColor{RedRgbValue = 20, GreenRgbValue = 100, BlueRgbValue = 30});
      List<BusylightColor> colors = new List<BusylightColor> { BusylightColor.Red, BusylightColor.Off, BusylightColor.Blue, BusylightColor.Off };
      Pulse(colors, 500);
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //device.Light(BusylightColor.Off);
      //device.StopKeepAliveSignaling();
      die = true;
    }
  }
}


text:
package com.c0demattari.bluetoothEnabler;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class BluetoothEnabler extends CordovaPlugin {

        @Override
        public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {

                BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
                if (action.equals("checkEnabled")) {
                        if (btAdapter.isEnabled()) {
                                callbackContext.success();
                        } else {
                                callbackContext.error("Bluetooth is disabled.");
                        }
                        return true;
                }
                return false;
        }

}


text:
module StickyHeaderApp {
    var fastInvalidate = true;

    function h(tag: string, ...args: any[]): IBobrilNode {
        return { tag: tag, children: args };
    }

    function hs(tag: string, style: any, ...args: any[]): IBobrilNode {
        return { tag: tag, style: style, children: args };
    }

    interface IOnChangeData {
        onChange: (value: any) => void;
    }

    interface IOnChangeCtx {
        data: IOnChangeData;
    }

    var OnChangeComponent: IBobrilComponent = {
        onChange(ctx: IOnChangeCtx, v: any): void {
            ctx.data.onChange(v);
        }
    }

    function checkbox(value: boolean, onChange: (value: boolean) => void): IBobrilNode {
        return { tag: "input", attrs: { type: "checkbox", value: value }, data: { onChange: onChange }, component: OnChangeComponent };
    }

    function smallbutton(onAction: () => void, content: any): IBobrilNode {
        return {
            tag: "button", style: { width: "2em", height: "2em" }, component: {
                onClick() { onAction(); return true; }
            }, children: content
        };
    }
    function pxinput(value: number, onChange: (value: number) => void): IBobrilNode {
        return {
            tag: "span", children: [
                smallbutton(() => { onChange(value - 1); }, "-"),
                " " + value + "px ",
                smallbutton(() => { onChange(value + 1); }, "+")
            ]
        };
    }

    function getOffset(element: HTMLElement): [number, number] {
        var box = element.getBoundingClientRect();
        var docElem = document.documentElement;
        var winScroll = b.getWindowScroll();
        return [
            box.left + winScroll[0] - docElem.clientLeft,
            box.top + winScroll[1] - docElem.clientTop
        ];
    }

    function getHeight(element: HTMLElement): number {
        return element.scrollHeight;
    }

    function stickyUpdateDomFix(ctx: any, me: IBobrilNode, element: HTMLElement) {
        var scrollableArea = element.parentElement;
        while (scrollableArea && !b.isScrollable(scrollableArea)[1]) scrollableArea = scrollableArea.parentElement;
        var isWindowScrolling = scrollableArea === document.documentElement || scrollableArea == null;
        var c: any = ctx;
        var tableElement = element;
        var origHeader = <HTMLElement>tableElement.firstChild;
        var newTopOffset = isWindowScrolling ? 0 : getOffset(scrollableArea)[1];
        var offset = getOffset(tableElement);
        var winScroll = b.getWindowScroll();
        var scrollTop = winScroll[1] + newTopOffset;
        var scrollLeft = winScroll[0];

        var scrolledPastTop = (isWindowScrolling ? scrollTop : newTopOffset) > offset[1];
        // twice header height for better UX
        var notScrolledPastBottom = (isWindowScrolling ? scrollTop : 0) <
            (offset[1] + getHeight(tableElement) - 2 * getHeight(origHeader) - newTopOffset);
        if (c.sticky !== (scrolledPastTop && notScrolledPastBottom)) {
            c.sticky = !c.sticky;
            if (fastInvalidate)
                b.invalidate(ctx, 1);
            else
                b.invalidate();
            return;
        }
        if (c.lastSticky) {
            var fixElement = <HTMLElement>tableElement.childNodes[1];
            var fixElementStyle = fixElement.style;
            var newLeft = offset[0] - scrollLeft + c.deltaCorr;
            var newTop = newTopOffset - (isWindowScrolling ? 0 : winScroll[1]);
            fixElementStyle.left = newLeft + "px";
            fixElementStyle.top = newTop + "px";
            if (fixElement.firstChild) {
                var l1 = (<HTMLElement>fixElement.firstChild).getBoundingClientRect().left;
                var l2 = (<HTMLElement>origHeader.firstChild).getBoundingClientRect().left;
                var dif = l2 - l1;
                c.deltaCorr += dif;
                if (Math.abs(dif) > 0.1) {
                    newLeft = offset[0] - scrollLeft + c.deltaCorr;
                    fixElementStyle.left = newLeft + "px";
                }
            }
        }
    }

    var StickyHeaderFixedComp: IBobrilComponent = {
        render(ctx: any, me: IBobrilNode) {
            me.style = me.style || {};
            me.style.position = "fixed";
            me.style.marginTop = "0px";
            me.style.zIndex = "3";
            me.style.left = "0";
            me.style.top = "0";
        }
    }

    function cloneObj<T>(o: T): T {
        return <T>b.assign({}, o);
    }

    var StickyTableFixComp: IBobrilComponent = {
        id: "StickyTableFix",
        init(ctx: any) {
            ctx.onScroll = () => {
                if (fastInvalidate) {
                    b.invalidate(ctx, 0);
                } else {
                    b.invalidate();
                }
            }
            ctx.sticky = false;
            ctx.deltaCorr = 0;
        },
        render(ctx: any, me: IBobrilNode) {
            var header: IBobrilNode = ctx.data.header;
            me.tag = "table";
            me.style = ctx.data.style;
            ctx.lastSticky = ctx.sticky;
            ctx.borderCollapse = ctx.data.borderCollapse;
            if (ctx.sticky) {
                var clone = b.cloneNode(header);
                b.postEnhance(clone, StickyHeaderFixedComp);
                clone.key = "StickyH";
                me.children = [header, clone, ctx.data.body];
            } else {
                me.children = [header, ctx.data.body];
            }
        },
        postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
            b.addOnScroll(ctx.onScroll);
            stickyUpdateDomFix(ctx, me, element);
        },
        postUpdateDom(ctx: any, me: IBobrilCacheNode, element: HTMLElement) {
            stickyUpdateDomFix(ctx, me, element);
            if (!ctx.lastSticky) return;
            var origEl = element.firstChild;
            var cloEl = origEl.nextSibling;
            var ieWeirdness = b.ieVersion() <= 9;
            for (var i = 0, l = origEl.childNodes.length; i < l; i++) {
                var w: number;
                var origElc = <HTMLElement>origEl.childNodes[i];
                if (ieWeirdness) {
                    // w = origElc.offsetWidth; this does not work correctly in IE9
                    var clientRect = origElc.getBoundingClientRect();
                    w = clientRect.right - clientRect.left;
                } else {
                    var computedStyle = window.getComputedStyle(origElc, null);
                    if (computedStyle.boxSizing === "border-box") {
                        w = origElc.offsetWidth;
                    } else {
                        w = parseFloat(computedStyle.width);
                    }
                }
                var s = (<HTMLElement>cloEl.childNodes[i]).style;
                var w2 = w + "px";
                s.minWidth = w2;
                s.maxWidth = w2;
                if (ieWeirdness) {
                    s.boxSizing = "border-box";
                }
            }
        },
        destroy(ctx: any, me: IBobrilNode, element: HTMLElement) {
            b.removeOnScroll(ctx.onScroll);
        }
    };

    function stickyTableFix(borderCollapse: boolean, style: any, header: IBobrilNode, body: any): IBobrilNode {
        style = cloneObj(style);
        style.borderCollapse = (borderCollapse ? "collapse" : "separate");
        return { data: { style: style, borderCollapse: borderCollapse, header: header, body: body }, component: StickyTableFixComp };
    }

    function stickyUpdateDomAbs(ctx: any, me: IBobrilNode, element: HTMLElement) {
        var scrollableArea = element.parentElement;
        while (scrollableArea && !b.isScrollable(scrollableArea)[1]) scrollableArea = scrollableArea.parentElement;
        var isWindowScrolling = scrollableArea === document.documentElement || scrollableArea == null;
        var c: any = ctx;
        var tableElement = <HTMLElement>element.firstChild;
        var origHeader = <HTMLElement>tableElement.firstChild;
        var newTopOffset = isWindowScrolling ? 0 : getOffset(scrollableArea)[1];
        var offset = getOffset(tableElement);
        var winScroll = b.getWindowScroll();
        var scrollTop = winScroll[1] + newTopOffset;
        var scrolledPastTop = (isWindowScrolling ? scrollTop : newTopOffset) > offset[1];
        // twice header height for better UX
        var notScrolledPastBottom = (isWindowScrolling ? scrollTop : 0) <
            (offset[1] + getHeight(tableElement) - 2 * getHeight(origHeader) - newTopOffset);
        var absElement = <HTMLElement>element.childNodes[1];
        var absElementStyle = absElement.style;
        if (scrolledPastTop && notScrolledPastBottom) {
            if (absElementStyle.visibility !== "visible")
                absElementStyle.visibility = "visible";
            var newTop = (isWindowScrolling ? winScroll[1] : newTopOffset) - offset[1];
            absElementStyle.left = c.deltaCorr + "px";
            absElementStyle.top = newTop + "px";
            var absHeader = <HTMLElement>ctx.refs["header"].element.firstChild;
            if (origHeader.firstChild) {
                var l1 = (<HTMLElement>absHeader.firstChild).getBoundingClientRect().left;
                var l2 = (<HTMLElement>origHeader.firstChild).getBoundingClientRect().left;
                var dif = l2 - l1;
                c.deltaCorr += dif;
                if (Math.abs(dif) > 0.1) {
                    absElementStyle.left = c.deltaCorr + "px";
                }
                var ieWeirdness = b.ieVersion() <= 9;
                for (var i = 0, l = origHeader.childNodes.length; i < l; i++) {
                    var w: number;
                    var origElc = <HTMLElement>origHeader.childNodes[i];
                    if (ieWeirdness) {
                        // w = origElc.offsetWidth; this does not work correctly in IE9
                        var clientRect = origElc.getBoundingClientRect();
                        w = clientRect.right - clientRect.left;
                    } else {
                        var computedStyle = window.getComputedStyle(origElc, null);
                        if (computedStyle.boxSizing === "border-box") {
                            w = origElc.offsetWidth;
                        } else {
                            w = parseFloat(computedStyle.width);
                        }
                    }
                    var s = (<HTMLElement>absHeader.childNodes[i]).style;
                    var w2 = w + "px";
                    if (s.minWidth !== w2 || s.maxWidth !== w2)
                    {
                        s.minWidth = w2;
                        s.maxWidth = w2;
                    }
                    if (ieWeirdness) {
                        if (s.boxSizing !== "border-box")
                            s.boxSizing = "border-box";
                    }
                }
            }
        } else {
            if (absElementStyle.visibility !== "hidden")
                absElementStyle.visibility = "hidden";
        }
    }

    var StickyTableAbsComp: IBobrilComponent = {
        id: "StickyTableAbs",
        init(ctx: any) {
            ctx.deltaCorr = 0;
            ctx.onScroll = () => {
                if (fastInvalidate) {
                    b.invalidate(ctx, 0);
                } else {
                    b.invalidate();
                }
            }
        },
        render(ctx: any, me: IBobrilNode) {
            var header: IBobrilNode = ctx.data.header;
            var headerClone = b.cloneNode(header);
            var styleClone = cloneObj(ctx.data.style);
            styleClone.border = "none";
            me.tag = "div";
            me.style = ctx.data.style;
            me.children = [
                {
                    tag: "table", attrs: me.attrs, className: me.className, style: me.style, children: [
                        header,
                        ctx.data.body
                    ]
                },
                {
                    tag: "div",
                    style: { visibility: "hidden", position: "absolute" },
                    children: {
                        tag: "table",
                        ref: [ctx, "header"],
                        className: me.className,
                        attrs: me.attrs,
                        style: styleClone,
                        children: headerClone
                    }
                }
            ];
            me.attrs = undefined;
            me.className = undefined;
            me.style = { position: "relative" }
        },
        postInitDom(ctx: any, me: IBobrilNode, element: HTMLElement) {
            b.addOnScroll(ctx.onScroll);
            stickyUpdateDomAbs(ctx, me, element);
        },
        postUpdateDom(ctx: any, me: IBobrilCacheNode, element: HTMLElement) {
            stickyUpdateDomAbs(ctx, me, element);
        },
        destroy(ctx: any, me: IBobrilNode, element: HTMLElement) {
            b.removeOnScroll(ctx.onScroll);
        }
    };

    function stickyTableAbs(borderCollapse: boolean, style: any, header: IBobrilNode, body: any): IBobrilNode {
        style = cloneObj(style);
        style.borderCollapse = (borderCollapse ? "collapse" : "separate");
        return { data: { style: style, header: header, body: body }, component: StickyTableAbsComp };
    }

    function headerCell(content: string): IBobrilNode {
        return hs("th", { backgroundColor: "#ffc", border: "1px solid #300" }, content);
    }

    function bodyCell(content: string): IBobrilNode {
        return hs("td", { border: "1px solid #600" }, content);
    }

    function range(from: number, to: number) {
        var res: number[] = [];
        for (var i = from; i <= to; i++) {
            res.push(i);
        }
        return res;
    }

    var cols = 20;
    var borderSpacing = 5;
    var borderCollapse = false;
    var implStrategyAbs = true;
    b.init(() => {
        function rows() {
            return range(1, 100).map(i => {
                return h("tr", range(1, cols).map(j => bodyCell("Cell " + j + "/" + i)));
            });
        }

        var stickyTable = implStrategyAbs ? stickyTableAbs : stickyTableFix;
        return [
            h("h1", "Sticky Header Bobril sample"),
            h("p", "Frame: " + b.frame() + " Duration Last: " + b.lastFrameDuration()),
            hs("div", { paddingBottom: 10 }, h("label", checkbox(fastInvalidate, v=> {
                fastInvalidate = v;
                b.invalidate();
            }), "Fast Invalidate")),
            hs("div", { paddingBottom: 10 }, h("label", checkbox(implStrategyAbs, v=> {
                implStrategyAbs = v;
                b.invalidate();
            }), "Absolute Positioning")),
            hs("div", { paddingBottom: 10 }, h("label", checkbox(borderCollapse, v=> {
                borderCollapse = v;
                b.invalidate();
            }), "Collapse borders")),
            " Border Spacing: ", pxinput(borderSpacing, (v) => {
                borderSpacing = v;
                b.invalidate();
            }),
            {
                tag: "div",
                style: { height: "150px", width: "300px", overflow: "auto" },
                children: [
                    h("p", "Before table"),
                    stickyTable(borderCollapse, { borderSpacing: borderSpacing + "px", border: "1px solid #000" }, h("tr", range(1, cols).map(j => headerCell("Header " + j))), rows()),
                    h("p", "Some text after table"),
                    range(1, 10).map(i=> h("p", "" + i))
                ]
            },
            stickyTable(borderCollapse, { borderSpacing: borderSpacing + "px", border: "1px solid #000" }, h("tr", range(1, cols).map(j=> headerCell("Header " + j))), rows()),
            h("p", "Some text after table"),
            range(1, 30).map(i=> h("p", "" + i))
        ];
    });
}


text:
layout: page
title: Helix Light Industries Show
date: 2016-05-24
author: Catherine Foley
tags: weekly links, java
status: published
summary: Ut hendrerit aliquet aliquet. Praesent at auctor dolor.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 08/30/2016
  endDate: 09/03/2016
  ctyhocn: DNCHHHX
  groupCode: HLIS
published: true
---
Morbi auctor, leo id eleifend mattis, nibh lorem mattis augue, quis eleifend nunc quam at lectus. Nam rutrum semper scelerisque. Mauris vitae orci augue. Donec rutrum lorem magna, at imperdiet felis maximus quis. Aliquam consectetur sapien pulvinar, suscipit ipsum ut, hendrerit neque. Donec fermentum est eget dignissim blandit. Fusce eu accumsan metus. Curabitur condimentum nunc ut elit porttitor, eget ultricies risus blandit.

* In posuere arcu vitae mi malesuada cursus
* Curabitur iaculis mauris ut mauris accumsan faucibus
* Sed ut velit non enim sodales dignissim nec egestas velit
* Fusce pharetra augue et rutrum volutpat
* Quisque sed erat hendrerit, cursus orci in, fermentum nisl.

Duis ultrices ac dolor at viverra. In condimentum volutpat ante, non rhoncus metus dapibus ac. Donec venenatis pellentesque congue. Proin vel auctor ipsum, sit amet scelerisque urna. Curabitur sed suscipit massa, vel consectetur lorem. Ut ornare elementum ante id lobortis. Nunc ut ullamcorper risus, a iaculis velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet metus efficitur, molestie felis in, sollicitudin dolor. Nulla commodo ac elit et commodo. Aenean condimentum condimentum neque, id semper mauris aliquet ut. Nam tristique aliquet ipsum, vehicula viverra augue. Mauris a est id metus pellentesque suscipit id id dolor.


text:
package org.jiemamy.utils.gtree.example;

import java.util.Map;

/**
 * モデルルート。
 * @version $Date$
 * @author Suguru ARAKAWA
 */
public interface Root {

	/**
	 * @return テーブル一覧
	 */
	Map<String, Table> getTables();

}


text:
<?php

namespace CSUNMetaLab\SwordUploader\Exceptions;

use Exception;

class CannotCreatePackageException extends Exception
{
	public function __construct($message="An error occurred during package creation") {
		parent::__construct($message);
	}
}


text:
define([
    'bluebird',
    './exceptions'
], function (
    Promise,
    exceptions
) {
    'use strict';

    function post(options) {
        const timeout = options.timeout || 60000;
        const startTime = new Date();

        return new Promise((resolve, reject, onCancel) => {
            const xhr = new XMLHttpRequest();
            xhr.onload = () => {
                if (xhr.status >= 300 && xhr.status < 400) {
                    reject(new exceptions.RedirectError(xhr.status, xhr.statusText, xhr));
                } else if (xhr.status >= 400 && xhr.status < 500) {
                    reject(new exceptions.ClientError(xhr.status, xhr.statusText, xhr));
                } else if (xhr.status >= 500) {
                    reject(new exceptions.ServerError(xhr.status, xhr.statusText, xhr));
                } else {
                    // var buf = new Uint8Array(xhr.response);
                    try {
                        resolve(xhr.response);
                    } catch (ex) {
                        reject(ex);
                    }
                }
            };
            xhr.ontimeout = () => {
                const elapsed = (new Date()) - startTime;
                reject(new exceptions.TimeoutError(timeout, elapsed, 'Request timeout', xhr));
            };
            xhr.onerror = () => {
                reject(new exceptions.ConnectionError('Request signaled error', xhr));
            };
            xhr.onabort = () => {
                reject(new exceptions.AbortError('Request was aborted', xhr));
            };

            if (onCancel) {
                onCancel(() => {
                    xhr.abort();
                });
            }

            if (options.responseType) {
                xhr.responseType = options.responseType;
            }
            try {
                xhr.open('POST', options.url, true);
            } catch (ex) {
                reject(new exceptions.GeneralError('Error opening request', xhr));
            }

            try {
                xhr.timeout = options.timeout || 60000;
                if (options.header) {
                    Object.keys(options.header).forEach((key) => {
                        xhr.setRequestHeader(key, options.header[key]);
                    });
                }
                xhr.withCredentials = options.withCredentials || false;

                // We support two types of data to send ... strings or int (byte) buffers
                if (typeof options.data === 'string') {
                    xhr.send(options.data);
                } else if (options.data instanceof Array) {
                    xhr.send(new Uint8Array(options.data));
                } else {
                    reject(new Error('Invalid type of data to send'));
                }
            } catch (ex) {
                reject(new exceptions.GeneralError('Error sending data in request', xhr));
            }
        });
    }

    function get(options) {
        const timeout = options.timeout || 60000;
        const startTime = new Date();

        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onload = () => {
                if (xhr.status >= 400 && xhr.status < 500) {
                    reject(new exceptions.ClientError(xhr.status, xhr.statusText, xhr));
                }
                if (xhr.status >= 500) {
                    reject(new exceptions.ServerError(xhr.status, xhr.statusText, xhr));
                }
                if (xhr.status >= 300 && xhr.status < 400) {
                    reject(new Error('Redirects not currently supported'));
                }
                // var buf = new Uint8Array(xhr.response);
                try {
                    resolve(xhr.response);
                } catch (ex) {
                    reject(ex);
                }
            };

            xhr.ontimeout = () => {
                const elapsed = (new Date()) - startTime;
                reject(new exceptions.TimeoutError(timeout, elapsed, 'Request timeout', xhr));
            };
            xhr.onerror = () => {
                reject(new exceptions.ConnectionError('General request error', xhr));
            };
            xhr.onabort = () => {
                reject(new exceptions.AbortError('Request was aborted', xhr));
            };

            if (options.responseType) {
                xhr.responseType = options.responseType;
            }
            try {
                xhr.open('GET', options.url, true);
            } catch (ex) {
                reject(new exceptions.GeneralError('Error opening request', xhr));
            }

            try {
                xhr.timeout = options.timeout || 60000;

                if (options.header) {
                    Object.keys(options.header).forEach((key) => {
                        xhr.setRequestHeader(key, options.header[key]);
                    });
                }
                xhr.withCredentials = options.withCredentials || false;

                // We support two types of data to send ... strings or int (byte) buffers
                xhr.send();
            } catch (ex) {
                reject(new exceptions.GeneralError('Error sending data in request', xhr));
            }
        });
    }

    return {
        get: get,
        post: post
    };
});


text:
'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var Map = require('./es6.map'),
    $export = require('./_export'),
    shared = require('./_shared')('metadata'),
    store = shared.store || (shared.store = new (require('./es6.weak-map'))());

var getOrCreateMetadataMap = function getOrCreateMetadataMap(target, targetKey, create) {
  var targetMetadata = store.get(target);
  if (!targetMetadata) {
    if (!create) return undefined;
    store.set(target, targetMetadata = new Map());
  }
  var keyMetadata = targetMetadata.get(targetKey);
  if (!keyMetadata) {
    if (!create) return undefined;
    targetMetadata.set(targetKey, keyMetadata = new Map());
  }return keyMetadata;
};
var ordinaryHasOwnMetadata = function ordinaryHasOwnMetadata(MetadataKey, O, P) {
  var metadataMap = getOrCreateMetadataMap(O, P, false);
  return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function ordinaryGetOwnMetadata(MetadataKey, O, P) {
  var metadataMap = getOrCreateMetadataMap(O, P, false);
  return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function ordinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
  getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function ordinaryOwnMetadataKeys(target, targetKey) {
  var metadataMap = getOrCreateMetadataMap(target, targetKey, false),
      keys = [];
  if (metadataMap) metadataMap.forEach(function (_, key) {
    keys.push(key);
  });
  return keys;
};
var toMetaKey = function toMetaKey(it) {
  return it === undefined || (typeof it === 'undefined' ? 'undefined' : _typeof(it)) == 'symbol' ? it : String(it);
};
var exp = function exp(O) {
  $export($export.S, 'Reflect', O);
};

module.exports = {
  store: store,
  map: getOrCreateMetadataMap,
  has: ordinaryHasOwnMetadata,
  get: ordinaryGetOwnMetadata,
  set: ordinaryDefineOwnMetadata,
  keys: ordinaryOwnMetadataKeys,
  key: toMetaKey,
  exp: exp
};
//# sourceMappingURL=_metadata.js.map


text:
<?xml version="1.0" encoding="utf-8"?>
<alpha
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:interpolator/accelerate_quad"
  android:fromAlpha="1.0"
  android:toAlpha="0.0"
  android:duration="@integer/search_fade_out_anim_time"/>


text:
using System;
using System.Linq;
using DumpObject;
using NUnit.Framework;
using System.Numerics;

namespace DumpObjectTests
{
    [TestFixture]
    public class DumperValueTypeTest
    {
        private Dumper _dumper;
        [OneTimeSetUp]
        public void InitializeTestSuite()
        {
            _dumper = new Dumper();
        }

        [Test]
        public void TestGet()
        {
            //string expr = "()=>_dumper.MaxDumpLevel";
            //Expression.Lambda<Func<_dumper.MaxDumpLevel.GetType()>>(expr);
        }

        [Test]
        public void DumpBooleanValueType()
        {
            var dump = _dumper.Dump(true);

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual(true, dump.Value, "Dump value shall be True.");
            Assert.AreEqual(typeof(bool), dump.Type, "Dump type shall be a Boolean.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }

        [Test]
        public void DumpDateTimeValueType()
        {
            var dump = _dumper.Dump(DateTime.Today);

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual(DateTime.Today, dump.Value, "Dump value shall be today.");
            Assert.AreEqual(typeof(DateTime), dump.Type, "Dump type shall be a DateTime.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }

        [Test]
        public void DumpIntValueType()
        {
            var dump = _dumper.Dump((int)5);

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual(5, dump.Value, "Dump value shall be 5.");
            Assert.AreEqual(typeof(int), dump.Type, "Dump type shall be an integer.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }

        [Test]
        public void DumpNullableWithValue()
        {
            int? value = 10;
            var dump = _dumper.Dump(value);

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual(10, dump.Value, "Dump value shall be 10.");
            Assert.AreEqual(typeof(int?), dump.Type, "Dump type shall be a Nullable<int>.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }

        [Test]
        public void DumpNullableWithoutValue()
        {
            int? value = null;
            var dump = _dumper.Dump(value);

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual(null, dump.Value, "Dump value shall be 10.");
            Assert.AreEqual(typeof(int?), dump.Type, "Dump type shall be a Nullable<int>.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }

        [Test]
        public void DumpStringValueType()
        {
            var dump = _dumper.Dump("value");

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual("value", dump.Value, "Dump value shall be 'value'.");
            Assert.AreEqual(typeof(string), dump.Type, "Dump type shall be a string.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }

        [Test]
        public void DumpBigIntegerValueType()
        {
            var bi = new BigInteger(1);
            var dump = _dumper.Dump(bi);

            Assert.NotNull(dump, "Dump shall return a DumpLevel instance.");
            Assert.AreEqual("1", dump.Value, "Dump value shall be 1.");
            Assert.AreEqual(typeof(BigInteger), dump.Type, "Dump type shall be a BigInteger.");
            Assert.AreEqual(0, dump.Count(), "Dump children count shall be 0.");
            Assert.AreEqual(0, dump.Level, "Dump level shall be 0.");
        }
    }
}


text:
require 'abstract_unit'
require 'action_dispatch/http/upload'
require 'action_controller/metal/strong_parameters'

class ParametersPermitTest < ActiveSupport::TestCase
  def assert_filtered_out(params, key)
    assert !params.has_key?(key), "key #{key.inspect} has not been filtered out"
  end

  setup do
    @params = ActionController::Parameters.new(
      person: {
        age: '32',
        name: {
          first: 'David',
          last: 'Heinemeier Hansson'
        },
        addresses: [{city: 'Chicago', state: 'Illinois'}]
      }
    )

    @struct_fields = []
    %w(0 1 12).each do |number|
      ['', 'i', 'f'].each do |suffix|
        @struct_fields << "sf(#{number}#{suffix})"
      end
    end
  end

  def walk_permitted params
    params.each do |k,v|
      case v
      when ActionController::Parameters
        walk_permitted v
      when Array
        v.each { |x| walk_permitted v }
      end
    end
  end

  test 'iteration should not impact permit' do
    hash = {"foo"=>{"bar"=>{"0"=>{"baz"=>"hello", "zot"=>"1"}}}}
    params = ActionController::Parameters.new(hash)

    walk_permitted params

    sanitized = params[:foo].permit(bar: [:baz])
    assert_equal({"0"=>{"baz"=>"hello"}}, sanitized[:bar].to_unsafe_h)
  end

  test 'if nothing is permitted, the hash becomes empty' do
    params = ActionController::Parameters.new(id: '1234')
    permitted = params.permit
    assert permitted.permitted?
    assert permitted.empty?
  end

  test 'key: permitted scalar values' do
    values  = ['a', :a, nil]
    values += [0, 1.0, 2**128, BigDecimal.new(1)]
    values += [true, false]
    values += [Date.today, Time.now, DateTime.now]
    values += [STDOUT, StringIO.new, ActionDispatch::Http::UploadedFile.new(tempfile: __FILE__),
      Rack::Test::UploadedFile.new(__FILE__)]

    values.each do |value|
      params = ActionController::Parameters.new(id: value)
      permitted = params.permit(:id)
      assert_equal value, permitted[:id]

      @struct_fields.each do |sf|
        params = ActionController::Parameters.new(sf => value)
        permitted = params.permit(:sf)
        assert_equal value, permitted[sf]
      end
    end
  end

  test 'key: unknown keys are filtered out' do
    params = ActionController::Parameters.new(id: '1234', injected: 'injected')
    permitted = params.permit(:id)
    assert_equal '1234', permitted[:id]
    assert_filtered_out permitted, :injected
  end

  test 'key: arrays are filtered out' do
    [[], [1], ['1']].each do |array|
      params = ActionController::Parameters.new(id: array)
      permitted = params.permit(:id)
      assert_filtered_out permitted, :id

      @struct_fields.each do |sf|
        params = ActionController::Parameters.new(sf => array)
        permitted = params.permit(:sf)
        assert_filtered_out permitted, sf
      end
    end
  end

  test 'key: hashes are filtered out' do
    [{}, {foo: 1}, {foo: 'bar'}].each do |hash|
      params = ActionController::Parameters.new(id: hash)
      permitted = params.permit(:id)
      assert_filtered_out permitted, :id

      @struct_fields.each do |sf|
        params = ActionController::Parameters.new(sf => hash)
        permitted = params.permit(:sf)
        assert_filtered_out permitted, sf
      end
    end
  end

  test 'key: non-permitted scalar values are filtered out' do
    params = ActionController::Parameters.new(id: Object.new)
    permitted = params.permit(:id)
    assert_filtered_out permitted, :id

    @struct_fields.each do |sf|
      params = ActionController::Parameters.new(sf => Object.new)
      permitted = params.permit(:sf)
      assert_filtered_out permitted, sf
    end
  end

  test 'key: it is not assigned if not present in params' do
    params = ActionController::Parameters.new(name: 'Joe')
    permitted = params.permit(:id)
    assert !permitted.has_key?(:id)
  end

  test 'key to empty array: empty arrays pass' do
    params = ActionController::Parameters.new(id: [])
    permitted = params.permit(id: [])
    assert_equal [], permitted[:id]
  end

  test 'do not break params filtering on nil values' do
    params = ActionController::Parameters.new(a: 1, b: [1, 2, 3], c: nil)

    permitted = params.permit(:a, c: [], b: [])
    assert_equal 1, permitted[:a]
    assert_equal [1, 2, 3], permitted[:b]
    assert_equal nil, permitted[:c]
  end

  test 'key to empty array: arrays of permitted scalars pass' do
    [['foo'], [1], ['foo', 'bar'], [1, 2, 3]].each do |array|
      params = ActionController::Parameters.new(id: array)
      permitted = params.permit(id: [])
      assert_equal array, permitted[:id]
    end
  end

  test 'key to empty array: permitted scalar values do not pass' do
    ['foo', 1].each do |permitted_scalar|
      params = ActionController::Parameters.new(id: permitted_scalar)
      permitted = params.permit(id: [])
      assert_filtered_out permitted, :id
    end
  end

  test 'key to empty array: arrays of non-permitted scalar do not pass' do
    [[Object.new], [[]], [[1]], [{}], [{id: '1'}]].each do |non_permitted_scalar|
      params = ActionController::Parameters.new(id: non_permitted_scalar)
      permitted = params.permit(id: [])
      assert_filtered_out permitted, :id
    end
  end

  test "fetch raises ParameterMissing exception" do
    e = assert_raises(ActionController::ParameterMissing) do
      @params.fetch :foo
    end
    assert_equal :foo, e.param
  end

  test "fetch with a default value of a hash does not mutate the object" do
    params = ActionController::Parameters.new({})
    params.fetch :foo, {}
    assert_equal nil, params[:foo]
  end

  test 'hashes in array values get wrapped' do
    params = ActionController::Parameters.new(foo: [{}, {}])
    params[:foo].each do |hash|
      assert !hash.permitted?
    end
  end

  # Strong params has an optimization to avoid looping every time you read
  # a key whose value is an array and building a new object. We check that
  # optimization here.
  test 'arrays are converted at most once' do
    params = ActionController::Parameters.new(foo: [{}])
    assert_same params[:foo], params[:foo]
  end

  # Strong params has an internal cache to avoid duplicated loops in the most
  # common usage pattern. See the docs of the method `converted_arrays`.
  #
  # This test checks that if we push a hash to an array (in-place modification)
  # the cache does not get fooled, the hash is still wrapped as strong params,
  # and not permitted.
  test 'mutated arrays are detected' do
    params = ActionController::Parameters.new(users: [{id: 1}])

    permitted = params.permit(users: [:id])
    permitted[:users] << {injected: 1}
    assert_not permitted[:users].last.permitted?
  end

  test "fetch doesnt raise ParameterMissing exception if there is a default" do
    assert_equal "monkey", @params.fetch(:foo, "monkey")
    assert_equal "monkey", @params.fetch(:foo) { "monkey" }
  end

  test "fetch doesnt raise ParameterMissing exception if there is a default that is nil" do
    assert_equal nil, @params.fetch(:foo, nil)
    assert_equal nil, @params.fetch(:foo) { nil }
  end

  test 'KeyError in fetch block should not be covered up' do
    params = ActionController::Parameters.new
    e = assert_raises(KeyError) do
      params.fetch(:missing_key) { {}.fetch(:also_missing) }
    end
    assert_match(/:also_missing$/, e.message)
  end

  test "not permitted is sticky beyond merges" do
    assert !@params.merge(a: "b").permitted?
  end

  test "permitted is sticky beyond merges" do
    @params.permit!
    assert @params.merge(a: "b").permitted?
  end

  test "modifying the parameters" do
    @params[:person][:hometown] = "Chicago"
    @params[:person][:family] = { brother: "Jonas" }

    assert_equal "Chicago", @params[:person][:hometown]
    assert_equal "Jonas", @params[:person][:family][:brother]
  end

  test "permit state is kept on a dup" do
    @params.permit!
    assert_equal @params.permitted?, @params.dup.permitted?
  end

  test "permit is recursive" do
    @params.permit!
    assert @params.permitted?
    assert @params[:person].permitted?
    assert @params[:person][:name].permitted?
    assert @params[:person][:addresses][0].permitted?
  end

  test "permitted takes a default value when Parameters.permit_all_parameters is set" do
    begin
      ActionController::Parameters.permit_all_parameters = true
      params = ActionController::Parameters.new({ person: {
        age: "32", name: { first: "David", last: "Heinemeier Hansson" }
      }})

      assert params.slice(:person).permitted?
      assert params[:person][:name].permitted?
    ensure
      ActionController::Parameters.permit_all_parameters = false
    end
  end

  test "permitting parameters as an array" do
    assert_equal "32", @params[:person].permit([ :age ])[:age]
  end

  test "to_h returns empty hash on unpermitted params" do
    assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
    assert_not @params.to_h.is_a? ActionController::Parameters
    assert @params.to_h.empty?
  end

  test "to_h returns converted hash on permitted params" do
    @params.permit!

    assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
    assert_not @params.to_h.is_a? ActionController::Parameters
  end

  test "to_h returns converted hash when .permit_all_parameters is set" do
    begin
      ActionController::Parameters.permit_all_parameters = true
      params = ActionController::Parameters.new(crab: "Senjougahara Hitagi")

      assert params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
      assert_not @params.to_h.is_a? ActionController::Parameters
      assert_equal({ "crab" => "Senjougahara Hitagi" }, params.to_h)
    ensure
      ActionController::Parameters.permit_all_parameters = false
    end
  end

  test "to_h returns always permitted parameter on unpermitted params" do
    params = ActionController::Parameters.new(
      controller: "users",
      action: "create",
      user: {
        name: "Sengoku Nadeko"
      }
    )

    assert_equal({ "controller" => "users", "action" => "create" }, params.to_h)
  end

  test "to_unsafe_h returns unfiltered params" do
    assert @params.to_unsafe_h.is_a? ActiveSupport::HashWithIndifferentAccess
    assert_not @params.to_unsafe_h.is_a? ActionController::Parameters
  end

  test "to_unsafe_h returns unfiltered params even after accessing few keys" do
    params = ActionController::Parameters.new("f"=>{"language_facet"=>["Tibetan"]})
    expected = {"f"=>{"language_facet"=>["Tibetan"]}}

    assert params['f'].is_a? ActionController::Parameters
    assert_equal expected, params.to_unsafe_h
  end

  test "to_h only deep dups Ruby collections" do
    company = Class.new do
      attr_reader :dupped
      def dup; @dupped = true; end
    end.new

    params = ActionController::Parameters.new(prem: { likes: %i( dancing ) })
    assert_equal({ 'prem' => { 'likes' => %i( dancing ) } }, params.permit!.to_h)

    params = ActionController::Parameters.new(companies: [ company, :acme ])
    assert_equal({ 'companies' => [ company, :acme ] }, params.permit!.to_h)
    assert_not company.dupped
  end

  test "to_unsafe_h only deep dups Ruby collections" do
    company = Class.new do
      attr_reader :dupped
      def dup; @dupped = true; end
    end.new

    params = ActionController::Parameters.new(prem: { likes: %i( dancing ) })
    assert_equal({ 'prem' => { 'likes' => %i( dancing ) } }, params.to_unsafe_h)

    params = ActionController::Parameters.new(companies: [ company, :acme ])
    assert_equal({ 'companies' => [ company, :acme ] }, params.to_unsafe_h)
    assert_not company.dupped
  end

  test "include? returns true when the key is present" do
    assert @params.include? :person
    assert @params.include? 'person'
    assert_not @params.include? :gorilla
  end
end


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

<title>The Fireworks Project Guide</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Hackers' and Hitchhikers' Guide to The Fireworks Project" />
<link rel="stylesheet" href="../../css/guide.css" type="text/css" media="handheld, all" />

Back to points voting overview.

Voting Process

Around the 3rd or 4th of the month, someone in The Fireworks Project creates a
monthly review on our Google Group to recap what has been done within the
company (this is an April, 2010 Recap).  On a monthly review, you can
expect to see the following:

A spread sheet of the Fireworks Project financials (This is April's Financials).

A recap of all the activity on Fireworks Basecamp page and who has participated.

A recap of the code developed and who has contributed.

A recap of the current active members (i.e. who is eligible to vote points)
and a spread sheet of the current point totals for every member (this is
April's Point Total).

After that, you are asked to vote points (if you are a current member) to
other members and recruits who you deem worthy of receiving points. It is
recommended, but not mandatory, that you give the reasoning for your voting. For
now, you must vote points on the monthly review thread.


text:
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';

/**
 * @class
 * DocumentsProxy
 * __NOTE__: An instance of this class is automatically created for an
 * instance of the SearchIndexClient.
 */
export interface DocumentsProxy {

    /**
     * Queries the number of documents in the Azure Search index.
     *
     * @param {object} [options] Optional Parameters.
     *
     * @param {object} [options.searchRequestOptions] Additional parameters for the
     * operation
     *
     * @param {uuid} [options.searchRequestOptions.clientRequestId] The tracking ID
     * sent with the request to help with debugging.
     *
     * @param {object} [options.customHeaders] Headers that will be added to the
     * request
     *
     * @returns {Promise} A promise is returned
     *
     * @resolve {HttpOperationResponse<Number>} - The deserialized result object.
     *
     * @reject {Error|ServiceError} - The error object.
     */
    countWithHttpOperationResponse(options?: { searchRequestOptions? : models.SearchRequestOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<number>>;

    /**
     * Queries the number of documents in the Azure Search index.
     *
     * @param {object} [options] Optional Parameters.
     *
     * @param {object} [options.searchRequestOptions] Additional parameters for the
     * operation
     *
     * @param {uuid} [options.searchRequestOptions.clientRequestId] The tracking ID
     * sent with the request to help with debugging.
     *
     * @param {object} [options.customHeaders] Headers that will be added to the
     * request
     *
     * @param {ServiceCallback} [optionalCallback] - The optional callback.
     *
     * @returns {ServiceCallback|Promise} If a callback was passed as the last
     * parameter then it returns the callback else returns a Promise.
     *
     * {Promise} A promise is returned.
     *
     *                      @resolve {Number} - The deserialized result object.
     *
     *                      @reject {Error|ServiceError} - The error object.
     *
     * {ServiceCallback} optionalCallback(err, result, request, response)
     *
     *                      {Error|ServiceError}  err        - The Error object if an error occurred, null otherwise.
     *
     *                      {Number} [result]   - The deserialized result object if an error did not occur.
     *
     *                      {WebResource} [request]  - The HTTP Request object if an error did not occur.
     *
     *                      {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
     */
    count(options?: { searchRequestOptions? : models.SearchRequestOptions, customHeaders? : { [headerName: string]: string; } }): Promise<number>;
    count(callback: ServiceCallback<number>): void;
    count(options: { searchRequestOptions? : models.SearchRequestOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<number>): void;
}


text:
package dev.knative.eventing.kafka.broker.receiver.impl.handler;

import dev.knative.eventing.kafka.broker.contract.DataPlaneContract;
import dev.knative.eventing.kafka.broker.core.metrics.Metrics;
import dev.knative.eventing.kafka.broker.core.reconciler.IngressReconcilerListener;
import dev.knative.eventing.kafka.broker.core.tracing.TracingConfig;
import dev.knative.eventing.kafka.broker.core.tracing.TracingSpan;
import dev.knative.eventing.kafka.broker.receiver.IngressProducer;
import dev.knative.eventing.kafka.broker.receiver.IngressRequestHandler;
import dev.knative.eventing.kafka.broker.receiver.RequestContext;
import dev.knative.eventing.kafka.broker.receiver.RequestToRecordMapper;
import io.cloudevents.CloudEvent;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Context;
import io.vertx.core.Future;
import io.vertx.kafka.client.producer.KafkaProducerRecord;
import io.vertx.kafka.client.producer.RecordMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static dev.knative.eventing.kafka.broker.core.utils.Logging.keyValue;
import static io.netty.handler.codec.http.HttpResponseStatus.ACCEPTED;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE;

/**
 * Implementation of {@link IngressRequestHandler} that will produce incoming requests using the provided producer.
 * <p>
 * Instances of this class can be shared among verticles, given the {@code requestToRecordMapper} provided is shareable among verticles.
 */
public class IngressRequestHandlerImpl implements IngressRequestHandler, IngressReconcilerListener {

  static final Tag UNKNOWN_EVENT_TYPE_TAG = Tag.of(Metrics.Tags.EVENT_TYPE, "unknown");

  static final int MAPPER_FAILED = BAD_REQUEST.code();
  static final Tags MAPPER_FAILED_COMMON_TAGS = Tags.of(
    Tag.of(Metrics.Tags.RESPONSE_CODE_CLASS, "4xx"),
    Tag.of(Metrics.Tags.RESPONSE_CODE, Integer.toString(MAPPER_FAILED)),
    UNKNOWN_EVENT_TYPE_TAG
  );

  static final int RECORD_PRODUCED = ACCEPTED.code();
  static final Tags RECORD_PRODUCED_COMMON_TAGS = Tags.of(
    Tag.of(Metrics.Tags.RESPONSE_CODE, Integer.toString(RECORD_PRODUCED)),
    Tag.of(Metrics.Tags.RESPONSE_CODE_CLASS, "2xx")
  );

  static final int FAILED_TO_PRODUCE = SERVICE_UNAVAILABLE.code();
  static final Tags FAILED_TO_PRODUCE_COMMON_TAGS = Tags.of(
    Tag.of(Metrics.Tags.RESPONSE_CODE, Integer.toString(FAILED_TO_PRODUCE)),
    Tag.of(Metrics.Tags.RESPONSE_CODE_CLASS, "5xx")
  );

  private static final Logger logger = LoggerFactory.getLogger(IngressRequestHandlerImpl.class);

  private final RequestToRecordMapper requestToRecordMapper;
  private final MeterRegistry meterRegistry;

  public IngressRequestHandlerImpl(final RequestToRecordMapper requestToRecordMapper,
                                   final MeterRegistry meterRegistry) {
    this.requestToRecordMapper = requestToRecordMapper;
    this.meterRegistry = meterRegistry;
  }

  @Override
  public void handle(final RequestContext requestContext, final IngressProducer producer) {

    final Tags resourceTags = Metrics.resourceRefTags(producer.getReference());

    requestToRecordMapper
      .requestToRecord(requestContext.getRequest(), producer.getTopic())
      .onFailure(cause -> {
        // Conversion to record failed
        requestContext.getRequest().response().setStatusCode(MAPPER_FAILED).end();

        final var tags = MAPPER_FAILED_COMMON_TAGS.and(resourceTags);
        Metrics.eventDispatchLatency(tags).register(meterRegistry).record(requestContext.performLatency());
        Metrics.eventCount(tags).register(meterRegistry).increment();

        logger.warn("Failed to convert request to record {}",
          keyValue("path", requestContext.getRequest().path()),
          cause
        );
      })
      .compose(record -> {
        // Conversion to record succeeded, let's push it to Kafka
        if (logger.isDebugEnabled()) {
          final var span = Span.fromContextOrNull(Context.current());
          if (span != null) {
            logger.debug("Received event {} {}",
              keyValue("event", record.value()),
              keyValue(TracingConfig.TRACE_ID_KEY, span.getSpanContext().getTraceId())
            );
          } else {
            logger.debug("Received event {}", keyValue("event", record.value()));
          }
        }

        // Decorate the span with event specific attributed
        TracingSpan.decorateCurrentWithEvent(record.value());

        final var eventTypeTag = Tag.of(Metrics.Tags.EVENT_TYPE, record.value().getType());

        return publishRecord(producer, record)
          .onSuccess(m -> {
            requestContext.getRequest().response().setStatusCode(RECORD_PRODUCED).end();

            final var tags = RECORD_PRODUCED_COMMON_TAGS
              .and(resourceTags)
              .and(eventTypeTag);
            Metrics.eventDispatchLatency(tags).register(meterRegistry).record(requestContext.performLatency());
            Metrics.eventCount(tags).register(meterRegistry).increment();

          })
          .onFailure(cause -> {
            requestContext.getRequest().response().setStatusCode(FAILED_TO_PRODUCE).end();

            final var tags = FAILED_TO_PRODUCE_COMMON_TAGS
              .and(resourceTags)
              .and(eventTypeTag);
            Metrics.eventDispatchLatency(tags).register(meterRegistry).record(requestContext.performLatency());
            Metrics.eventCount(tags).register(meterRegistry).increment();

            logger.warn("Failed to produce record {}",
              keyValue("path", requestContext.getRequest().path()),
              cause
            );
          });
      });
  }

  private static Future<RecordMetadata> publishRecord(final IngressProducer ingress,
                                                      final KafkaProducerRecord<String, CloudEvent> record) {
    return ingress.send(record)
      .onComplete(ar -> {
        if (ar.succeeded()) {
          if (logger.isDebugEnabled()) {
            logger.debug("Record produced {} {} {} {} {}",
              keyValue("topic", record.topic()),
              keyValue("partition", ar.result().getPartition()),
              keyValue("offset", ar.result().getOffset()),
              keyValue("value", record.value()),
              keyValue("headers", record.headers())
            );
          }
        } else {
          logger.error("Failed to send record {} {}",
            keyValue("topic", record.topic()),
            ar.cause()
          );
        }
      });
  }

  @Override
  public Future<Void> onNewIngress(DataPlaneContract.Resource resource, DataPlaneContract.Ingress ingress) {
    return Future.succeededFuture();
  }

  @Override
  public Future<Void> onUpdateIngress(DataPlaneContract.Resource resource, DataPlaneContract.Ingress ingress) {
    return Future.succeededFuture();
  }

  @Override
  public Future<Void> onDeleteIngress(DataPlaneContract.Resource resource, DataPlaneContract.Ingress ingress) {
    Metrics.searchResourceMeters(meterRegistry, resource.getReference()).forEach(meterRegistry::remove);
    return Future.succeededFuture();
  }
}


text:
/*

package org.apache.taverna.workbench.ui.credentialmanager.toolbar;

import static org.apache.taverna.workbench.ui.credentialmanager.toolbar.CredentialManagerToolbarSection.CREDENTIAL_MANAGER_TOOLBAR_SECTION;

import java.net.URI;

import javax.swing.Action;

import org.apache.taverna.ui.menu.AbstractMenuAction;
import org.apache.taverna.workbench.ui.credentialmanager.action.CredentialManagerAction;

public class CredentialManagerToolbarAction extends AbstractMenuAction {
	private static final String ENTRY_URI = "http://taverna.sf.net/2008/t2workbench/toolbar#credentialManagerAction";

	public CredentialManagerToolbarAction() {
		super(CREDENTIAL_MANAGER_TOOLBAR_SECTION, 100, URI.create(ENTRY_URI));
	}

	@Override
	protected Action createAction() {
		// need to add CredentialManager if toolbar is ever used
		return new CredentialManagerAction(null, null);
	}
}


text:
package moulder;

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

public class Registry {

    public static final class TemplatorConfig {
        public final String selector;
        public final List<Moulder> templators;

        public TemplatorConfig(String selector, List<Moulder> templators) {
            this.selector = selector;
            this.templators = templators;
        }
    }

    private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();

    /**
     * Registers a number of moulders to be applied to its input element's
     * children returned by the supplied selector
     *
     * @param selector
     *            to selected the input element's children to be processed
     * @param templators
     *            the moulders to apply on the selected children
     */
    public void register(String selector, List<Moulder> templators) {
        cfg.add(new TemplatorConfig(selector, templators));
    }

    /**
     * Return the registered selector/moulders pairs
     *
     * @return
     */
    public List<TemplatorConfig> getConfig() {
        return cfg;
    }
}