text:
namespace mus {

namespace {

// The first time polling a fence, delay some extra time to allow other
// stubs to process some work, or else the timing of the fences could
// allow a pattern of alternating fast and slow frames to occur.
const int64_t kHandleMoreWorkPeriodMs = 2;
const int64_t kHandleMoreWorkPeriodBusyMs = 1;

// Prevents idle work from being starved.
const int64_t kMaxTimeSinceIdleMs = 10;

}  // namespace

CommandBufferDriver::Client::~Client() {}

CommandBufferDriver::CommandBufferDriver(
    gpu::CommandBufferNamespace command_buffer_namespace,
    uint64_t command_buffer_id,
    gfx::AcceleratedWidget widget,
    scoped_refptr<GpuState> gpu_state)
    : command_buffer_namespace_(command_buffer_namespace),
      command_buffer_id_(command_buffer_id),
      widget_(widget),
      client_(nullptr),
      gpu_state_(gpu_state),
      previous_processed_num_(0),
      weak_factory_(this) {
  DCHECK_EQ(base::ThreadTaskRunnerHandle::Get(),
            gpu_state_->command_buffer_task_runner()->task_runner());
}

CommandBufferDriver::~CommandBufferDriver() {
  DCHECK(CalledOnValidThread());
  DestroyDecoder();
}

bool CommandBufferDriver::Initialize(
    mojo::ScopedSharedBufferHandle shared_state,
    mojo::Array<int32_t> attribs) {
  DCHECK(CalledOnValidThread());
  gpu::gles2::ContextCreationAttribHelper attrib_helper;
  if (!attrib_helper.Parse(attribs.storage()))
    return false;

  const bool offscreen = widget_ == gfx::kNullAcceleratedWidget;
  if (offscreen) {
    surface_ = gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size(1, 1));
  } else {
    surface_ = gfx::GLSurface::CreateViewGLSurface(widget_);
    gfx::VSyncProvider* vsync_provider =
        surface_ ? surface_->GetVSyncProvider() : nullptr;
    if (vsync_provider) {
      vsync_provider->GetVSyncParameters(
          base::Bind(&CommandBufferDriver::OnUpdateVSyncParameters,
                     weak_factory_.GetWeakPtr()));
    }
  }

  if (!surface_.get())
    return false;

  // TODO(piman): virtual contexts, gpu preference.
  context_ = gfx::GLContext::CreateGLContext(
      gpu_state_->share_group(), surface_.get(), gfx::PreferIntegratedGpu);
  if (!context_.get())
    return false;

  if (!context_->MakeCurrent(surface_.get()))
    return false;

  // TODO(piman): ShaderTranslatorCache is currently per-ContextGroup but
  // only needs to be per-thread.
  const bool bind_generates_resource = attrib_helper.bind_generates_resource;
  scoped_refptr<gpu::gles2::ContextGroup> context_group =
      new gpu::gles2::ContextGroup(
          gpu_state_->mailbox_manager(), new GpuMemoryTracker,
          new gpu::gles2::ShaderTranslatorCache,
          new gpu::gles2::FramebufferCompletenessCache, nullptr, nullptr,
          nullptr, bind_generates_resource);

  command_buffer_.reset(
      new gpu::CommandBufferService(context_group->transfer_buffer_manager()));
  bool result = command_buffer_->Initialize();
  DCHECK(result);

  decoder_.reset(::gpu::gles2::GLES2Decoder::Create(context_group.get()));
  scheduler_.reset(new gpu::GpuScheduler(command_buffer_.get(), decoder_.get(),
                                         decoder_.get()));
  sync_point_order_data_ = gpu::SyncPointOrderData::Create();
  sync_point_client_ = gpu_state_->sync_point_manager()->CreateSyncPointClient(
      sync_point_order_data_, GetNamespaceID(), command_buffer_id_);
  decoder_->set_engine(scheduler_.get());
  decoder_->SetWaitSyncPointCallback(base::Bind(
      &CommandBufferDriver::OnWaitSyncPoint, base::Unretained(this)));
  decoder_->SetFenceSyncReleaseCallback(base::Bind(
      &CommandBufferDriver::OnFenceSyncRelease, base::Unretained(this)));
  decoder_->SetWaitFenceSyncCallback(base::Bind(
      &CommandBufferDriver::OnWaitFenceSync, base::Unretained(this)));

  gpu::gles2::DisallowedFeatures disallowed_features;

  std::vector<int32_t> attrib_vector;
  attrib_helper.Serialize(&attrib_vector);
  if (!decoder_->Initialize(surface_, context_, offscreen, gfx::Size(1, 1),
                            disallowed_features, attrib_vector))
    return false;

  command_buffer_->SetPutOffsetChangeCallback(base::Bind(
      &gpu::GpuScheduler::PutChanged, base::Unretained(scheduler_.get())));
  command_buffer_->SetGetBufferChangeCallback(base::Bind(
      &gpu::GpuScheduler::SetGetBuffer, base::Unretained(scheduler_.get())));
  command_buffer_->SetParseErrorCallback(
      base::Bind(&CommandBufferDriver::OnParseError, base::Unretained(this)));

  // TODO(piman): other callbacks

  const size_t kSize = sizeof(gpu::CommandBufferSharedState);
  scoped_ptr<gpu::BufferBacking> backing(
      MojoBufferBacking::Create(std::move(shared_state), kSize));
  if (!backing)
    return false;

  command_buffer_->SetSharedStateBuffer(std::move(backing));
  gpu_state_->driver_manager()->AddDriver(this);
  return true;
}

void CommandBufferDriver::SetGetBuffer(int32_t buffer) {
  DCHECK(CalledOnValidThread());
  command_buffer_->SetGetBuffer(buffer);
}

void CommandBufferDriver::Flush(int32_t put_offset) {
  DCHECK(CalledOnValidThread());
  if (!MakeCurrent())
    return;

  command_buffer_->Flush(put_offset);
  ProcessPendingAndIdleWork();
}

void CommandBufferDriver::RegisterTransferBuffer(
    int32_t id,
    mojo::ScopedSharedBufferHandle transfer_buffer,
    uint32_t size) {
  DCHECK(CalledOnValidThread());
  // Take ownership of the memory and map it into this process.
  // This validates the size.
  scoped_ptr<gpu::BufferBacking> backing(
      MojoBufferBacking::Create(std::move(transfer_buffer), size));
  if (!backing) {
    DVLOG(0) << "Failed to map shared memory.";
    return;
  }
  command_buffer_->RegisterTransferBuffer(id, std::move(backing));
}

void CommandBufferDriver::DestroyTransferBuffer(int32_t id) {
  DCHECK(CalledOnValidThread());
  command_buffer_->DestroyTransferBuffer(id);
}

void CommandBufferDriver::CreateImage(int32_t id,
                                      mojo::ScopedHandle memory_handle,
                                      int32_t type,
                                      mojo::SizePtr size,
                                      int32_t format,
                                      int32_t internal_format) {
  DCHECK(CalledOnValidThread());
  if (!MakeCurrent())
    return;

  gpu::gles2::ImageManager* image_manager = decoder_->GetImageManager();
  if (image_manager->LookupImage(id)) {
    LOG(ERROR) << "Image already exists with same ID.";
    return;
  }

  gfx::BufferFormat gpu_format = static_cast<gfx::BufferFormat>(format);
  if (!gpu::ImageFactory::IsGpuMemoryBufferFormatSupported(
          gpu_format, decoder_->GetCapabilities())) {
    LOG(ERROR) << "Format is not supported.";
    return;
  }

  gfx::Size gfx_size = size.To<gfx::Size>();
  if (!gpu::ImageFactory::IsImageSizeValidForGpuMemoryBufferFormat(
          gfx_size, gpu_format)) {
    LOG(ERROR) << "Invalid image size for format.";
    return;
  }

  if (!gpu::ImageFactory::IsImageFormatCompatibleWithGpuMemoryBufferFormat(
          internal_format, gpu_format)) {
    LOG(ERROR) << "Incompatible image format.";
    return;
  }

  if (type != gfx::SHARED_MEMORY_BUFFER) {
    NOTIMPLEMENTED();
    return;
  }

  MojoPlatformHandle platform_handle;
  MojoResult extract_result = MojoExtractPlatformHandle(
      memory_handle.release().value(), &platform_handle);
  if (extract_result != MOJO_RESULT_OK) {
    NOTREACHED();
    return;
  }

#if defined(OS_WIN)
  base::SharedMemoryHandle handle(platform_handle, base::GetCurrentProcId());
#else
  base::FileDescriptor handle(platform_handle, false);
#endif

  scoped_refptr<gl::GLImageSharedMemory> image =
      new gl::GLImageSharedMemory(gfx_size, internal_format);
  // TODO(jam): also need a mojo enum for this enum
  if (!image->Initialize(
          handle, gfx::GpuMemoryBufferId(id), gpu_format, 0,
          gfx::RowSizeForBufferFormat(gfx_size.width(), gpu_format, 0))) {
    NOTREACHED();
    return;
  }

  image_manager->AddImage(image.get(), id);
}

void CommandBufferDriver::DestroyImage(int32_t id) {
  DCHECK(CalledOnValidThread());
  gpu::gles2::ImageManager* image_manager = decoder_->GetImageManager();
  if (!image_manager->LookupImage(id)) {
    LOG(ERROR) << "Image with ID doesn't exist.";
    return;
  }
  if (!MakeCurrent())
    return;
  image_manager->RemoveImage(id);
}

bool CommandBufferDriver::IsScheduled() const {
  DCHECK(CalledOnValidThread());
  return scheduler_->scheduled();
}

bool CommandBufferDriver::HasUnprocessedCommands() const {
  DCHECK(CalledOnValidThread());
  if (command_buffer_) {
    gpu::CommandBuffer::State state = GetLastState();
    return command_buffer_->GetPutOffset() != state.get_offset &&
        !gpu::error::IsError(state.error);
  }
  return false;
}

gpu::Capabilities CommandBufferDriver::GetCapabilities() const {
  DCHECK(CalledOnValidThread());
  return decoder_->GetCapabilities();
}

gpu::CommandBuffer::State CommandBufferDriver::GetLastState() const {
  DCHECK(CalledOnValidThread());
  return command_buffer_->GetLastState();
}

uint32_t CommandBufferDriver::GetUnprocessedOrderNum() const {
  DCHECK(CalledOnValidThread());
  return sync_point_order_data_->unprocessed_order_num();
}

uint32_t CommandBufferDriver::GetProcessedOrderNum() const {
  DCHECK(CalledOnValidThread());
  return sync_point_order_data_->processed_order_num();
}

bool CommandBufferDriver::MakeCurrent() {
  DCHECK(CalledOnValidThread());
  if (!decoder_)
    return false;
  if (decoder_->MakeCurrent())
    return true;
  DLOG(ERROR) << "Context lost because MakeCurrent failed.";
  gpu::error::ContextLostReason reason =
      static_cast<gpu::error::ContextLostReason>(
          decoder_->GetContextLostReason());
  command_buffer_->SetContextLostReason(reason);
  command_buffer_->SetParseError(gpu::error::kLostContext);
  OnContextLost(reason);
  return false;
}

void CommandBufferDriver::ProcessPendingAndIdleWork() {
  DCHECK(CalledOnValidThread());
  scheduler_->ProcessPendingQueries();
  ScheduleDelayedWork(
      base::TimeDelta::FromMilliseconds(kHandleMoreWorkPeriodMs));
}

void CommandBufferDriver::ScheduleDelayedWork(base::TimeDelta delay) {
  DCHECK(CalledOnValidThread());
  const bool has_more_work =
      scheduler_->HasPendingQueries() || scheduler_->HasMoreIdleWork();
  if (!has_more_work) {
    last_idle_time_ = base::TimeTicks();
    return;
  }

  const base::TimeTicks current_time = base::TimeTicks();
  // |process_delayed_work_time_| is set if processing of delayed work is
  // already scheduled. Just update the time if already scheduled.
  if (!process_delayed_work_time_.is_null()) {
    process_delayed_work_time_ = current_time + delay;
    return;
  }

  // Idle when no messages are processed between now and when PollWork is
  // called.
  previous_processed_num_ =
      gpu_state_->driver_manager()->GetProcessedOrderNum();

  if (last_idle_time_.is_null())
    last_idle_time_ = current_time;

    // scheduled() returns true after passing all unschedule fences and this is
    // when we can start performing idle work. Idle work is done synchronously
    // so we can set delay to 0 and instead poll for more work at the rate idle
    // work is performed. This also ensures that idle work is done as
    // efficiently as possible without any unnecessary delays.
  if (scheduler_->scheduled() && scheduler_->HasMoreIdleWork())
    delay = base::TimeDelta();

  process_delayed_work_time_ = current_time + delay;
  gpu_state_->command_buffer_task_runner()->task_runner()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&CommandBufferDriver::PollWork, weak_factory_.GetWeakPtr()),
      delay);
}

void CommandBufferDriver::PollWork() {
  DCHECK(CalledOnValidThread());
  // Post another delayed task if we have not yet reached the time at which
  // we should process delayed work.
  base::TimeTicks current_time = base::TimeTicks::Now();
  DCHECK(!process_delayed_work_time_.is_null());
  if (process_delayed_work_time_ > current_time) {
    gpu_state_->command_buffer_task_runner()->task_runner()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&CommandBufferDriver::PollWork, weak_factory_.GetWeakPtr()),
      process_delayed_work_time_ - current_time);
    return;
  }
  process_delayed_work_time_ = base::TimeTicks();
  PerformWork();
}

void CommandBufferDriver::PerformWork() {
  DCHECK(CalledOnValidThread());
  if (!MakeCurrent())
    return;

  if (scheduler_) {
    const uint32_t current_unprocessed_num =
        gpu_state_->driver_manager()->GetUnprocessedOrderNum();
    // We're idle when no messages were processed or scheduled.
    bool is_idle = (previous_processed_num_ == current_unprocessed_num);
    if (!is_idle && !last_idle_time_.is_null()) {
      base::TimeDelta time_since_idle =
          base::TimeTicks::Now() - last_idle_time_;
      base::TimeDelta max_time_since_idle =
          base::TimeDelta::FromMilliseconds(kMaxTimeSinceIdleMs);
      // Force idle when it's been too long since last time we were idle.
      if (time_since_idle > max_time_since_idle)
        is_idle = true;
    }

    if (is_idle) {
      last_idle_time_ = base::TimeTicks::Now();
      scheduler_->PerformIdleWork();
    }
    scheduler_->ProcessPendingQueries();
  }

  ScheduleDelayedWork(
      base::TimeDelta::FromMilliseconds(kHandleMoreWorkPeriodBusyMs));
}

void CommandBufferDriver::DestroyDecoder() {
  DCHECK(CalledOnValidThread());
  if (decoder_) {
    gpu_state_->driver_manager()->RemoveDriver(this);
    bool have_context = decoder_->MakeCurrent();
    decoder_->Destroy(have_context);
    decoder_.reset();
  }
}

void CommandBufferDriver::OnUpdateVSyncParameters(
    const base::TimeTicks timebase,
    const base::TimeDelta interval) {
  DCHECK(CalledOnValidThread());
  if (client_) {
    client_->UpdateVSyncParameters(timebase.ToInternalValue(),
                                   interval.ToInternalValue());
  }
}

bool CommandBufferDriver::OnWaitSyncPoint(uint32_t sync_point) {
  DCHECK(CalledOnValidThread());
  DCHECK(scheduler_->scheduled());
  if (!sync_point)
    return true;

  scheduler_->SetScheduled(false);
  gpu_state_->sync_point_manager()->AddSyncPointCallback(
      sync_point, base::Bind(&gpu::GpuScheduler::SetScheduled,
                             scheduler_->AsWeakPtr(), true));
  return scheduler_->scheduled();
}

void CommandBufferDriver::OnFenceSyncRelease(uint64_t release) {
  DCHECK(CalledOnValidThread());
  if (!sync_point_client_->client_state()->IsFenceSyncReleased(release))
    sync_point_client_->ReleaseFenceSync(release);
}

bool CommandBufferDriver::OnWaitFenceSync(
    gpu::CommandBufferNamespace namespace_id,
    uint64_t command_buffer_id,
    uint64_t release) {
  DCHECK(CalledOnValidThread());
  DCHECK(IsScheduled());
  gpu::SyncPointManager* sync_point_manager = gpu_state_->sync_point_manager();
  DCHECK(sync_point_manager);

  scoped_refptr<gpu::SyncPointClientState> release_state =
      sync_point_manager->GetSyncPointClientState(namespace_id,
                                                  command_buffer_id);

  if (!release_state)
    return true;

  scheduler_->SetScheduled(false);
  sync_point_client_->Wait(
      release_state.get(),
      release,
      base::Bind(&gpu::GpuScheduler::SetScheduled,
                 scheduler_->AsWeakPtr(), true));
  return scheduler_->scheduled();
}

void CommandBufferDriver::OnParseError() {
  DCHECK(CalledOnValidThread());
  gpu::CommandBuffer::State state = GetLastState();
  OnContextLost(state.context_lost_reason);
}

void CommandBufferDriver::OnContextLost(uint32_t reason) {
  DCHECK(CalledOnValidThread());
  if (client_)
    client_->DidLoseContext(reason);
}

}  // namespace mus


text:
Chains are Uni's way of handling asynchronous functions. Each block in a chain represents a functional piece that must be passed to continue on to the next block. If a fail is triggered, the next fail block in the chain will get called.

```javascript

uni.ch(function(d,ch){
	console.log('first');
	ch.pass('first is done');
}).pass(function(d,ch){
	console.log(d,' now on second');
	ch.fail('testing a fail');
}).fail(function(d,ch){
	console.log('failed:',d);
});

```

### Arguments

- `d` (any): data that is passed into the block by the caller
- `ch` (obj): ch is an object that defines a `pass` and `fail` function

For actions, pass the ch object into by action in the place of the done object. Upon pass of the action, the next `pass` block will be executed with `d` holding the value passed inside the `done.pass` call. If fail is called, the next `fail` block will be executed with the value passed in the `done.fail` function as `d`.

## LOOP

Loops are used to handle asynchronous repeating functions. Loops are used when a standard loop operator like `for` will not work.

```javascript

var ary = [1,2,3];
uni.loop(ary,function(loop){
	console.log('loop ',ary[loop.i]);
	loop.pass();
});

```

redpajama_set_name: RedPajamaGithub


text:
/** \file fastformat/inserters/to_e.hpp
 *
 * [C++ only] Inserter functions for floating-point types.
 */

#ifndef FASTFORMAT_INCL_FASTFORMAT_INSERTERS_HPP_TO_E
#define FASTFORMAT_INCL_FASTFORMAT_INSERTERS_HPP_TO_E

/* /////////////////////////////////////////////////////////////////////////
 * Version information
 */

#ifndef FASTFORMAT_DOCUMENTATION_SKIP_SECTION
# define FASTFORMAT_VER_FASTFORMAT_INSERTERS_HPP_TO_E_MAJOR     1
# define FASTFORMAT_VER_FASTFORMAT_INSERTERS_HPP_TO_E_MINOR     0
# define FASTFORMAT_VER_FASTFORMAT_INSERTERS_HPP_TO_E_REVISION  4
# define FASTFORMAT_VER_FASTFORMAT_INSERTERS_HPP_TO_E_EDIT      6
#endif /* !FASTFORMAT_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#include <fastformat/inserters/real.hpp>

/* /////////////////////////////////////////////////////////////////////////
 * Namespace
 */

#if !defined(FASTFORMAT_NO_NAMESPACE)
namespace fastformat
{
namespace inserters
{
#endif /* !FASTFORMAT_NO_NAMESPACE */

/* /////////////////////////////////////////////////////////////////////////
 * Inserter functions
 */

/** Inserts the string form of a floating-point value
 *
 * \ingroup group__inserters
 *
 * \param value The \c double value to be converted to string form
 */
inline stlsoft::basic_shim_string<ff_char_t, 64> to_e(
    double const&   value
)
{
    return
#if !defined(FASTFORMAT_NO_NAMESPACE)
      ::fastformat::inserters::
#endif /* !FASTFORMAT_NO_NAMESPACE */
        real(value, ximpl_real::default_width_sentinel_(), ximpl_real::default_precision_sentinel_(), 'e');
}

/** Inserts the string form of a floating-point value
 *
 * \ingroup group__inserters
 *
 * \param value The \c double value to be converted to string form
 */
inline stlsoft::basic_shim_string<ff_char_t, 64> to_E(
    double const&   value
)
{
    return
#if !defined(FASTFORMAT_NO_NAMESPACE)
      ::fastformat::inserters::
#endif /* !FASTFORMAT_NO_NAMESPACE */
        real(value, ximpl_real::default_width_sentinel_(), ximpl_real::default_precision_sentinel_(), 'E');
}

/** Inserts the string form of a floating-point value, with the given width
 * and precision
 *
 * \ingroup group__inserters
 *
 * \param value The \c double value to be converted to string form
 * \param minimumWidth The minimum width of the resulting string form
 * \param decimalPlaces The number of decimal places to be included
 *
 * \pre minimumWidth < 512
 * \pre decimalPlaces <= minimumWidth
 */
inline stlsoft::basic_shim_string<ff_char_t, 64> to_e(
    double const&   value
,   int             minimumWidth
,   int             decimalPlaces
)
{
    return
#if !defined(FASTFORMAT_NO_NAMESPACE)
      ::fastformat::inserters::
#endif /* !FASTFORMAT_NO_NAMESPACE */
        real(value, minimumWidth, decimalPlaces, 'e');
}

/** Inserts the string form of a floating-point value, with the given width
 * and precision
 *
 * \ingroup group__inserters
 *
 * \param value The \c double value to be converted to string form
 * \param minimumWidth The minimum width of the resulting string form
 * \param decimalPlaces The number of decimal places to be included
 *
 * \pre minimumWidth < 512
 * \pre decimalPlaces <= minimumWidth
 */
inline stlsoft::basic_shim_string<ff_char_t, 64> to_E(
    double const&   value
,   int             minimumWidth
,   int             decimalPlaces
)
{
    return
#if !defined(FASTFORMAT_NO_NAMESPACE)
      ::fastformat::inserters::
#endif /* !FASTFORMAT_NO_NAMESPACE */
        real(value, minimumWidth, decimalPlaces, 'E');
}

/* /////////////////////////////////////////////////////////////////////////
 * Namespace
 */

#if !defined(FASTFORMAT_NO_NAMESPACE)
} // namespace inserters
using ::fastformat::inserters::to_e;
using ::fastformat::inserters::to_E;
} // namespace fastformat
#endif /* !FASTFORMAT_NO_NAMESPACE */

/* /////////////////////////////////////////////////////////////////////////
 * Inclusion
 */

#ifdef STLSOFT_PPF_pragma_once_SUPPORT
# pragma once
#endif /* STLSOFT_PPF_pragma_once_SUPPORT */

/* ////////////////////////////////////////////////////////////////////// */

#endif /* !FASTFORMAT_INCL_FASTFORMAT_INSERTERS_HPP_TO_E */

/* ///////////////////////////// end of file //////////////////////////// */


text:
{#
   This file is part of the Exposure package.

   Copyright 2013 by Sébastien Pujadas

   For the full copyright and licence information, please view the LICENCE
   file that was distributed with this source code.
#}

{% from 'form_macros.tpl.html' import error, autofill, autofill_or_value, value_if_autofill_or_boolean, error_class %}

{% extends "page-left-nav.tpl.html" %}

{% block content %}

Profile

<form method="post" class="form-horizontal" enctype="multipart/form-data" action="/">

    Name

      <input type="text" class="form-control" id="name" name="name" placeholder="name"
             maxlength="254" value="{{ autofill_or_value (session.autofill, 'name', user.name) }}" />
      {{ error(session.errors, 'name') }}

    Surname

      <input type="text" class="form-control" id="surname" name="surname" placeholder="surname"
             maxlength="254" value="{{ autofill_or_value (session.autofill, 'surname', user.surname) }}" />
      {{ error(session.errors, 'surname') }}

    Email

      <input type="email" class="form-control" id="email" name="email" placeholder="email"
             maxlength="254" value="{{ autofill_or_value (session.autofill, 'email', user.email) }}" />
      {{ error(session.errors, 'email') }}

    Email (confirm)

      <input type="email" class="form-control" id="email_check" name="email_check" placeholder="email (confirm)"
             maxlength="254" value="{{ autofill_or_value (session.autofill, 'email_check', user.email) }}" />
      {{ error(session.errors, 'email_check') }}

    Password

Change password

    Country

      <select name="country" class="form-control" id="country">
          <option value=""></option>
          {% for c in countries %}
          <option value="{{ c.code }}"{% if (country is defined) and (country == c.code) %} selected="selected"{% endif %}>{{c.name.stringByLanguageCode(session.language)}}</option>
          {% endfor %}
      </select>
    {{ error(session.errors, 'country') }}

  {% include 'location.inc.tpl.html' %}

    Photo (2 Mo max.)

      {% if user.photo %}
        {% if user.moderationStatus.status == constant('\\Exposure\\Model\\ModerationStatus::STATUS_APPROVED') %}

If you change your photo, you will have to resubmit your profile to be moderated.

        {% endif %}

      {% endif %}
      <input type="hidden" name="MAX_FILE_SIZE" value="2097152"/>
      <input type="file" name="photo"/>
      {{ error(session.errors, 'photo') }}

    Presentation

      {% if user.moderationStatus.status == constant('\\Exposure\\Model\\ModerationStatus::STATUS_APPROVED') %}

If you update your presentation, you will have to resubmit your profile to be moderated.

      {% endif %}
      <textarea class="form-control" name="presentation" id="presentation"
        maxlength="{{constant('\\Exposure\\Model\\User::PRESENTATION_MAX_LENGTH')}}"
        placeholder="presentation">{{ autofill_or_value(session.autofill, 'presentation', user.presentation.stringByLanguageCode(session.language)) }}</textarea>
      {{ error(session.errors, 'presentation') }}

  <button type="submit" class="btn btn-primary">Save</button>
  <input type="hidden" name="token" value="{{ session.token }}" />
  <input type="hidden" name="action" value="profile_save" />
</form>

Cancel

{% endblock %}


text:
- Use iRODS to upload, manage and annotate data
- Steer dataflows between iRODS instances with the iRODS native icommands
- Do automatic data replication between iRODS servers with the B2SAFE module
- Steer data between our laptop/userinterface and iRODS with gridFTP
- Execute third party transfers with gridFTP between a gridFTP enabled iRODS server and a 'normal' gridFTP server

# iRODS and B2SAFE
## Login
You login to iRODS with the command
```
iinit
```
You will be asked for the iRODS server you would like to connect to the port (standard 1247), the zone name of the iRODS server, your iRODS user name and password.

## Help
You can get a full list of all commands with:
```
ihelp
```
If you are unsure how to use a command or what options there are, call the help:
```
<command> -h
```

## Basic commands
First we will have a look at some very basic commands to move through the logical namespace in iRPDS. The basic commands in iRODS are very similar to bash/shell commands.
You can browse through your coollections with:
```
ils
```
To change the current working directory do:
```
ipwd
icd /aliceZone/home/<username>/<collection>
ipwd
```
And you can create new collections with:
```
imkdir TestC
```

## Logical and physical namespaces in iRODS
The *ils* command gives you an option to extract the physical location of a file:
```
ils -L
```
We will use this command quite often today to see what happens with files upon replication.
With this command you see where the file is stored on the iRODS server.

## Uploading a Collection to iRODS
We can put a single file into our home-collection or a designated collection.

```
echo "Some text" > test.txt
iput -K test.txt TestC
```
The flag *-K* triggers the calculation and verification of a checksum, in this case an md5 checksum. We can drop the destination folder *TestC*, in that case, the data will be stored in the current working collection that you can check with *ipwd*.

Let us create some data in our home directory on the linux filesystem to upload to iRODS
```
mkdir -p Collection
for i in {000..002}; do echo "Collection${i} and some text.">"Collection/File${i}.txt"; done
```

Now upload the collection to iRODS:
```
iput -r -K Collection
```
The option *K* triggers the calculation of checksums and verifies them upon upload.
Check with
```
ils Collection -L
```
You will see some output like:
```
alice               0 demoResc           29 2016-08-23.09:04 & File000.txt
    9dcbb372c049bdd4b035c1ccb3798e69    generic    /irodsVault/home/alice/Collection/File000.txt
```
* *alice* is the data owner
* *0* is the index of this replica. the number only refers to replicas in one iRODS zone and can be used to autpmatically trim the number of replicas or create new ones in case one got lost.
* *demoResc* is the resource on which the data is stored. Resources can refer to certain paths on the iRODS server or other storage servers and clusters.
* The next entry is the time of the upload and the file name
* the follwing entry is the checksum, in our case it is a MD5 sum
* The last entry is the physical path of the data, in our case the data lies on the iRODS server.

**Exercise**

Data can be downloaded from iRODS to you local machine with the command *iget*.
Explore the command *iget* to store the data back in you home directory. Do not overwrite your original data!

## Replication across iRODS Zones
To keep data safe you sometimes want to store them at a different site belonging to a different administrative unit. iRODS offers to federate iRODS Zones for specific users.
In our little example we set up such a federation.

Remember: to check what data we have stored in our iRODS home collection we used
```
ils
```
and it listed automatically all data in */aliceZone/home/<user>*.

To access data on the other iRODS server type in:
```
ils /bobZone/home/<user>#aliceZone
```
* *bobZone* denotes the zone on the different server, they are really physically different machines and they run their own iCAT data base
* Your username needs to be extended with *#aliceZone* to indicate that on bobZone you are a remote user
* Authentication: You authenticate with your iRODS instance. System administrators at the other iRODS instance added you as a remote users and your corresponding rights.

### Manual replication to a different iRODS zone
You can use the same commands as above to steer and browse through your home Collection in BobZone. However, you cannot use *iput* to upload data there.
The corresponding command is *irsync*

**Exercise** transfer one file from your *Collection* to bobzone using *irsync*
```
irsync i:<path/file> i:<path/file>
ils /bobZone/<path-to-file> -L
```
The *i* indicates that the file lies in the iRODS logical namespace.
Obviously bobZone uses a different default checksum algorithm.

### Automatic replication with B2SAFE
To understand B2SAFE we first need to see what iRODS rules are.
### iRODS rules
We have seen that we can replicate data to a different Zone. Now we want to be sure that we can track replicated files, replicate files and collections upon change and we want automatise everything as much as possible. Here, we will make use of iRODS rules.
iRODS rules are short procedure or functions with an own syntax.

Open the file *examples/hello.r*

```
HelloWorld{
    if(*name=="<YourName>"){
        writeLine("stdout", "Hello *name!");
        }
    else { writeLine("stdout", "Hello world!"); }
}
INPUT *name="YourName"
OUTPUT ruleExecOut, *name
```
Replace *YourName* with your name, once in the if statement and if you wish also in the line starting with *INPUT*.

* You can specify the value of parameters in INPUT
* ruleExecOut is the standard output, here the variable *name* is returned too.
Safe the file as *hello.r* somewhere in your account and execute the following command:

```
irule -F hello.r
```

#### B2SAFE
B2SAFE is a ruleset that extends the core rule set of iRODS and provides tools to replicate data and keep track of the replicas by creating persistent identifiers and leaving additional information in the iCAT database.

We will use B2SAFE to replicate our Collection to bobZone, create PIDs for the original data in aliceZone, create PIDs for the replicas in bobZone and link the files on PID level.

First let us inspect and adapt the corresponding rule in examples/eudatRepl.r .
```
eudatRepl{
    # Data set replication
    # registered data (with PID registration) (3rd argument - 1st bool("true"))
    # recursive (4th argument 2nd bool("true"))
    EUDATReplication(*source, *destination, bool("true"), bool("true"), *response)
}
INPUT *source='/aliceZone/home/alice/Collection', *destination='/bobZone/home/alice#aliceZone/Collection'
OUTPUT ruleExecOut
```
*EUDATReplication* is a rule specified in the B2SAFE module.

Execute the rule with:
```
irule -vF eudatRepl.r
```
* The v-option stands for verbose
The execution of the rule takes some time due to several checks and the creation of the PIDs.

We did not specify any output, so we need to find out what happened.
First we inspect the iCAT metadata entry for our data in aliceZone:

```
imeta ls -d Collection/File000.txt
```

```
AVUs defined for dataObj Collection/File000.txt:
attribute: eudat_dpm_checksum_date:demoResc
value: 01471935855
units:
----
attribute: PID
value: 846/4798e6c8-6a8c-11e6-9242-fa163efdf672
units:
```
The B2SAFE rules automatically calculate a checksum and store the date of the last check as an AVU in the iCAT. They also assign a PID. You can inspect the information stored in the PID at:

```
http://epic3.storage.surfsara.nl:8001/846/4798e6c8-6a8c-11e6-9242-fa163efdf672?noredirect
```

*NOTE*, do not forget the *?noredirect*, our data is not publicly avaiable and accessible via aURL, so this will fail.

* The field URL shows you the iRODS logical path.
* There is a field with the MD5 checksum
* There is a special field *10320/LOC*. It contains the iRODS path of our file and some other PID.

Let us inspect this PID by copying the last bits starting at *846* and resolve it with the epic3 resolver.
(We are working with test PIDs on a test server. Production PIDs are resolved by hdl.handle.net, thus the whole link would work.)

```
http://epic3.storage.surfsara.nl:8001/846/485beb0a-6a8c-11e6-926e-fa163e38303e?noredirect
```

We see here that this file resides in *bobZone*, so it is one of the previously created replicas.
It contains the same checksum as our original file.
There are two additional entries *ROR* and *PPID*. The *ROR* conatins the PID of the original file, the *PPID* contains the PID of the direct parent file. In our case both are identical.
You see that the *10320/LOC* only contains the path to the replica. Usually this field collects all direct children of a data file.

These are all B2SAFE specifiactions and have been implemented by EUDAT.

Now let us verify the information we drew from the PIDs sytem and go to bobZone on our shell.
You can access the iCAT catalogue in bobZone and fetch information on the replica:

```
imeta ls -d /bobZone/home/alice#aliceZone/Collection/File000.txt
```

*Note* that collections also receive a PID:
```
imeta ls -C Collection
```

#### (Optional) Extending the replication chain
Now adopt the *eudatRepl.r* rule to replicate the Collection you have in bobZone back to a different Collection in aliceZone.
Simply exchange the values in *source* and *destination* and make sure to rename *Collection* in aliceZone (otherwise you will overwrite the previous one).

```
eudatRepl{
    # Data set replication
    # registered data (with PID registration) (3rd argument - 1st bool("true"))
    # recursive (4th argument 2nd bool("true"))
    EUDATReplication(*source, *destination, bool("true"), bool("true"), *response)
}
INPUT *source='/bobZone/home/alice#aliceZone/Collection', *destination='/aliceZone/home/alice/Collection1'
OUTPUT ruleExecOut
```

**Exercise**
- Inspect the new PIDs for the data in *Collection1*, especially the fields *PPID* and *ROR*
- What changed in the PID entries of the ROR-PID and the PPID-PID?

Example Chain:
- ROR:
   http://epic3.storage.surfsara.nl:8001/846/4798e6c8-6a8c-11e6-9242-fa163efdf672?noredirect
- Direct child of the ROR:
   http://epic3.storage.surfsara.nl:8001/846/485beb0a-6a8c-11e6-926e-fa163e38303e?noredirect
- Child of the replica:
   http://epic3.storage.surfsara.nl:8001/846/fd5f8fc8-6a8e-11e6-9aae-fa163efdf672?noredirect

**Exercise**
- Rereplicate the original data collection to another collection to bob.
- Adjust the rule eudatRepl.r
- Which PIDs change?

# B2STAGE: Data management in iRODS with gridFTP
We extended the iRODS with a gridFTP endpoint and coupled it to the iRODS instance.
This is what the technology B2STAGE does. It also includes automatic PID resolving.
As result you can use gridFTP tools like *globus-url-copy* to copy, delete and manage your data in the iRODS logical namespace.

## Upload data to iRODS with *globus-url-copy*
Reupload your collections again and store it under a different iRODS path.

Ensure you are in your user directory of the remote alice zone:

```
ipwd
icd /aliceZone/home/<username>/
ipwd
```

First create a grid proxy from your certificate:

```
grid-proxy-init
```

then you can use the follwoing command to upload your whole collection to a new iRODS collection

```
imkdir GridFTPColl
globus-url-copy -r Collection/ gsiftp://di4r2016-3.novalocal/aliceZone/home/<username>/GridFTPColl/
```
- *gsiftp* dentotes the endpoint and protocol
- *di4r2016-3.novalocal* is the short cut for the gridFTP server, (inspect mapping in /etc/hosts)
- *aliceZone/home/<username>/GridFTPColl/* is the iRODS path, where `<username>` is replaced with your username.

We created an event hook. All data under the collection public will be labeled with a PID and replicated to the other iRODS server upon deposition.
Event hooks work like normal rules, but the rule engine executes them automatically, e.g. upon creation of a document or upon put.

We created an event hook. All data under the collection public will be labeled with a PID and replicated to the other iRODS server upon deposition.
Event hooks work like normal rules, but the rule engine executes them automatically, e.g. upon creation of a document or upon put.

Check with

```
ils -L GridFTPColl
```
to see what happened.

### Remarks

With the options *-sync* and *-sync-level* of the `globus-url-copy` command you can determine which files to update. Note, that these commands will perform checksum calculations but will not store them in the iCAT catalogue.

With the command `grid-proxy-info` you can get information about the state of the current proxy certificate. Ensure that time left is larger than zero.

What is a proxy certificate? To interact directly with a remote service a certificate can be used to prove identity. However, in the grid world it is often necessary for a remote service to act on a user's behalf.
One could imagine sending the private key to remote services, however this is very insecure. On the grid, a proxy allows limited delegation of rights. Strictly speaking, a proxy is also a certificate, but usually the unqualified term "certificate" is reserved for something issued by a certificate authority (CA). Proxies normally have a rather short lifetime, typically 12 hours. See [1] for more information on proxy certificates.

## Retrieve data by PID
In the previous section we labeled files with PIDs. The B2SAFE module, however, does not only label files with PIDs but also Collections. These PIDs can be used to list and retrieve data with gridFTP.

```
imeta ls -C Collection
globus-url-copy -list gsiftp://di4r2016-3.novalocal/846/4318901c-6a8c-11e6-a1db-fa163efdf672/
```

Note: replace the pid value in the `globus-url-copy` command with the correct output from the `imeta ls` command.

We replaced the iRODS path with the PID for the collection.
The GridFTP tries to find the file, when this fails it tries to resolve the file path. If this is successful and the URL field in the PID contains a path to which this gridFTP instance has access to, you can retrieve the file(s).

```
globus-url-copy -cd gsiftp://di4r2016-3.novalocal/846/4318901c-6a8c-11e6-a1db-fa163efdf672/ NewCollGsi/
ls NewCollGsi
```
Note: make sure to update the pid value again.

## Third party transfers
You can steer data flows between gridFTP endpoints from an external client. We will not send data from our iRODS server to another gridFTP server (which accidentially also lies on the machine where the iRODS bobZone is located. However, they are NOT connected.).
We will transfer the data behind a PID:

```
imeta ls -C Collection
```

to the other gridFTP server

```
globus-url-copy gsiftp://di4r2016-3.novalocal/846/4318901c-6a8c-11e6-a1db-fa163efdf672/ gsiftp://di4r2016-2.novalocal/home/di4r/
```
On the other server the files in *Collection* are saved in *tmp*:
(Note, you do not have access to the server, so you have to trust me.)
```
root@di4r2016-2:/home/cloud-user# ls /tmp/
4318901c-6a8c-11e6-a1db-fa163efdf672  psqlodbc_irods19024.log  psqlodbc_irods8322.log  psqlodbc_irods8551.log  psqlodbc_irods8740.log
File000.txt                           psqlodbc_irods19044.log  psqlodbc_irods8347.log  psqlodbc_irods8553.log  psqlodbc_irods8742.log
File001.txt                           psqlodbc_irods19100.log  psqlodbc_irods8476.log  psqlodbc_irods8560.log  psqlodbc_irods8745.log
File002.txt
...
```

And we can put data from another gridFTP endpoint into iRODS via the gridFTP protocol:
We fetch one of the data files we have just saved in the *tmp* directory of the gridFTP endpoint and save it as *ExternalColl* in our iRODS (alice) instance:

```
imkdir ExternalColl
globus-url-copy gsiftp://di4r2016-2.novalocal/tmp/File000.txt gsiftp://di4r2016-3.novalocal/aliceZone/home/alice/ExternalColl/File000.txt

ils ExternalColl
```

### Remarks

What is a third party transfer? A third party transfers is a transfer between two remote servers.

# What have we learned?
- We can use iRODS to upload, manage and annotate data
- We can steer dataflows between iRODS instances with the iRODS native icommands
- We can steer data between our laptop/userinterface and iRODS with gridFTP
- We can execute third party transfers with gridFTP between a gridFTP enabled iRODS server and a 'normal' gridFTP server


text:
layout: page
title: Send your old stuff to us
permalink: /material_submission/
redirect_from: /node/30/
---

Yotsuba Society is there for the study and preservation of the Western imageboard culture. How are we not a society if we don't have old stuff to preserve for future generations? Anyway if you have any of the following from 4chan or any other imageboard or textboard like:

* Any and all saved threads and images
* IRC chatlogs from any imageboards/textboard channel
* Legendary, historic or notable, pictures and/or screencaps
* Any other notable material if related to the culture.

In particular, we are looking for material, images, and threads that dates back between October 2003 to late 2007 from boards other than /b/.

Send them to `yotsubasocietycontact [at] gmail.com` Please send any thread and picture packages as zip files, and please do not send us any threads that contain material that is illegal under US Federal or State law such as child porn, bestiality, or jailbait.


text:
package org.pac4j.core.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import junit.framework.TestCase;

import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.context.MockWebContext;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.Credentials;
import org.pac4j.core.kryo.ColorSerializer;
import org.pac4j.core.kryo.FormattedDateSerializer;
import org.pac4j.core.kryo.LocaleSerializer;
import org.pac4j.core.profile.Color;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.FormattedDate;
import org.pac4j.core.profile.Gender;
import org.pac4j.core.profile.ProfileHelper;
import org.pac4j.core.profile.UserProfile;
import org.pac4j.core.util.TestsConstants;
import org.pac4j.core.util.TestsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esotericsoftware.kryo.Kryo;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is the generic test case for client.
 *
 * @author Jerome Leleu
 * @since 1.1.0
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class ClientIT extends TestCase implements TestsConstants {

    protected static final Logger logger = LoggerFactory.getLogger(ClientIT.class);

    protected abstract Mechanism getMechanism();

    public void testMechanism() {
        final BaseClient client = (BaseClient) getClient();
        assertEquals(getMechanism(), client.getMechanism());
    }

    public void testMissingCallbackUrl() {
        final IndirectClient client = (IndirectClient) getClient();
        client.setCallbackUrl(null);
        TestsHelper.initShouldFail(client, "callbackUrl cannot be blank");
    }

    protected IndirectClient internalTestClone(final IndirectClient oldClient) {
        oldClient.setCallbackUrl(CALLBACK_URL);
        final IndirectClient client = (IndirectClient) oldClient.clone();
        assertEquals(oldClient.getCallbackUrl(), client.getCallbackUrl());
        assertEquals(oldClient.getName(), client.getName());
        return client;
    }

    public void testAuthenticationAndUserProfileRetrieval() throws Exception {
        ProfileHelper.setKeepRawData(true);
        try {
            final Client client = getClient();

            final J2EContext context = getJ2EContext();
            final WebClient webClient = TestsHelper.newWebClient(isJavascriptEnabled());

            final HtmlPage redirectionPage = getRedirectionPage(webClient, client, context);

            updateContextForAuthn(webClient, redirectionPage, context);

            final UserProfile profile = getCredentialsAndProfile(client, context);

            verifyProfile(profile);

            // Java serialization
            byte[] bytes = TestsHelper.serialize(profile);
            final UserProfile profile2 = (UserProfile) TestsHelper.unserialize(bytes);
            verifyProfile(profile2);

            // like CAS serialization
            final Map<String, Object> attributes = profile2.getAttributes();
            final Map<String, Object> newAttributes = new HashMap<String, Object>();
            for (final String key : attributes.keySet()) {
                newAttributes.put(key, attributes.get(key).toString());
            }
            final UserProfile profile3 = ProfileHelper.buildProfile(profile2.getTypedId(), newAttributes);
            verifyProfile(profile3);

            // Kryo serialization
            final Kryo kryo = new Kryo();
            kryo.register(HashMap.class);
            kryo.register(Locale.class, new LocaleSerializer());
            kryo.register(Date.class);
            kryo.register(FormattedDate.class, new FormattedDateSerializer());
            kryo.register(Gender.class);
            kryo.register(Color.class, new ColorSerializer());
            kryo.register(ArrayList.class);
            registerForKryo(kryo);
            bytes = TestsHelper.serializeKryo(kryo, profile);
            final UserProfile profile4 = (UserProfile) TestsHelper.unserializeKryo(kryo, bytes);
            verifyProfile(profile4);
        } finally {
            ProfileHelper.setKeepRawData(false);
        }
    }

    protected J2EContext getJ2EContext() {
        return new J2EContext(getHttpServletRequest(), getHttpServletResponse());
    }

    protected HttpServletRequest getHttpServletRequest() {
        return new MockHttpServletRequest();
    }

    protected HttpServletResponse getHttpServletResponse() {
        return new MockHttpServletResponse();
    }

    // Default implementation use getCallbackUrl method
    protected void updateContextForAuthn(WebClient webClient, HtmlPage redirectionPage, J2EContext context)
            throws Exception {
        final String callbackUrl = getCallbackUrl(webClient, redirectionPage);
        final MockHttpServletRequest request = (MockHttpServletRequest) context.getRequest();
        request.addParameters(TestsHelper.getParametersFromUrl(callbackUrl));
    }

    protected void registerForKryo(final Kryo kryo) {
    }

    protected boolean isJavascriptEnabled() {
        return false;
    }

    protected abstract Client getClient();

    protected HtmlPage getRedirectionPage(final WebClient webClient, final Client<?, ?> client, final J2EContext context)
            throws Exception {
        final BaseClient baseClient = (BaseClient) client;
        // force immediate redirection for tests
        baseClient.redirect(context, true, false);
        final String redirectionUrl = context.getResponse().getHeader(HttpConstants.LOCATION_HEADER);
        logger.debug("redirectionUrl : {}", redirectionUrl);
        final HtmlPage loginPage = webClient.getPage(redirectionUrl);
        return loginPage;
    }

    protected abstract String getCallbackUrl(final WebClient webClient, HtmlPage authorizationPage) throws Exception;

    protected UserProfile getCredentialsAndProfile(final Client client, final WebContext context) throws Exception {

        final Credentials credentials = client.getCredentials(context);
        logger.debug("credentials : {}", credentials);

        final UserProfile profile = client.getUserProfile(credentials, context);
        return profile;
    }

    protected abstract void verifyProfile(UserProfile userProfile);

    protected void assertCommonProfile(final UserProfile userProfile, final String email, final String firstName,
            final String familyName, final String displayName, final String username, final Gender gender,
            final Locale locale, final String pictureUrl, final String profileUrl, final String location) {
        final CommonProfile profile = (CommonProfile) userProfile;
        assertEquals(email, profile.getEmail());
        assertEquals(firstName, profile.getFirstName());
        assertEquals(familyName, profile.getFamilyName());
        assertEquals(displayName, profile.getDisplayName());
        assertEquals(username, profile.getUsername());
        assertEquals(gender, profile.getGender());
        assertEquals(locale, profile.getLocale());
        if (pictureUrl == null) {
            assertNull(profile.getPictureUrl());
        } else {
            assertTrue(profile.getPictureUrl().contains(pictureUrl));
        }
        if (profileUrl == null) {
            assertNull(profile.getProfileUrl());
        } else {
            final String profUrl = profile.getProfileUrl();
            assertTrue(profUrl.startsWith(profileUrl));
        }
        assertEquals(location, profile.getLocation());
    }

    protected boolean isCancellable() {
        return false;
    }

    public void testCancelAuthentication() throws Exception {
        if (isCancellable()) {
            final Client client = getClient();

            final J2EContext context = getJ2EContext();
            final WebClient webClient = TestsHelper.newWebClient(isJavascriptEnabled());

            final HtmlPage redirectionPage = getRedirectionPage(webClient, client, context);

            updateContextForCancel(redirectionPage, context);

            final UserProfile profile = getCredentialsAndProfile(client, context);

            assertNull(profile);
        }
    }

    protected void updateContextForCancel(HtmlPage redirectionPage, WebContext context) throws Exception {
        final String callbackUrl = getCallbackUrlForCancel(redirectionPage);
        final MockWebContext mockWebContext = (MockWebContext) context;
        mockWebContext.addRequestParameters(TestsHelper.getParametersFromUrl(callbackUrl));
    }

    protected String getCallbackUrlForCancel(final HtmlPage authorizationPage) throws Exception {
        throw new IllegalArgumentException("To be implemented");
    }
}


text:
'use strict';

const common = require('../common');
const assert = require('assert');

if (!common.hasCrypto) {
  common.skip('missing crypto');
  return;
}
const tls = require('tls');
const fs = require('fs');
const util = require('util');

const sent = 'hello world';
const serverOptions = {
  isServer: true,
  key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
  cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
};

let ssl = null;

process.on('exit', function() {
  assert.ok(ssl !== null);
  // If the internal pointer to stream_ isn't cleared properly then this
  // will abort.
  util.inspect(ssl);
});

const server = tls.createServer(serverOptions, function(s) {
  s.on('data', function() { });
  s.on('end', function() {
    server.close();
    s.destroy();
  });
}).listen(0, function() {
  const c = new tls.TLSSocket();
  ssl = c.ssl;
  c.connect(this.address().port, function() {
    c.end(sent);
  });
});


text:
This contains snippets used in the NDB queries documentation, demonstrating
various ways to make ndb queries.

<!-- auto-doc-link -->
These samples are used on the following documentation page:

> https://cloud.google.com/appengine/docs/python/ndb/queries

<!-- end-auto-doc-link -->


text:
from django.db.models import Q
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_GET, require_POST
from django.shortcuts import render
from django.http import HttpResponse

from api.accounts.user.utils import ExcludeInternalUsers
from gui.models.permission import UserAdminPermission
from gui.models.user import User
from gui.decorators import ajax_required, staff_required, admin_required, profile_required, permission_required
from gui.utils import get_boolean_value, collect_view_data, reverse, redirect, get_query_string
from gui.dc.user.utils import get_edited_user
from gui.dc.user.forms import AdminUserForm, AdminUserModalForm, AdminUserProfileForm, AdminChangePasswordForm
from gui.profile.forms import SSHKeyForm

class AllIn(set):
    """Universal set - match everything"""
    def __contains__(self, item):
        return True

@login_required
@admin_required
@profile_required
def dc_user_list(request):
    """
    User -> Dc group management.
    """
    user, dc = request.user, request.dc
    users = User.objects.order_by('username').filter(ExcludeInternalUsers)
    context = collect_view_data(request, 'dc_user_list')
    context['is_staff'] = is_staff = user.is_staff
    context['can_edit'] = can_edit = is_staff or user.has_permission(request, UserAdminPermission.name)
    context['all'] = _all = can_edit and request.GET.get('all', False)
    context['active'] = _active = not (can_edit and request.GET.get('inactive', False))
    context['qs'] = qs = get_query_string(request, all=_all, inactive=_active).urlencode()

    if _all or dc.access == dc.PUBLIC:
        if _all:
            pr = ('roles', 'roles__dc_set')
        else:
            pr = ('roles',)

        context['users'] = users.select_related('dc_bound').filter(is_active=_active).prefetch_related(*pr)

        if dc.access == dc.PUBLIC:
            context['dc_users'] = AllIn()
        else:
            # Uses set() because of optimized membership ("in") checking
            context['dc_users'] = set(users.filter((Q(id=dc.owner.id) | Q(roles__in=dc.roles.all())))
                                           .values_list('pk', flat=True))
    else:
        context['users'] = users.select_related('dc_bound')\
                                .filter(is_active=_active)\
                                .filter(Q(id=dc.owner.id) | Q(roles__in=dc.roles.all()) | Q(dc_bound=dc))\
                                .prefetch_related('roles').distinct()

    if can_edit:
        context['url_form_admin'] = reverse('dc_user_modal_form', query_string=qs)
        context['form_admin'] = AdminUserModalForm(request, None, prefix='adm', initial={'dc_bound': not is_staff,
                                                                                'is_active': True})

    return render(request, 'gui/dc/user_list.html', context)

@login_required
@admin_required  # SuperAdmin or DCAdmin+UserAdmin
@permission_required(UserAdminPermission)
@ajax_required
@require_POST
def dc_user_modal_form(request):
    """
    Ajax page for updating, removing and adding user.
    """
    qs = request.GET.copy()

    if request.POST['action'] == 'update':
        user = get_edited_user(request, request.POST['adm-username'])
    else:
        user = None

    form = AdminUserModalForm(request, user, request.POST, prefix='adm')

    if form.is_valid():
        args = (form.cleaned_data['username'],)
        status = form.save(args=args)

        if status == 204:
            return HttpResponse(None, status=status)
        elif status in (200, 201):
            if form.action == 'create':
                messages.success(request, _('User was successfully created'))
                return redirect('dc_user_profile', username=form.cleaned_data['username'])
            else:
                messages.success(request, _('User profile was successfully updated'))
                redirect_to = 'dc_user_list'

                if user:
                    user = user.__class__.objects.get(pk=user.pk)  # Reload user object from DB (modified in API)
                    # You can modify yourself and lose access to /dc - Issue #108
                    if request.user == user and not user.is_admin(dc=request.dc):
                        redirect_to = '/'

                return redirect(redirect_to, query_string=qs)

    return render(request, 'gui/dc/user_dc_form.html', {'form': form})

@login_required
@admin_required  # SuperAdmin or DCAdmin+UserAdmin
@permission_required(UserAdminPermission)
@profile_required
def dc_user_profile(request, username):
    """
    User Profile management.
    """
    user = get_edited_user(request, username, sr=('dc_bound', 'userprofile'))
    profile = user.userprofile
    context = collect_view_data(request, 'dc_user_list')
    context['uform'] = AdminUserForm(request, user, init=True)
    context['upform'] = AdminUserProfileForm(request, profile, init=True)
    context['pform'] = AdminChangePasswordForm(user)
    context['sform'] = SSHKeyForm(request, user)
    context['user'] = user
    context['profile'] = profile
    context['ssh_keys'] = user.usersshkey_set.all().order_by('id')
    if not request.user.is_staff:
        context['disabled_api_key'] = True

    return render(request, 'gui/dc/profile/user_profile.html', context)

@login_required
@admin_required  # SuperAdmin or DCAdmin+UserAdmin
@permission_required(UserAdminPermission)
@ajax_required
@require_POST
def dc_user_profile_form(request, username):
    """
    Ajax page for updating user profile.
    """
    user = get_edited_user(request, username, sr=('dc_bound', 'userprofile'))
    profile = user.userprofile

    if request.POST['action'] == 'update':
        uform = AdminUserForm(request, user, request.POST)
        upform = AdminUserProfileForm(request, profile, request.POST)

        if uform.is_valid() and upform.is_valid():  # The real validation is not happening here but below
            args = (uform.cleaned_data['username'],)
            # The validation happens in these two forms and they inform about the result which we process.
            # However, if upform save fails, uform is saved already and we cannot do anything about that.
            # FIXME bad design here and in gui.profile.views.update
            ustatus = uform.save(action='update', args=args)
            upstatus = upform.save(action='update', args=args)

            if (ustatus == 200 and upstatus in (200, 204)) or (upstatus == 200 and ustatus in (200, 204)):
                messages.success(request, _('User profile was successfully updated'))
                user = user.__class__.objects.get(pk=user.pk)  # Reload user object from DB (modified in API)
                # You can modify yourself and lose access to /dc - Issue #108
                if request.user == user and not user.is_admin(dc=request.dc):
                    redirect_to = '/'
                else:
                    redirect_to = 'dc_user_list'

                return redirect(redirect_to)

    else:
        uform = AdminUserForm(request, user, init=True)
        upform = AdminUserProfileForm(request, profile, init=True)

    context = {
        'uform': uform,
        'upform': upform,
        'user': user,
        'profile': profile,
        'ssh_keys': user.usersshkey_set.all().order_by('id'),
    }

    if not request.user.is_staff:
        context['disabled_api_key'] = True

    return render(request, 'gui/dc/profile/profile_page.html', context)

@login_required
@admin_required  # SuperAdmin or DCAdmin+UserAdmin
@permission_required(UserAdminPermission)
@ajax_required
@require_POST
@transaction.atomic
def dc_user_profile_password_modal_form(request, username):
    """
    Ajax page for changing user password.
    """
    user = get_edited_user(request, username)
    status = 200
    pform = AdminChangePasswordForm(user, request.POST)

    if pform.is_valid():
        status = pform.save(request)
        if status == 200:
            messages.success(request, _('User password was successfully changed'))
            return redirect('dc_user_profile', user.username)

    return render(request, 'gui/dc/profile/profile_password_form.html', {
        'user': user,
        'pform': pform,
    }, status=status)

@login_required
@staff_required  # SuperAdmin
@ajax_required
@require_GET
def dc_user_profile_apikeys(request, username):
    """
    Ajax page for displaying API keys.
    """
    user = get_edited_user(request, username)
    display = get_boolean_value(request.GET.get('display', False))

    return render(request, 'gui/profile/profile_api_keys_list.html', {
        'user': user,
        'display_keys': display
    })

@login_required
@admin_required  # SuperAdmin or DCAdmin+UserAdmin
@permission_required(UserAdminPermission)
@ajax_required
@require_POST
@transaction.atomic
def dc_user_profile_sshkey_modal_form(request, username, action):
    """
    Ajax page for adding or deleting SSH keys.
    """
    user = get_edited_user(request, username)

    if action == 'add':
        sform = SSHKeyForm(request, None, request.POST)
        if sform.is_valid():
            status = sform.save(action='create', args=(user.username, sform.cleaned_data['name']))
            if status == 201:
                messages.success(request, _('SSH key was successfully saved'))
                return redirect('dc_user_profile', user.username)

        return render(request, 'gui/profile/profile_sshkey_form.html', {
            'user': user,
            'sform': sform
        }, status=200)

    elif action == 'delete':
        res = SSHKeyForm.api_call('delete', None, request, args=(user.username, request.POST.get('name')))
        status = res.status_code
        if status == 200:
            messages.success(request, _('SSH key was successfully removed'))
            return redirect('dc_user_profile', user.username)

        return render(request, 'gui/profile/profile_sshkey_list.html', {
            'user': user,
            'ssh_keys': user.usersshkey_set.all().order_by('id')
        }, status=status)


text:
<!doctype html>
<title>img wide.jpg; overflow:hidden; -o-object-fit:none; -o-object-position:top right</title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='hidden_none_top_right-ref.html'>


text:
<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
	<input class="search-input" type="search" name="s" placeholder="<?php _e( 'To search, type and hit enter.', 'html5blank' ); ?>">
	<button class="search-submit" type="submit" role="button"></button>
</form>


text:
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <cmath>

#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/numerics/math_constants.h"
#include "base/test/task_environment.h"
#include "services/device/generic_sensor/fake_platform_sensor_fusion.h"
#include "services/device/generic_sensor/relative_orientation_euler_angles_fusion_algorithm_using_accelerometer.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace device {

namespace {

class RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest
    : public testing::Test {
 public:
  RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest() {
    auto fusion_algorithm = std::make_unique<
        RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>();
    fusion_algorithm_ = fusion_algorithm.get();
    fake_fusion_sensor_ = base::MakeRefCounted<FakePlatformSensorFusion>(
        std::move(fusion_algorithm));
    fusion_algorithm_->set_fusion_sensor(fake_fusion_sensor_.get());
    EXPECT_EQ(1UL, fusion_algorithm_->source_types().size());
  }

  void VerifyRelativeOrientationEulerAngles(double acceleration_x,
                                            double acceleration_y,
                                            double acceleration_z,
                                            double expected_beta_in_degrees,
                                            double expected_gamma_in_degrees) {
    SensorReading reading;
    reading.accel.x = acceleration_x;
    reading.accel.y = acceleration_y;
    reading.accel.z = acceleration_z;

    fake_fusion_sensor_->SetSensorReading(mojom::SensorType::ACCELEROMETER,
                                          reading,
                                          true /* sensor_reading_success */);

    SensorReading fused_reading;
    EXPECT_TRUE(fusion_algorithm_->GetFusedData(
        mojom::SensorType::ACCELEROMETER, &fused_reading));

    EXPECT_TRUE(
        std::isnan(fused_reading.orientation_euler.z.value() /* alpha */));
    EXPECT_DOUBLE_EQ(expected_beta_in_degrees,
                     fused_reading.orientation_euler.x /* beta */);
    EXPECT_DOUBLE_EQ(expected_gamma_in_degrees,
                     fused_reading.orientation_euler.y /* gamma */);
  }

 protected:
  base::test::TaskEnvironment task_environment_;
  scoped_refptr<FakePlatformSensorFusion> fake_fusion_sensor_;
  raw_ptr<RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>
      fusion_algorithm_;
};

}  // namespace

TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       NoAccelerometerReading) {
  SensorReading reading;
  fake_fusion_sensor_->SetSensorReading(mojom::SensorType::ACCELEROMETER,
                                        reading,
                                        false /* sensor_reading_success */);
  SensorReading fused_reading;
  EXPECT_FALSE(fusion_algorithm_->GetFusedData(mojom::SensorType::ACCELEROMETER,
                                               &fused_reading));
}

// Tests a device resting flat.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       NeutralOrientation) {
  double acceleration_x = 0.0;
  double acceleration_y = 0.0;
  double acceleration_z = base::kMeanGravityDouble;

  double expected_beta_in_degrees = 0.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests an upside-down device, such that the W3C boundary [-180, 180) causes
// the beta value to become negative.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       UpsideDown) {
  double acceleration_x = 0.0;
  double acceleration_y = 0.0;
  double acceleration_z = -base::kMeanGravityDouble;

  double expected_beta_in_degrees = -180.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests for positive beta value before the device is completely upside-down.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       BeforeUpsideDownBoundary) {
  double acceleration_x = 0.0;
  double acceleration_y = -base::kMeanGravityDouble / 2.0;
  double acceleration_z = -base::kMeanGravityDouble / 2.0;

  double expected_beta_in_degrees = 135.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests a device lying on its top-edge.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       TopEdge) {
  double acceleration_x = 0.0;
  double acceleration_y = base::kMeanGravityDouble;
  double acceleration_z = 0.0;

  double expected_beta_in_degrees = -90.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests before a device is completely on its top-edge.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       BeforeTopEdgeBoundary) {
  double acceleration_x = 0.0;
  double acceleration_y = base::kMeanGravityDouble / 2.0;
  double acceleration_z = base::kMeanGravityDouble / 2.0;

  double expected_beta_in_degrees = -45.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests a device lying on its bottom-edge.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       BottomEdge) {
  double acceleration_x = 0.0;
  double acceleration_y = -base::kMeanGravityDouble;
  double acceleration_z = 0.0;

  double expected_beta_in_degrees = 90.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests before a device is completely on its bottom-edge.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       BeforeBottomEdgeBoundary) {
  double acceleration_x = 0.0;
  double acceleration_y = -base::kMeanGravityDouble / 2.0;
  double acceleration_z = base::kMeanGravityDouble / 2.0;

  double expected_beta_in_degrees = 45.0;
  double expected_gamma_in_degrees = 0.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests a device lying on its left-edge.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       LeftEdge) {
  double acceleration_x = -base::kMeanGravityDouble;
  double acceleration_y = 0.0;
  double acceleration_z = 0.0;

  double expected_beta_in_degrees = 0.0;
  double expected_gamma_in_degrees = -90.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests for negative gamma value before the device is completely on its left
// side.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       BeforeLeftEdgeBoundary) {
  double acceleration_x = -base::kMeanGravityDouble / std::sqrt(2.0);
  double acceleration_y = 0.0;
  double acceleration_z = base::kMeanGravityDouble / std::sqrt(2.0);

  double expected_beta_in_degrees = 0.0;
  double expected_gamma_in_degrees = -45.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests a device lying on its right-edge, such that the W3C boundary [-90, 90)
// causes the gamma value to become negative.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       RightEdge) {
  double acceleration_x = base::kMeanGravityDouble;
  double acceleration_y = 0.0;
  double acceleration_z = 0.0;

  double expected_beta_in_degrees = 0.0;
  double expected_gamma_in_degrees = -90.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

// Tests for positive gamma value before the device is completely on its right
// side.
TEST_F(RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometerTest,
       BeforeRightEdgeBoundary) {
  double acceleration_x = base::kMeanGravityDouble / std::sqrt(2.0);
  double acceleration_y = 0.0;
  double acceleration_z = base::kMeanGravityDouble / std::sqrt(2.0);

  double expected_beta_in_degrees = 0.0;
  double expected_gamma_in_degrees = 45.0;

  VerifyRelativeOrientationEulerAngles(acceleration_x, acceleration_y,
                                       acceleration_z, expected_beta_in_degrees,
                                       expected_gamma_in_degrees);
}

}  // namespace device


text:
/* eslint-env node, mocha */
import { assert } from 'assertive-chai';
import { parse } from '../src/browsers';

describe('parse', function() {

  it('should correctly parse id=foo', function () {
    const rule = parse('id=foo');
    assert.lengthOf(rule.identifiers, 1);
    assert.equal(rule.identifiers[0].property, 'id');
    assert.equal(rule.identifiers[0].value, 'foo');
  });

  it('should correctly parse id=foo;cl=bar', function () {
    const rule = parse('id=foo;cl=bar');
    assert.lengthOf(rule.identifiers, 2);
    assert.equal(rule.identifiers[0].property, 'id');
    assert.equal(rule.identifiers[0].value, 'foo');
    assert.equal(rule.identifiers[1].property, 'cl');
    assert.equal(rule.identifiers[1].value, 'bar');
  });

  it('should correctly parse id=fo=o', function () {
    const rule = parse('id=fo=o');
    assert.lengthOf(rule.identifiers, 1);
    assert.equal(rule.identifiers[0].property, 'id');
    assert.equal(rule.identifiers[0].value, 'fo=o');
  });

  it('should correctly parse id=', function () {
    const rule = parse('id=');
    assert.lengthOf(rule.identifiers, 1);
    assert.equal(rule.identifiers[0].property, 'id');
    assert.equal(rule.identifiers[0].value, '');
  });

  it('should return null on non-string', function () {
    const rule = parse([]);
    assert.equal(rule, null);
  });

  it('should return null on empty string', function () {
    const rule = parse([]);
    assert.equal(rule, null);
  });

});


text:
$packageName = 'partitionwizard'
$installerType = 'exe'
$silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
$url = 'http://www.partitionwizard.com/download/pwfree9.exe'
$checksum = '8d344e46d2317184afdacc90d8f10618ba1df511'
$checksumType = 'sha1'
$validExitCodes = @(0)
Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
    <% if (!appId || !operatorId || !startTime) { %>
    <div class="tuple loading" style="padding:<%= tuplePaddingTB %>px 0; margin-bottom:<%= tupleMarginBtm %>px"> no recording found

    <% } else if (totalTuples == '0') { %>
    <div class="tuple loading" style="padding:<%= tuplePaddingTB %>px 0; margin-bottom:<%= tupleMarginBtm %>px"> no tuples in this recording

    <% } else if (currentTotal == '0') { %>
    <div class="tuple loading" style="padding:<%= tuplePaddingTB %>px 0; margin-bottom:<%= tupleMarginBtm %>px"> no tuples for selected ports

    <% }%>


text:
@import Foundation;

//! Project version number for VntripFramework.
FOUNDATION_EXPORT double VntripFrameworkVersionNumber;

//! Project version string for VntripFramework.
FOUNDATION_EXPORT const unsigned char VntripFrameworkVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <VntripFramework/PublicHeader.h>


text:
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.7 FATAL_ERROR)

FUNCTION(MLI_SET_DEPTH level)
  SET(dirs)
  SET(dir ${CMAKE_SOURCE_DIR})
  SET(relinc)
  FOREACH(i RANGE 1 ${level})
    GET_FILENAME_COMPONENT(bn ${dir} NAME)
    GET_FILENAME_COMPONENT(dir ${dir} PATH)
    LIST(APPEND dirs ${bn})
    SET(relinc "${relinc}/..")
  ENDFOREACH()
  LIST(REVERSE dirs)
  STRING(REPLACE ";" "/" relpath "${dirs}")
  SET(MLI_INCLUDE_OUTPUT_DIR
    "${CMAKE_BINARY_DIR}/${relpath}"
    PARENT_SCOPE)
  SET(MLI_INCLUDE_RELATIVE_OUTPUT_DIR
    "${relpath}"
    PARENT_SCOPE)
  INCLUDE_DIRECTORIES(
    "${CMAKE_SOURCE_DIR}/${relinc}"
    "${CMAKE_BINARY_DIR}")
ENDFUNCTION()


text:
<?php $TRANSLATIONS = array(
"Contacts" => "Stiki",
"Save" => "Shrani",
"Uploading..." => "Poteka pošiljanje ...",
"Importing..." => "Uvažanje ...",
"Preparing..." => "Poteka pripravljanje ...",
"Imported {count} of {total} contacts" => "Uvoženih je {count} od skupno {total} stikov",
"Imported {imported} contacts. {failed} failed." => "Uspešno je uvoženih {imported} stikov, {failed} je izpuščenih.",
"An address book called {name} already exists" => "Imenik z imenom {name} že obstaja",
"Failed adding address book: {error}" => "Dodajanje imenika je spodletelo: {error}",
"Failed loading address books: {error}" => "Nalaganje imenikov je spodletelo: {error}",
"Indexing contacts" => "Ustvarjanje seznama stikov",
"Unrecoverable error loading address books: {msg}" => "Prišlo je do nepopravljive napake med nalaganjem imenikov: {msg}",
"Error." => "Napaka",
"Add to..." => "Dodaj v ...",
"Remove from..." => "Odstrani iz ...",
"Add group..." => "Dodaj skupino ...",
"Invalid URL: \"{url}\"" => "Neveljaven naslov URL: \"{url}\"",
"There was an error opening a mail composer." => "Med odpiranjem sestavljalnika pošte je prišlo do napake.",
"Invalid email: \"{url}\"" => "Neveljaven elektronski naslov: \"{url}\"",
"Merge failed. Cannot find contact: {id}" => "Združevanje je spodletelo. Stika ni mogoče najti: {id}",
"Merge failed." => "Združevanje je spodletelo.",
"Merge failed. Error saving contact." => "Združevanje je spodletelo. Prišlo je do napake med shranjevanjem stika.",
"Select photo" => "Izbor slike",
"Network or server error. Please inform administrator." => "Napaka omrežja ali strežnika. Pošljite obvestilo skrbniku sistema.",
"Error adding to group." => "Napaka med dodajanjem stika v skupino.",
"Error removing from group." => "Napaka med odstranjevanjem stika iz skupino.",
"Error setting {name} as favorite." => "Napaka med nastavljanjem {name} kot priljubljenega.",
"Merge contacts" => "Združi stike",
"Cancel" => "Prekliči",
"Add group" => "Dodaj skupino",
"OK" => "V redu",
"Could not find contact: {id}" => "Stika ni mogoče najti: {id}",
"No files selected for upload." => "Ni izbrane datoteke za pošiljanje.",
"The file you are trying to upload exceed the maximum size for file uploads on this server." => "Datoteka, ki jo poskušate naložiti, presega dovoljeno velikost za pošiljanje na ta strežnik.",
"Edit profile picture" => "Uredi fotografijo profila",
"Crop photo" => "Obreži sliko",
"Is this correct?" => "Ali je to pravilno?",
"Error parsing date: {date}" => "Napaka razčlenjevanja datuma: {date}",
"# groups" => "# skupine",
"Error parsing birthday {bday}: {error}" => "Napaka razčlenjevanja datuma rojstva {bday}: {error}",
"Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted." => "Nekateri stiki so označeni za izbris, vendar še niso izbrisani. Počakajte na dokončanje opravila.",
"Click to undo deletion of {num} contacts" => "S klikom bodo povrnjeni izbrisani stiki ({num})",
"Cancelled deletion of {num} contacts" => "Preklican izbris {num} stikov",
"Add" => "Dodaj",
"Contact is already in this group." => "Stik je že v tej skupini.",
"Contacts are already in this group." => "Stiki so že v tej skupini.",
"Couldn't get contact list." => "Ni mogoče pridobiti seznama stikov.",
"Contact is not in this group." => "Stik ni v tej skupini.",
"Contacts are not in this group." => "Stiki niso v tej skupini.",
"Failed renaming group: {error}" => "Napaka preimenovanja skupine: {error}",
"A group named {group} already exists" => "Skupina z imenom {group} že obstaja.",
"You can drag groups to\narrange them as you like." => "Skupine je mogoče\nrazvrščati po meri.",
"Failed adding group: {error}" => "Dodajanje skupine je spodletelo: {error}",
"All" => "Vsi",
"Favorites" => "Priljubljeni",
"Shared by {owner}" => "Souporabo omogoča {owner}",
"Not grouped" => "Brez skupine",
"Failed loading groups: {error}" => "Nalaganje skupin je spodletelo: {error}",
"Please choose the addressbook" => "Izberite imenik",
"Import into..." => "Uvozi v ...",
"Error loading import template" => "Napaka nalaganja predloge uvoza",
"Import contacts" => "Uvozi stike",
"Import" => "Uvozi",
"Import done" => "Uvoz je končan",
"Close" => "Zapri",
"Error" => "Napaka",
"Displayname cannot be empty." => "Prikazno ime ne sme biti prazno.",
"Show CardDav link" => "Pokaži povezavo CardDav",
"Show read-only VCF link" => "Pokaži povezavo VCF samo za branje",
"Download" => "Prejmi",
"Edit" => "Uredi",
"Delete" => "Izbriši",
"More..." => "Več ...",
"Less..." => "Manj ...",
"Server error! Please inform system administator" => "Napaka strežnika! Stopite v stik s skrbnikom sistema.",
"Failed loading photo: {error}" => "Nalaganje slike je spodletelo: {error}",
"You do not have permissions to see this contacts" => "Ni ustreznih dovoljenj za ogled teh stikov.",
"Contact not found" => "Stika ni mogoče najti",
"You do not have permissions to see these contacts" => "Ni ustreznih dovoljenj za ogled teh stikov.",
"You do not have permissions add contacts to the address book" => "Ni ustreznih dovoljenj za dodajanje stikov v imenik.",
"The backend for this address book does not support adding contacts" => "Zaledje tega imenika ne omogoča dodajanja stikov.",
"You do not have permissions to delete this contact" => "Ni ustreznih dovoljenj za brisanje tega stika",
"The backend for this address book does not support deleting contacts" => "Zaledje tega imenika ne omogoča brisanje stikov",
"Unknown error" => "Neznana napaka",
"The backend for this address book does not support updating" => "Zaledje tega imenika ne omogoča posodobitev",
"You don't have permissions to update the address book." => "Ni ustreznih dovoljenj za posodobitev imenika.",
"You don't have permissions to delete the address book." => "Ni ustreznih dovoljenj za brisanje imenika.",
"Address book not found" => "Imenika ni mogoče najti",
"You do not have permissions to see this contact" => "Ni ustreznih dovoljenj za ogled tega stika",
"You do not have permissions to update this contact" => "Ni ustreznih dovoljenj za posodabljanje tega stika",
"The backend for this contact does not support updating it" => "Hrbtišče stika ne omogoča posodabljanja podatkov",
"This backend not support adding contacts" => "Hrbtišče ne podpira dodajanja stikov",
"Property not found" => "Lastnosti ni mogoče najti",
" Missing IM parameter for: " => "Manjka parameter IM za:",
"Unknown IM: " => "Neznan IM:",
"{name}'s Birthday" => "{name} - rojstni dan",
"Error creating address book" => "Napaka med ustvarjanjem imenika",
"Error updating address book" => "Napaka med posodabljanjem imenika",
"You do not have permissions to delete the \"%s\" address book" => "Ni ustreznih dovoljenj za brisanje imenika \"%s\"",
"Error deleting address book" => "Napaka med brisanjem imenika",
"Error creating contact." => "Napaka med ustvarjanjem stika.",
"Error deleting contact." => "Napaka med brisanjem stika.",
"Error retrieving contact." => "Napaka med pridobivanjem stika.",
"Error saving contact." => "Napaka med shranjevanjem stika.",
"Error removing contact from other address book." => "Prišlo je do napake med odstranjevanjem stika iz drugega imenika.",
"Couldn't find contact." => "Stika ni mogoče najti.",
"No contact data in request." => "Ni zahtevanih podatkov stika.",
"Error merging into contact." => "Napaka med združevanjem v stik.",
"Error saving contact to backend." => "Napaka shranjevanja stika.",
"Property name is not set." => "Ime lastnosti ni nastavljeno.",
"Property checksum is not set." => "Lastnost nadzorne vsote ni nastavljena.",
"Information about vCard is incorrect. Please reload the page." => "Podrobnosti kartice vCard niso pravilne. Ponovno naložite stran.",
"Error updating contact" => "Napaka posodabljanja stika",
"Error saving contact to backend" => "Napaka shranjevanja stika v hrbtišče sistema",
"Error getting user photo" => "Napaka pridobivanja fotografije uporabnika",
"No file was uploaded. Unknown error" => "Ni poslane datoteke. Neznana napaka.",
"There is no error, the file uploaded with success" => "Datoteka je uspešno naložena.",
"The uploaded file exceeds the upload_max_filesize directive in php.ini" => "Naložena datoteka presega velikost, ki jo določa parameter upload_max_filesize v datoteki php.ini",
"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" => "Poslana datoteka presega velikost, ki jo določa parameter največje dovoljene velikosti v obrazcu HTML.",
"The uploaded file was only partially uploaded" => "Poslan je le del datoteke.",
"No file was uploaded" => "Ni poslane datoteke",
"Missing a temporary folder" => "Manjka začasna mapa",
"Couldn't load temporary image: " => "Začasne slike ni mogoče naložiti: ",
"Couldn't save temporary image: " => "Začasne slike ni mogoče shraniti: ",
"No photo path was submitted." => "Pot slike ni poslana.",
"File doesn't exist:" => "Datoteka ne obstaja:",
"Error loading image." => "Napaka med nalaganjem slike.",
"Image has been removed from cache" => "Slika je odstranjena iz predpomnilnika",
"Error creating temporary image" => "Napaka med ustvarjanjem začasne slike",
"Error cropping image" => "Napaka med obrezovanjem slike",
"Error resizing image" => "Napaka med spreminjanjem velikosti slike",
"Error getting PHOTO property." => "Napaka med pridobivanjem lastnosti fotografije.",
"No group name given." => "Ni podanega imena skupine.",
"Error adding group." => "Napaka dodajanja skupine.",
"No group name to rename from given." => "Ni podanega imena skupine za preimenovanje.",
"No group name to rename to given." => "Ni imena skupine za preimenovanje podane.",
"Error renaming group." => "Napaka preimenovanja skupine.",
"Group ID missing from request." => "V zahtevi manjka ID skupine.",
"Group name missing from request." => "Ime skupine manjka iz zahteve.",
"Contact ID missing from request." => "V zahtevi manjka ID stika.",
"Failed to write to disk" => "Pisanje na disk je spodletelo",
"Not enough storage available" => "Na voljo ni dovolj prostora",
"Attempt to upload blacklisted file:" => "Poskus pošiljanja datoteke na črnem seznamu:",
"Error uploading contacts to storage." => "Napaka med nalaganjem stikov v hrambo.",
"Error moving file to imports folder." => "Napaka premikanja datoteke v mapo uvoza.",
"You do not have permissions to import into this address book." => "Ni ustreznih dovoljenj za uvoz v ta imenik.",
"File name missing from request." => "V zahtevi manjka ime datoteke.",
"Progress key missing from request." => "Ključ napredka manjka iz zahteve.",
"Attempt to access blacklisted file:" => "Poskus dostopa do datoteke na črnem seznamu:",
"No contacts found in: " => "Ni stikov v:",
"No key is given." => "Ni podanega ključa.",
"No value is given." => "Ni podane vrednosti.",
"Could not set preference: " => "Ni mogoče nastaviti lastnosti:",
"Contact" => "Stik",
"Other" => "Drugo",
"HomePage" => "Domača stran",
"Jabber" => "Jabber",
"Internet call" => "Internetni klic",
"AIM" => "AIM",
"MSN" => "MSN",
"Twitter" => "Twitter",
"GoogleTalk" => "GoogleTalk",
"Facebook" => "Facebook",
"XMPP" => "XMPP",
"ICQ" => "ICQ",
"Yahoo" => "Yahoo",
"Skype" => "Skype",
"QQ" => "QQ",
"GaduGadu" => "GaduGadu",
"Work" => "Služba",
"Home" => "Doma",
"Mobile" => "Mobilni telefon",
"Text" => "Besedilo",
"Voice" => "Glas",
"Message" => "Sporočilo",
"Fax" => "Faks",
"Video" => "Video",
"Pager" => "Pozivnik",
"Internet" => "Internet",
"Friends" => "Prijatelji",
"Family" => "Družina",
"New Contact" => "Nov stik",
"Group name" => "Ime skupine",
"New Group" => "Nova skupina",
"Address books" => "Imeniki",
"Display name" => "Ime za prikaz",
"Add Address Book" => "Dodaj imenik",
"Select file..." => "Izbor datoteke ...",
"(De-)select all" => "Preklopi izbor vsega",
"Sort order" => "Vrstni red razvrščanja",
"First- Lastname" => "Ime- Priimek",
"Last-, Firstname" => "Priimek-, Ime",
"Groups" => "Skupine",
"Favorite" => "Priljubljeno",
"Merge selected" => "Združi izbrano",
"Keyboard shortcuts" => "Tipkovne bližnjice",
"Navigation" => "Krmarjenje",
"Next contact in list" => "Naslednji stik na seznamu",
"Previous contact in list" => "Predhodni stik na seznamu",
"Expand/collapse current addressbook" => "Razširi/Zloži trenutni imenik",
"Next addressbook" => "Naslednji imenik",
"Previous addressbook" => "Predhodni imenik",
"Actions" => "Dejanja",
"Refresh contacts list" => "Osveži seznam stikov",
"Add new contact" => "Dodaj nov stik",
"Add new addressbook" => "Dodaj nov imenik",
"Delete current contact" => "Izbriši trenutni stik",
"
You have no contacts in your address book or your address book is disabled.

Add a new contact or import existing contacts from a VCF file.
" => "
Ali v imeniku ni stikov ali pa je imenik onemogočen.

Dodajte nov stik ali pa uvozite stike iz datoteke VCF.
",
"Add contact" => "Dodaj stik",
"Delete group" => "Izbriši skupino",
"Rename group" => "Preimenuj skupino",
"Which contact should the data be merged into?" => "S katerim stikom naj bodo podatki združeni?",
"Delete the other(s) after successful merge?" => "Ali naj bodo ostali izbrisani po uspešnem združevanju?",
"Compose mail" => "Sestavi sporočilo",
"Delete current photo" => "Izbriši trenutno sliko",
"Edit current photo" => "Uredi trenutno sliko",
"Upload new photo" => "Pošlji novo sliko",
"Select photo from ownCloud" => "Izberi sliko v oblaku ownCloud",
"Name" => "Ime",
"First name" => "Ime",
"Additional names" => "Druga imena",
"Last name" => "Priimek",
"Select groups" => "Izbor skupin",
"Select address book" => "Izbor imenika",
"Nickname" => "Vzdevek",
"Enter nickname" => "Vnos vzdevka",
"Title" => "Naslov",
"Enter title" => "Vnos naziva",
"Organization" => "Ustanova",
"Enter organization" => "Vnos ustanove",
"Birthday" => "Rojstni dan",
"Notes go here..." => "Prostor za opombe ...",
"Export as VCF" => "Izvozi kot VCF",
"Add field..." => "Dodaj polje ...",
"Phone" => "Telefon",
"Email" => "Elektronski naslov",
"Instant Messaging" => "Hipno sporočanje",
"Address" => "Naslov",
"Note" => "Opomba",
"Web site" => "Spletna stran",
"Delete contact" => "Izbriši stik",
"Preferred" => "Prednostno",
"Please specify a valid email address." => "Navesti je treba veljaven elektronski poštni naslov.",
"someone@example.com" => "nekdo@primer.com",
"Mail to address" => "Elektronski naslov prejemnika",
"Delete email address" => "Izbriši elektronski poštni naslov",
"Enter phone number" => "Vpiši telefonsko številko",
"Delete phone number" => "Izbriši telefonsko številko",
"Go to web site" => "Pojdi na spletno stran",
"Delete URL" => "Izbriši naslov URL",
"View on map" => "Pokaži na zemljevidu",
"Delete address" => "Izbriši imenik",
"1600 Pennsylvania Avenue, NW" => "1600 Pennsylvania Avenue, NW",
"Street address" => "Naslov ulice",
"20500" => "20500",
"Postal code" => "Poštna številka",
"Washington, DC" => "Washington, DC",
"City" => "Mesto",
"District of Columbia" => "District of Columbia",
"State or province" => "Zvezna država ali provinca",
"USA" => "ZDA",
"Country" => "Država",
"Instant Messenger" => "Hipni sporočilnik",
"Delete IM" => "Izbriši IM",
"Active" => "Dejavno",
"Share" => "Souporaba",
"Export" => "Izvozi",
"CardDAV link" => "Povezava CardDAV",
"CardDAV syncing addresses" => "Naslovi CardDAV za usklajevanje",
"more info" => "več podrobnosti",
"Primary address (Kontact et al)" => "Osnovni naslov (za stik)",
"iOS/OS X" => "iOS/OS X",
"Addressbooks" => "Imeniki",
"New Address Book" => "Nov imenik",
"Description" => "Opis"
);


text:
package org.apache.camel.spring.interceptor;

import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class TransactedDoTryRecipientListTest extends TransactionClientDataSourceSupport {

    @Test
    @Timeout(value = 10)
    public void testRecipientList() throws Exception {
        String response = template.requestBody("direct:start", "Hello World", String.class);

        assertEquals("Hi !!!", response);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .transacted()
                        .doTry()
                            .recipientList(constant("direct:a"))
                        .endDoTry();

                from("direct:a")
                        .delay(1)
                        .transform(constant("Hi !!!"));
            }
        };
    }
}


text:
package sflow

import (
	"encoding/binary"
	"errors"
)

var ErrInvalidSliceLength = errors.New("sflow: invalid slice length")
var ErrUnsupportedIpVersion = errors.New("sflow: unsupported datagram version")
var ErrUnsupportedDatagramVersion = errors.New("sflow: unsupported datagram version")

func DecodeDatagram(bs []byte) ([]byte, *Datagram, error) {
	if len(bs) < 28 {
		return nil, nil, ErrInvalidSliceLength
	}

	// Decode headers first
	dgram := &Datagram{}

	dgram.Version = binary.BigEndian.Uint32(bs)

	//if dgram.Version != 5 {
	//	return nil, ErrUnsupportedDatagramVersion
	//}
	dgram.IpVersion = binary.BigEndian.Uint32(bs[4:])

	//err = binary.Read(d.reader, binary.BigEndian, &)
	//if err != nil {
	//	return nil, err
	//}

	ipLen := 4
	switch dgram.IpVersion {
	case 1: // IP_V4
		ipLen = 4
	case 2: // IP_V6
		ipLen = 16
		if len(bs) < 40 {
			return nil, nil, ErrInvalidSliceLength
		}
	case 0: // UNKNOWN
		ipLen = 0
	default:
		return nil, nil, ErrUnsupportedIpVersion
	}
	if ipLen > 0 {
		dgram.IpAddress = bs[8 : 8+ipLen]
	}
	dgram.SubAgentId = binary.BigEndian.Uint32(bs[8+ipLen:])
	dgram.SequenceNumber = binary.BigEndian.Uint32(bs[12+ipLen:])
	dgram.Uptime = binary.BigEndian.Uint32(bs[16+ipLen:])
	dgram.NumSamples = binary.BigEndian.Uint32(bs[20+ipLen:])
	return bs[24+ipLen:], dgram, nil
}


text:
'use strict';

/* jshint ignore:start */
var expect = require('expect.js');
/* jshint ignore:end */
var Qty = require('../../qty');

describe('Speed' , function () {

    it('should evaluate empty input as 0m/s', function () {
        var zero = Qty.Speed();
        expect(zero.value()).to.be(0);
        expect(zero.isSpeed()).to.be.ok();
    });

    it('should evaluate numerical input as 1 m/s', function () {
        expect(Qty.Speed(1).convertToSI().value()).to.be(1);
    });
    describe('kph', function () {
        it('can be obtain from m/s', function () {
            expect(Qty.Speed(10).convertTo('km/h').value()).to.be(36);
        });
        it('can be converted to mph', function () {
            expect(Qty.Speed('120km/h').to('mph').value()).to.be(120/1.609344);
        });
        it('can be obtained from division by hour', function () {
             expect(Qty('1km').by('1h').format()).to.be('1kph');
        });
    });

    describe('mph', function () {
        it('should be a speed', function () {
            expect(Qty('100 mph').isSpeed()).to.be.ok();
        });
        it('should not be a length', function () {
            expect(Qty('100 mph').isLength()).not.to.be.ok();
        });
        it('can be formatted with short unity', function () {
            expect(Qty('100 mph').format('0 u')).to.be('100 mph');
        });
        it('can be formatted with long unity', function () {
            expect(Qty('100 mph').format('0 U')).to.be('100 miles per hour');
        });
        it('can be obtained from division by hour', function () {
            expect(Qty('1mile').by('1h').format()).to.be('1mph');
        });
    });
});


text:
/* @flow */
import { applyStyles } from '../utils/dom/css';
import { hintsStyle, hintStyle, closeButtonStyle } from '../styles';

function createHint(document: Document, hint: string, title: string) {
  const span = document.createElement('span');
  span.appendChild(document.createTextNode(hint));
  span.setAttribute('title', title);
  applyStyles(span, hintStyle);
  return span;
}

type CloseCallback = () => void;
function createClose(document: Document, callback: CloseCallback) {
  const hints = document.createElement('div');
  applyStyles(hints, hintsStyle);

  const close = createHint(document, '×', 'Click or press Escape to dismiss.');
  close.addEventListener('click', () => callback());
  applyStyles(close, closeButtonStyle);
  hints.appendChild(close);
  return hints;
}

export type { CloseCallback };
export { createClose };


text:
package com.twitter.elephantbird.cascading2.scheme;

import com.twitter.elephantbird.mapreduce.input.combine.DelegateCombineFileInputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.RecordReader;

import com.twitter.elephantbird.mapred.output.DeprecatedOutputFormatWrapper;
import com.twitter.elephantbird.mapreduce.input.MultiInputFormat;
import com.twitter.elephantbird.mapreduce.io.RawBytesWritable;
import com.twitter.elephantbird.mapreduce.output.LzoBinaryBlockOutputFormat;

import cascading.flow.FlowProcess;
import cascading.tap.Tap;

/**
 * Scheme for lzo compressed files with binary records.
 *
 * @author Sam Ritchie
 */
public class LzoByteArrayScheme extends LzoBinaryScheme<byte[], RawBytesWritable> {
  @Override protected RawBytesWritable prepareBinaryWritable() {
    return new RawBytesWritable();
  }

  @Override public void sourceConfInit(FlowProcess<JobConf> fp,
      Tap<JobConf, RecordReader, OutputCollector> tap,
      JobConf conf) {
    MultiInputFormat.setClassConf(byte[].class, conf);
    DelegateCombineFileInputFormat.setDelegateInputFormat(conf, MultiInputFormat.class);
  }

  @Override public void sinkConfInit(FlowProcess<JobConf> fp,
      Tap<JobConf, RecordReader, OutputCollector> tap,
      JobConf conf) {
    DeprecatedOutputFormatWrapper.setOutputFormat(LzoBinaryBlockOutputFormat.class, conf);
  }
}


text:
package com.roylaurie.subcomm.client.message;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.roylaurie.subcomm.client.SubcommMessage;

public final class SubcommCommandMessage extends SubcommMessage {
	private static final String NETCHAT_PREFIX = "SEND:CMD";
    private static final Pattern NETCHAT_PATTERN = Pattern.compile(
        "^" + NETCHAT_PREFIX + ":(.*)$"
    );

    private final String mCommand;

    /**
     * Creates a message object from a single raw netchat message.
     * @param String netchatMessage
     * @return SubcommCommandMessage NULL if the expected pattern doesn't match.
     * @throws IllegalArgumentException If the parameter values are unsupported
     */
    public static SubcommCommandMessage parseNetchatMessage(String netchatMessage) {
        Matcher matcher = NETCHAT_PATTERN.matcher(netchatMessage);
        if (!matcher.find())
            return null;

        String command = matcher.group(1);
        if (command == null || command.length() == 0)
            throw new IllegalArgumentException("Message not specified.");

        return new SubcommCommandMessage(command);
    }

    public SubcommCommandMessage(String command) {
        super(NETCHAT_PREFIX);
        mCommand = command;
    }

    public String getCommand() {
        return mCommand;
    }

    @Override
    public String getNetchatMessage() {
       return createNetchatMessage(mCommand);
    }
}