text:
package org.apache.hadoop.hbase.testing;

import static org.junit.Assert.assertNotEquals;

import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.MiscTests;
import org.junit.ClassRule;
import org.junit.experimental.categories.Category;

@Category({ MiscTests.class, LargeTests.class })
public class TestTestingHBaseClusterReplicationShareZk
  extends TestingHBaseClusterReplicationTestBase {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestTestingHBaseClusterReplicationShareZk.class);

  private HBaseTestingUtility util = new HBaseTestingUtility();

  @Override
  protected void startClusters() throws Exception {
    util.startMiniZKCluster();
    String zkConnectString = util.getZkCluster().getAddress().toString();
    sourceCluster = TestingHBaseCluster
      .create(TestingHBaseClusterOption.builder().useExternalZooKeeper(zkConnectString).build());
    sourceCluster.start();
    peerCluster = TestingHBaseCluster
      .create(TestingHBaseClusterOption.builder().useExternalZooKeeper(zkConnectString).build());
    peerCluster.start();
    assertNotEquals(sourceCluster.getConf().get(HConstants.ZOOKEEPER_ZNODE_PARENT),
      peerCluster.getConf().get(HConstants.ZOOKEEPER_ZNODE_PARENT));
  }

  @Override
  protected void stopClusters() throws Exception {
    util.shutdownMiniZKCluster();
  }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/servicecatalog/ServiceCatalog_EXPORTS.h>
#include <aws/servicecatalog/model/ConstraintDetail.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/servicecatalog/model/Status.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ServiceCatalog
{
namespace Model
{
  class AWS_SERVICECATALOG_API CreateConstraintResult
  {
  public:
    CreateConstraintResult();
    CreateConstraintResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    CreateConstraintResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Information about the constraint.

     */
    inline const ConstraintDetail& GetConstraintDetail() const{ return m_constraintDetail; }

    /**
     *
Information about the constraint.

     */
    inline void SetConstraintDetail(const ConstraintDetail& value) { m_constraintDetail = value; }

    /**
     *
Information about the constraint.

     */
    inline void SetConstraintDetail(ConstraintDetail&& value) { m_constraintDetail = std::move(value); }

    /**
     *
Information about the constraint.

     */
    inline CreateConstraintResult& WithConstraintDetail(const ConstraintDetail& value) { SetConstraintDetail(value); return *this;}

    /**
     *
Information about the constraint.

     */
    inline CreateConstraintResult& WithConstraintDetail(ConstraintDetail&& value) { SetConstraintDetail(std::move(value)); return *this;}

    /**
     *
The constraint parameters.

     */
    inline const Aws::String& GetConstraintParameters() const{ return m_constraintParameters; }

    /**
     *
The constraint parameters.

     */
    inline void SetConstraintParameters(const Aws::String& value) { m_constraintParameters = value; }

    /**
     *
The constraint parameters.

     */
    inline void SetConstraintParameters(Aws::String&& value) { m_constraintParameters = std::move(value); }

    /**
     *
The constraint parameters.

     */
    inline void SetConstraintParameters(const char* value) { m_constraintParameters.assign(value); }

    /**
     *
The constraint parameters.

     */
    inline CreateConstraintResult& WithConstraintParameters(const Aws::String& value) { SetConstraintParameters(value); return *this;}

    /**
     *
The constraint parameters.

     */
    inline CreateConstraintResult& WithConstraintParameters(Aws::String&& value) { SetConstraintParameters(std::move(value)); return *this;}

    /**
     *
The constraint parameters.

     */
    inline CreateConstraintResult& WithConstraintParameters(const char* value) { SetConstraintParameters(value); return *this;}

    /**
     *
The status of the current request.

     */
    inline const Status& GetStatus() const{ return m_status; }

    /**
     *
The status of the current request.

     */
    inline void SetStatus(const Status& value) { m_status = value; }

    /**
     *
The status of the current request.

     */
    inline void SetStatus(Status&& value) { m_status = std::move(value); }

    /**
     *
The status of the current request.

     */
    inline CreateConstraintResult& WithStatus(const Status& value) { SetStatus(value); return *this;}

    /**
     *
The status of the current request.

     */
    inline CreateConstraintResult& WithStatus(Status&& value) { SetStatus(std::move(value)); return *this;}

  private:

    ConstraintDetail m_constraintDetail;

    Aws::String m_constraintParameters;

    Status m_status;
  };

} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws


text:
package org.juxtasoftware.model;

public class EncodingException extends Exception {
    private static final long serialVersionUID = -2323242497463165307L;

    public EncodingException() {
        super();
    }

    public EncodingException(String message) {
        super(message);
    }

    public EncodingException(String message, Throwable cause) {
        super(message, cause);
    }

    public EncodingException(Throwable cause) {
        super(cause);
    }

}


text:
import random
import numpy as np
from colorsys import hsv_to_rgb, rgb_to_hsv

def jitter(size=0.15):
    return random.random() * size - (size/2)

def randomColor():
    return np.array(hsv_to_rgb(random.random(),0.75+jitter(0.5),1))

def hsvColorAdd(npRgbColor, hsv):
    """
    Add a hsv tuple to a color expressed an RGB numpy array
    Return an RGB numpy array value.
    """
    hsv1 = rgb_to_hsv(*tuple(npRgbColor))
    newhsv = np.array(hsv1) + np.array(hsv)
    return np.array(hsv_to_rgb(*tuple(newhsv)))

def colorJitter(hue_jitter=0.1, sat_jitter=0.5, val_jitter=0.5):
    return ( jitter(hue_jitter) % 1.0, jitter(sat_jitter), jitter(val_jitter) )


text:
from ....foo import Foo
from ....bar_abs import Bar as BarAbs
from ....bar_rel import Bar as BarRel
from ....goo.ber.goober import Goober # up 3 levels and down 2

import unittest

class TestRelImport(unittest.TestCase):
    def test_foo(self):
        self.assertEqual('bar', Foo().bar())

    def test_bar_abs(self, ):
        self.assertEqual('bar', BarAbs().foo())

    def test_bar_rel(self, ):
        self.assertEqual('bar', BarRel().foo())

    def test_goober(self, ):
        self.assertEqual(9, Goober().echo(9))


text:
{% load i18n %}
{% regroup plugin_classes by module as module_list %}
{% for module in module_list %}

{% if module.grouper %}{{ module.grouper|capfirst }}{% else %}{% trans "Available plugins" %}{% endif %}

    {% for p in module.list %}

{{ p.name }}

    {% endfor %}
{% endfor %}


text:
.yui3-skin-sam .yui3-console-test-container {
    border-top: 1px solid black;
    padding: 4px 1ex;
}

.yui3-skin-sam .yui3-console-test-container select.menu {
    width: 50%;
}


text:
package cmd

import (
	"fmt"
	"net/url"
	"os"

	"github.com/spf13/cobra"
)

// SubscribersSetToStandbyCmdImsi holds value of 'imsi' option
var SubscribersSetToStandbyCmdImsi string

func init() {
	SubscribersSetToStandbyCmd.Flags().StringVar(&SubscribersSetToStandbyCmdImsi, "imsi", "", TRAPI("IMSI of the target subscriber."))
	SubscribersCmd.AddCommand(SubscribersSetToStandbyCmd)
}

// SubscribersSetToStandbyCmd defines 'set-to-standby' subcommand
var SubscribersSetToStandbyCmd = &cobra.Command{
	Use:   "set-to-standby",
	Short: TRAPI("/subscribers/{imsi}/set_to_standby:post:summary"),
	Long:  TRAPI(`/subscribers/{imsi}/set_to_standby:post:description`) + "\n\n" + createLinkToAPIReference("Subscriber", "setSubscriberToStandby"),
	RunE: func(cmd *cobra.Command, args []string) error {

		if len(args) > 0 {
			return fmt.Errorf("unexpected arguments passed => %v", args)
		}

		opt := &apiClientOptions{
			BasePath: "/v1",
			Language: getSelectedLanguage(),
		}

		ac := newAPIClient(opt)
		if v := os.Getenv("SORACOM_VERBOSE"); v != "" {
			ac.SetVerbose(true)
		}
		err := authHelper(ac, cmd, args)
		if err != nil {
			cmd.SilenceUsage = true
			return err
		}

		param, err := collectSubscribersSetToStandbyCmdParams(ac)
		if err != nil {
			return err
		}

		body, err := ac.callAPI(param)
		if err != nil {
			cmd.SilenceUsage = true
			return err
		}

		if body == "" {
			return nil
		}

		if rawOutput {
			_, err = os.Stdout.Write([]byte(body))
		} else {
			return prettyPrintStringAsJSON(body)
		}
		return err
	},
}

func collectSubscribersSetToStandbyCmdParams(ac *apiClient) (*apiParams, error) {
	var parsedBody interface{}
	var err error
	err = checkIfRequiredStringParameterIsSupplied("imsi", "imsi", "path", parsedBody, SubscribersSetToStandbyCmdImsi)
	if err != nil {
		return nil, err
	}

	return &apiParams{
		method: "POST",
		path:   buildPathForSubscribersSetToStandbyCmd("/subscribers/{imsi}/set_to_standby"),
		query:  buildQueryForSubscribersSetToStandbyCmd(),

		noRetryOnError: noRetryOnError,
	}, nil
}

func buildPathForSubscribersSetToStandbyCmd(path string) string {

	escapedImsi := url.PathEscape(SubscribersSetToStandbyCmdImsi)

	path = strReplace(path, "{"+"imsi"+"}", escapedImsi, -1)

	return path
}

func buildQueryForSubscribersSetToStandbyCmd() url.Values {
	result := url.Values{}

	return result
}


text:
namespace Oryol {
namespace _priv {

//------------------------------------------------------------------------------
void
panDetector::reset() {
    if (this->startEvent.type != touchEvent::invalid) {
        this->startEvent = touchEvent();
    }
    this->panning = false;
}

//------------------------------------------------------------------------------
bool
panDetector::distLess(const glm::vec2& pos0, const glm::vec2& pos1, int32 dist) const {
    float dx = pos1.x - pos0.x;
    float dy = pos1.y - pos0.y;
    return (dx * dx + dy * dy) < (dist * dist);
}

//------------------------------------------------------------------------------
gestureState::Code
panDetector::detect(const touchEvent& newEvent) {
    o_assert_dbg(newEvent.numTouches > 0);

    // check for cancelled event
    if (newEvent.type == touchEvent::cancelled) {
        this->reset();
        return gestureState::none;
    }

    // check for required number of touches
    if (newEvent.numTouches != 1) {
        this->reset();
        return gestureState::none;
    }

    // check if touch identifiers are unchanged (number of touches and same touch ids)
    if ((this->startEvent.type != touchEvent::invalid) && !this->startEvent.sameTouches(newEvent)) {
        this->reset();
        return gestureState::none;
    }

    // check whether to start, move or end panning
    if (newEvent.type == touchEvent::began) {
        this->startEvent = newEvent;
        this->startPosition = newEvent.touchPos(newEvent.points[0].identifier);
        this->position = this->startPosition;
        this->panning = false;
        return gestureState::none;
    }
    else if (newEvent.type == touchEvent::moved) {
        // cancel if start event is not valid
        if (this->startEvent.type == touchEvent::invalid) {
            return gestureState::none;
        }

        this->position = newEvent.touchPos(this->startEvent.points[0].identifier);
        if (this->panning) {
            // already panning
            return gestureState::move;
        }
        else {
            // not yet panning, check if min-distance is reached before starting pan,
            // and if yes, start panning
            if (!this->distLess(this->startPosition, this->position, MinMovedDistance)) {
                this->panning = true;
                return gestureState::start;
            }
            else {
                // not yet panning
                return gestureState::none;
            }
        }
    }
    else if (newEvent.type == touchEvent::ended) {
        if (this->panning) {
            this->position = newEvent.touchPos(this->startEvent.points[0].identifier);
            this->reset();
            return gestureState::end;
        }
        else {
            this->reset();
            return gestureState::none;
        }
    }
    return gestureState::none;
}

} // namespace _priv
} // namespace Oryol


text:
namespace VaultSharp.V1.AuthMethods.UserPass
{
    public interface IUserPassAuthMethod
    {
    }
}


text:
using System.Collections.Generic;
using System.IO;
using Utils;

namespace Scada.Comm.Devices.AB
{
    /// <summary>
    /// The class contains utility methods for the address book
    /// <para>Класс, содержащий вспомогательные методы для адресной книги</para>
    /// </summary>
    public static class AbUtils
    {
        /// <summary>
        /// Загрузить адресную книгу из файла
        /// </summary>
        public static bool LoadAddressBook(string configDir, Log.WriteLineDelegate writeToLog,
            out AddressBook addressBook)
        {
            addressBook = new AddressBook();

            string fileName = configDir + AddressBook.DefFileName;
            if (File.Exists(fileName))
            {
                writeToLog(Localization.UseRussian ?
                    "Загрузка адресной книги" :
                    "Loading address book");
                string errMsg;

                if (addressBook.Load(fileName, out errMsg))
                {
                    return true;
                }
                else
                {
                    writeToLog(errMsg);
                    return false;
                }
            }
            else
            {
                writeToLog(Localization.UseRussian ?
                    "Адресная книга отсутствует" :
                    "Address book is missing");
                return false;
            }
        }

        /// <summary>
        /// Загрузить адресную книгу из файла или получить её из общих свойств линии связи Коммуникатора
        /// </summary>
        public static AddressBook GetAddressBook(string configDir, SortedList<string, object> commonProps,
            Log.WriteLineDelegate writeToLog)
        {
            AddressBook addressBook;
            object addrBookObj;

            if (commonProps.TryGetValue("AddressBook", out addrBookObj))
            {
                addressBook = addrBookObj as AddressBook;
            }
            else
            {
                LoadAddressBook(configDir, writeToLog, out addressBook);
                commonProps.Add("AddressBook", addressBook);
            }

            return addressBook;
        }
    }
}


text:
require 'spec_helper'

describe 'definition names' do
  before :all do
    module TestDefinition
      module DummyEntities
        module WithVeryLongName
          module AnotherGroupingModule
            class Class1
              class Entity < Grape::Entity
                expose :first_thing
              end
            end

            class Class2
              class Entities < Grape::Entity
                expose :second_thing
              end
            end

            class Class3
              class Entity < Grape::Entity
                expose :third_thing

                def self.entity_name
                  'FooKlass'
                end
              end
            end

            class Class4
              class FourthEntity < Grape::Entity
                expose :fourth_thing
              end
            end

            class Class5
              class FithEntity < Class4::FourthEntity
                expose :fith_thing
              end
            end

            class Class6
              class SixthEntity < Grape::Entity
                expose :sixth_thing

                def self.entity_name
                  'BarKlass'
                end
              end
            end

            class Class7
              class SeventhEntity < Class6::SixthEntity
                expose :seventh_thing
              end
            end
          end
        end
      end

      class NameApi < Grape::API
        add_swagger_documentation models: [
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class1::Entity,
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class2::Entities,
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class3::Entity,
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class4::FourthEntity,
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class5::FithEntity,
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class6::SixthEntity,
          DummyEntities::WithVeryLongName::AnotherGroupingModule::Class7::SeventhEntity
        ]
      end
    end
  end

  let(:app) { TestDefinition::NameApi }

  subject do
    get '/swagger_doc'
    JSON.parse(last_response.body)['definitions']
  end

  specify { expect(subject).to include 'Class1' }
  specify { expect(subject).to include 'Class2' }
  specify { expect(subject).to include 'FooKlass' }
  specify { expect(subject).to include 'FourthEntity' }
  specify { expect(subject).to include 'FithEntity' }
  specify { expect(subject).to include 'BarKlass' }
  specify { expect(subject).to include 'SeventhEntity' }
end


text:
package com.aishang.app.ui.BuyHotel;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.aishang.app.BoilerplateApplication;
import com.aishang.app.R;
import com.aishang.app.data.model.JMyVacationListResult;
import com.aishang.app.ui.MyCard.*;
import com.aishang.app.ui.base.BaseActivity;
import com.aishang.app.util.AiShangUtil;
import com.aishang.app.util.NetworkUtil;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jcodecraeer.xrecyclerview.progressindicator.AVLoadingIndicatorView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import java.util.ArrayList;
import java.util.Arrays;
import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentCardListener} interface
 * to handle interaction events.
 * Use the {@link CardFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CardFragment extends Fragment implements MyCardMvpView {

  @Bind(R.id.recyclerView) XRecyclerView mRecyclerView;
  @Bind(R.id.swipe_refresh) SwipeRefreshLayout swipeRefreshLayout;
  @Bind(R.id.avloadingIndicatorView) AVLoadingIndicatorView avloadingIndicatorView;
  @Bind(R.id.no_data_text) TextView noDataText;
  @Bind(R.id.empty_view) RelativeLayout noDataHotel;
  @Inject MyCardPresenter presenter;
  @Inject MyCardAdapter adapter;

  private OnFragmentCardListener mListener;

  /**
   * Use this factory method to create a new instance of
   * this fragment using the provided parameters.
   *
   * @return A new instance of fragment CardFragment.
   */
  public static CardFragment newInstance() {
    CardFragment fragment = new CardFragment();
    return fragment;
  }

  public CardFragment() {
    // Required empty public constructor
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_card, container, false);
    ButterKnife.bind(this, view);

    initSwipeRefresh();
    initRefreshLayout();
    proLoad();

    return view;
  }

  @Override public void onAttach(Context context) {
    super.onAttach(context);
    ((BaseActivity) context).getActivityComponent().inject(this);

    presenter.attachView(this);

    if (context instanceof OnFragmentCardListener) {
      mListener = (OnFragmentCardListener) context;
    } else {
      throw new RuntimeException(
          context.toString() + " must implement OnFragmentInteractionListener");
    }
  }

  @Override public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  private void autoRefresh() {
    new Handler().postDelayed(new Runnable() {
      @Override public void run() {
        proLoad();
      }
    }, 100);
  }

  private void initSwipeRefresh() {
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override public void onRefresh() {
        asynMyOrder();
      }
    });
  }

  @Override public void showError(String error) {

  }

  @Override public void showEmpty() {
    if (avloadingIndicatorView.getVisibility() == View.VISIBLE) {
      avloadingIndicatorView.setVisibility(View.GONE);
    }

    if (noDataHotel.getVisibility() != View.VISIBLE) {
      noDataHotel.setVisibility(View.VISIBLE);
    }

    mRecyclerView.refreshComplete();
    adapter.getItems().clear();
    adapter.notifyDataSetChanged();
  }

  @Override public void refreshCompleted() {
    if (swipeRefreshLayout.isRefreshing()) {
      swipeRefreshLayout.setRefreshing(false);
    }
  }

  @Override public void refreshList(JMyVacationListResult result) {

    if (avloadingIndicatorView.getVisibility() == View.VISIBLE) {
      avloadingIndicatorView.setVisibility(View.GONE);
    }

    if (noDataHotel.getVisibility() == View.VISIBLE) {
      noDataHotel.setVisibility(View.GONE);
    }

    adapter.getItems().clear();
    adapter.getItems().addAll(result.getMemberexCardList());

    adapter.notifyDataSetChanged();
    mRecyclerView.refreshComplete();

    if (mListener != null && result.getMemberexCardList().size() > 0) {
      mListener.defaultCard(result.getMemberexCardList().get(0));
    }
  }

  private void proLoad() {
    if (NetworkUtil.isNetworkConnected(this.getActivity())) {
      if (avloadingIndicatorView.getVisibility() != View.VISIBLE) {
        avloadingIndicatorView.setVisibility(View.VISIBLE);
      }

      if (noDataHotel.getVisibility() == View.VISIBLE) {
        noDataHotel.setVisibility(View.GONE);
      }
      asynMyOrder();
    } else {

      if (avloadingIndicatorView.getVisibility() == View.VISIBLE) {
        avloadingIndicatorView.setVisibility(View.GONE);
      }

      if (noDataHotel.getVisibility() == View.VISIBLE) {
        noDataHotel.setVisibility(View.GONE);
      }
    }
  }

  private void initRefreshLayout() {
    LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(layoutManager);

    mRecyclerView.addItemDecoration(
        new HorizontalDividerItemDecoration.Builder(this.getActivity()).colorResId(
            android.R.color.transparent).sizeResId(R.dimen.spacing_medium).build());

    mRecyclerView.setLoadingMoreEnabled(false);
    mRecyclerView.setPullRefreshEnabled(false);
    mRecyclerView.setAdapter(adapter);
  }

  private void asynMyOrder() {
    swipeRefreshLayout.setRefreshing(true);
    String cookie = BoilerplateApplication.get(this.getActivity())
        .getMemberLoginResult()
        .getData()
        .getCookies();
    String member = BoilerplateApplication.get(this.getActivity()).getMemberAccount();
    String json = AiShangUtil.generMyVacationListParam(member, cookie, "2012-01-01");
    presenter.loadData(0, json);
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    ButterKnife.unbind(this);
  }

  /**
   * This interface must be implemented by activities that contain this
   * fragment to allow an interaction in this fragment to be communicated
   * to the activity and potentially other fragments contained in that
   * activity.
   *

   * See the Android Training lesson Communicating with Other Fragments for more information.
   */
  public interface OnFragmentCardListener {
    void defaultCard(JMyVacationListResult.MemberexCardListEntity card);
  }
}


text:
<ar-page page="page">

{{page.casename()}}

Chain: {{page.varname}} (score={{page.var().score|number:2}})

<ar-varbox vardiff="page.var()"></ar-varbox>

  <form class="form-inline" style="margin-bottom:15px">

      Significance Level:
      <select id="siglevel" class="form-control input-sm"
              ng-model="page.siglevel"
              ng-options="level for level in page.levels">
      </select>

      Significant Inputs:

{{page.visibleSize()}}

      Total Inputs:

{{page.size()}}

  </form>

Variable {{varname}} has no significant inputs.  Either it is
a model input, or we haven't yet implemented chaining for it.

      Output
      Narrative
      Score

          {{var.name}}

      <ar-varbox vardiff="var"></ar-varbox>
      {{var.score | number:2}}

</ar-page>


text:
alias search="emerge -s"
alias pretend="emerge -pv"

alias dep="equery depends"
alias uses="equery uses"
alias depgraph="equery depgraph"
alias world="less /var/lib/portage/world"
alias kernels="eselect kernel list"
alias efile="e-file"


text:
"use strict";

import React, {Component} from "react";

export default class Pagination extends Component {

	static propTypes = {
		pagination: React.PropTypes.object
	};

	render() {
		return (

							«

					{this.props.pagination.pages.map(page => {
						return
{page.text}
;
					})}

							»

		);
	}
}


text:
import React from 'react';
import { compose } from 'react-apollo';
import autoBind from 'react-autobind';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';

// components
import CommentEditor from '../../components/CommentEditor/CommentEditor';

// graphql
import keywordInsertMutation from '../../../keywords/graphql/mutations/insert';
import keywordUpdateMutation from '../../../keywords/graphql/mutations/update';
import commentsInsertMutation from '../../graphql/mutations/insert';

// lib
import getSelectedLemmaUrn from '../../lib/getSelectedLemmaUrn';
import getSelectOptionsFromCommentFormData from '../../lib/getSelectOptionsFromCommentFormData';
import getNLinesFromLemmaCitation from '../../lib/getNLinesFromLemmaCitation';
import serializeUrn from '../../../cts/lib/serializeUrn';

class CommentEditorContainer extends React.Component {
	constructor(props) {
		super(props);
		autoBind(this);
	}

	handleSelectWork(urn) {
		console.log(urn);

	}

	render() {
		let commenterOptions = [];
		let referenceWorkOptions = [];
		let keywordOptions = [];

		if (
			this.props.commentersQuery
			&& this.props.commentersQuery.commenters
		) {
			this.props.commentersQuery.commenters.forEach(commenter => {
				commenterOptions.push({
					value: commenter._id,
					label: commenter.name,
					slug: commenter.slug,
				});
			});
		}

		if (
			this.props.referenceWorksQuery
			&& this.props.referenceWorksQuery.referenceWorks
		) {
			this.props.referenceWorksQuery.referenceWorks.forEach(referenceWork => {
				referenceWorkOptions.push({
					value: referenceWork._id,
					label: referenceWork.title,
					slug: referenceWork.slug,
				});
			});
		}

		if (
			this.props.keywordsQuery
			&& this.props.keywordsQuery.keywords
		) {
			this.props.keywordsQuery.keywords.forEach(keyword => {
				keywordOptions.push({
					value: keyword._id,
					label: keyword.title,
					slug: keyword.slug,
				});
			});
		}

		return (
			<CommentEditor
			/>
		);
	}
}

const mapStateToProps = (state, props) => ({
	tenantId: state.tenant.tenantId,
});

export default compose(
	connect(mapStateToProps),
	keywordInsertMutation,
	keywordUpdateMutation,
	commentsInsertMutation,
	withRouter,
)(CommentEditorContainer);


text:
package io.debezium.relational.ddl;

import java.util.Optional;

import io.debezium.annotation.Immutable;
import io.debezium.relational.TableId;

/**
 * An interface that can listen to various actions of a {@link DdlParser}. Every kind of {@link Event} has a {@link EventType
 * type} that makes it easier to implement a {@link DdlParserListener} using a {@code switch} statement. However, each kind of
 * {@link Event} also may have additional data associated with it.
 * <p>
 * Clearly not all DDL statements processed by a {@link DdlParser parser} will result in an {@link Event event}.
 *
 * @author Randall Hauch
 */
@FunctionalInterface
public interface DdlParserListener {

    /**
     * Handle a DDL event.
     *
     * @param event the DDL event; never null
     */
    void handle(Event event);

    /**
     * The type of concrete {@link Event}s.
     */
    public static enum EventType {
        CREATE_TABLE,
        ALTER_TABLE,
        DROP_TABLE,
        TRUNCATE_TABLE,
        CREATE_INDEX,
        DROP_INDEX,
        CREATE_DATABASE,
        ALTER_DATABASE,
        DROP_DATABASE,
        USE_DATABASE,
        SET_VARIABLE,
    }

    /**
     * The base class for all concrete events.
     */
    @Immutable
    public static abstract class Event {
        private final String statement;
        private final EventType type;

        public Event(EventType type, String ddlStatement) {
            this.type = type;
            this.statement = ddlStatement;
        }

        /**
         * Get the {@link EventType type} of event. This is useful when switching on the kind of event.
         * @return the type of event; never null
         */
        public EventType type() {
            return type;
        }

        /**
         * Get the DDL statement associated with this event.
         * @return the DDL statement; never null
         */
        public String statement() {
            return statement;
        }
    }

    /**
     * The base class for all table-related events.
     */
    @Immutable
    public static abstract class TableEvent extends Event {
        private final TableId tableId;
        private final boolean isView;

        public TableEvent(EventType type, TableId tableId, String ddlStatement, boolean isView) {
            super(type, ddlStatement);
            this.tableId = tableId;
            this.isView = isView;
        }

        /**
         * Get the identifier of the primary table affected by this event.
         * @return the table identifier; never null
         */
        public TableId tableId() {
            return tableId;
        }

        /**
         * Determine whether the target of the event is a view rather than a table.
         * @return {@code true} if the target is a view, or {@code false} if the target is a table
         */
        public boolean isView() {
            return isView;
        }

        @Override
        public String toString() {
            return tableId() + " => " + statement();
        }
    }

    /**
     * An event describing the creation (or replacement) of a table.
     */
    @Immutable
    public static class TableCreatedEvent extends TableEvent {
        public TableCreatedEvent(TableId tableId, String ddlStatement, boolean isView) {
            super(EventType.CREATE_TABLE, tableId, ddlStatement, isView);
        }
    }

    /**
     * An event describing the altering of a table.
     */
    @Immutable
    public static class TableAlteredEvent extends TableEvent {
        private final TableId previousTableId;

        public TableAlteredEvent(TableId tableId, TableId previousTableId, String ddlStatement, boolean isView) {
            super(EventType.ALTER_TABLE, tableId, ddlStatement, isView);
            this.previousTableId = previousTableId;
        }

        /**
         * If the table was renamed, then get the old identifier of the table before it was renamed.
         * @return the table's previous identifier; may be null if the alter did not affect the table's identifier
         */
        public TableId previousTableId() {
            return previousTableId;
        }

        @Override
        public String toString() {
            if (previousTableId != null) {
                return tableId() + " (was " + previousTableId() + ") => " + statement();
            }
            return tableId() + " => " + statement();
        }
    }

    /**
     * An event describing the dropping of a table.
     */
    @Immutable
    public static class TableDroppedEvent extends TableEvent {
        public TableDroppedEvent(TableId tableId, String ddlStatement, boolean isView) {
            super(EventType.DROP_TABLE, tableId, ddlStatement, isView);
        }
    }

    /**
     * An event describing the truncating of a table.
     */
    @Immutable
    public static class TableTruncatedEvent extends TableEvent {
        public TableTruncatedEvent(TableId tableId, String ddlStatement, boolean isView) {
            super(EventType.TRUNCATE_TABLE, tableId, ddlStatement, isView);
        }
    }

    /**
     * The abstract base class for all index-related events.
     */
    @Immutable
    public static abstract class TableIndexEvent extends Event {
        private final TableId tableId;
        private final String indexName;

        public TableIndexEvent(EventType type, String indexName, TableId tableId, String ddlStatement) {
            super(type, ddlStatement);
            this.tableId = tableId;
            this.indexName = indexName;
        }

        /**
         * Get the identifier of the table to which the index applies.
         * @return the table identifier; may be null if the index is not scoped to a single table
         */
        public TableId tableId() {
            return tableId;
        }

        /**
         * Get the name of the index affected by this event.
         * @return the index name; never null
         */
        public String indexName() {
            return indexName;
        }

        @Override
        public String toString() {
            if (tableId == null) {
                return indexName() + " => " + statement();
            }
            return indexName() + " on " + tableId() + " => " + statement();
        }
    }

    /**
     * An event describing the creation of an index on a table.
     */
    @Immutable
    public static class TableIndexCreatedEvent extends TableIndexEvent {
        public TableIndexCreatedEvent(String indexName, TableId tableId, String ddlStatement) {
            super(EventType.CREATE_INDEX, indexName, tableId, ddlStatement);
        }
    }

    /**
     * An event describing the dropping of an index on a table.
     */
    @Immutable
    public static class TableIndexDroppedEvent extends TableIndexEvent {
        public TableIndexDroppedEvent(String indexName, TableId tableId, String ddlStatement) {
            super(EventType.DROP_INDEX, indexName, tableId, ddlStatement);
        }
    }

    /**
     * The base class for all table-related events.
     */
    @Immutable
    public static abstract class DatabaseEvent extends Event {
        private final String databaseName;

        public DatabaseEvent(EventType type, String databaseName, String ddlStatement) {
            super(type, ddlStatement);
            this.databaseName = databaseName;
        }

        /**
         * Get the database name affected by this event.
         * @return the database name; never null
         */
        public String databaseName() {
            return databaseName;
        }

        @Override
        public String toString() {
            return databaseName() + " => " + statement();
        }
    }

    /**
     * An event describing the creation of a database.
     */
    @Immutable
    public static class DatabaseCreatedEvent extends DatabaseEvent {
        public DatabaseCreatedEvent(String databaseName, String ddlStatement) {
            super(EventType.CREATE_DATABASE, databaseName, ddlStatement);
        }
    }

    /**
     * An event describing the altering of a database.
     */
    @Immutable
    public static class DatabaseAlteredEvent extends DatabaseEvent {
        private final String previousDatabaseName;

        public DatabaseAlteredEvent(String databaseName, String previousDatabaseName, String ddlStatement) {
            super(EventType.ALTER_DATABASE, databaseName, ddlStatement);
            this.previousDatabaseName = previousDatabaseName;
        }

        /**
         * If the table was renamed, then get the old identifier of the table before it was renamed.
         * @return the table's previous identifier; may be null if the alter did not affect the table's identifier
         */
        public String previousDatabaseName() {
            return previousDatabaseName;
        }

        @Override
        public String toString() {
            if (previousDatabaseName != null) {
                return databaseName() + " (was " + previousDatabaseName() + ") => " + statement();
            }
            return databaseName() + " => " + statement();
        }
    }

    /**
     * An event describing the dropping of a database.
     */
    @Immutable
    public static class DatabaseDroppedEvent extends DatabaseEvent {
        public DatabaseDroppedEvent(String databaseName, String ddlStatement) {
            super(EventType.DROP_DATABASE, databaseName, ddlStatement);
        }
    }

    /**
     * An event describing the switching of a database.
     */
    @Immutable
    public static class DatabaseSwitchedEvent extends DatabaseEvent {
        public DatabaseSwitchedEvent(String databaseName, String ddlStatement) {
            super(EventType.USE_DATABASE, databaseName, ddlStatement);
        }
    }

    /**
     * An event describing the setting of a variable.
     */
    @Immutable
    public static class SetVariableEvent extends Event {

        private final String variableName;
        private final String value;
        private final String databaseName;
        private final int order;

        public SetVariableEvent(String variableName, String value, String currentDatabaseName, int order, String ddlStatement) {
            super(EventType.SET_VARIABLE, ddlStatement);
            this.variableName = variableName;
            this.value = value;
            this.databaseName = currentDatabaseName;
            this.order = order;
        }

        /**
         * Get the name of the variable that was set.
         * @return the variable name; never null
         */
        public String variableName() {
            return variableName;
        }

        /**
         * Get the value of the variable that was set.
         * @return the variable value; may be null
         */
        public String variableValue() {
            return value;
        }

        /**
         * In case of multiple vars set in the same SET statement the order of the variable in the statement.
         * @return the variable order
         */
        public int order() {
            return order;
        }

        public Optional<String> databaseName() {
            return Optional.ofNullable(databaseName);
        }

        @Override
        public String toString() {
            return statement();
        }
    }
}


text:
"""Support for MySensors binary sensors."""
from homeassistant.components import mysensors
from homeassistant.components.binary_sensor import (
    DEVICE_CLASS_MOISTURE,
    DEVICE_CLASS_MOTION,
    DEVICE_CLASS_SAFETY,
    DEVICE_CLASS_SOUND,
    DEVICE_CLASS_VIBRATION,
    DEVICE_CLASSES,
    DOMAIN,
    BinarySensorEntity,
)
from homeassistant.const import STATE_ON

SENSORS = {
    "S_DOOR": "door",
    "S_MOTION": DEVICE_CLASS_MOTION,
    "S_SMOKE": "smoke",
    "S_SPRINKLER": DEVICE_CLASS_SAFETY,
    "S_WATER_LEAK": DEVICE_CLASS_SAFETY,
    "S_SOUND": DEVICE_CLASS_SOUND,
    "S_VIBRATION": DEVICE_CLASS_VIBRATION,
    "S_MOISTURE": DEVICE_CLASS_MOISTURE,
}

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the mysensors platform for binary sensors."""
    mysensors.setup_mysensors_platform(
        hass,
        DOMAIN,
        discovery_info,
        MySensorsBinarySensor,
        async_add_entities=async_add_entities,
    )

class MySensorsBinarySensor(mysensors.device.MySensorsEntity, BinarySensorEntity):
    """Representation of a MySensors Binary Sensor child node."""

    @property
    def is_on(self):
        """Return True if the binary sensor is on."""
        return self._values.get(self.value_type) == STATE_ON

    @property
    def device_class(self):
        """Return the class of this sensor, from DEVICE_CLASSES."""
        pres = self.gateway.const.Presentation
        device_class = SENSORS.get(pres(self.child_type).name)
        if device_class in DEVICE_CLASSES:
            return device_class
        return None


text:
cls
Get-ChildItem env:


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Regulations Governing Nurse Practitioners Carrying out Medical Activities under the Supervision of a Physician</英文法規名稱>
<中文法規名稱>專科護理師於醫師監督下執行醫療業務辦法</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=L0020185</法規網址>
<最新英文異動日期>20170508</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件>
  <檔案>
    <檔案名稱><![CDATA[Appendix.PDF]]></檔案名稱>
    <下載網址>https://law.moj.gov.tw/Eng/LawClass/LawGetFile.ashx?FileId=0000004953</下載網址>
  </檔案>
  <檔案>
    <檔案名稱><![CDATA[Appendix.doc]]></檔案名稱>
    <下載網址>https://law.moj.gov.tw/Eng/LawClass/LawGetFile.ashx?FileId=0000003710</下載網址>
  </檔案>
</附件>
<沿革內容><![CDATA[1.Promulgated on October 19, 2015
2.The appendix of Article 3 and Article 8 was amended and promulgated on May 8, 2017 pursuant to the Ministry of Health and Welfare Order Wei-Bu-Zhao-Zi-Di No. 1061560785.]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[The Regulations are established in accordance with Paragraph 4 of Article 24 of the Nursing Personnel Act (hereinafter referred to as the Act).]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The supervision, as set forth in Paragraph 3 of Article 24 of the Act, shall refer to the instructions, guidance, or directions given by a physician to nurse practitioners and professional registered nurses who are receiving nurse practitioner training (hereinafter referred to as nurse practitioners and nurse practitioners in training) before or while they carry out medical activities.
A physician is not required to be personally present for the supervision set forth in the preceding paragraph.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[The scope of medical activities that nurse practitioners and nurse practitioners in training may carry out under the supervision of a physician (hereinafter referred to as medical activities under supervision) is as follows:
1. Where intrusion into the human body is involved:
(1) Wound treatment;
(2) Tube treatment;
(3) Examination treatment;
(4) Other treatments.
2. Where intrusion into the human body is not involved:
(1) Issuance of the forms and documents required for pre-established specific medical procedures;
(2) Initial comprehensive judgment on tests and examinations;
(3) Non-invasive medical treatment;
(4) Relevant medical counseling services.
The regulations governing the medical activities set forth in the two subparagraphs of the preceding paragraph are set out in the appendix.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[Medical institutions that employ nurse practitioners and nurse practitioners in training to carry out medical activities under supervision shall set up nurse practitioner working groups (hereinafter referred to as working groups), in which a staff member at the rank of deputy superintendent or higher will serve as the convener and directors of the nursing and medical departments will serve as deputy conveners. The following shall be done:
1. Developing standard operating procedures for nurse practitioners and nurse practitioners in training to carry out medical activities under supervision, including supervising physicians, medical orders, records, and the systems for reporting the conditions of a patient and treatment results;
2. Determining the medical activities within the scope shown in the appendix of the preceding article and specific training that nurse practitioners and nurse practitioners in training with different specialties at medical institutions can carry out;
3. Reviewing and verifying the details of pre-established specific medical procedures;
4. Developing standard operating procedures for the implementation of pre-established specific medical procedures;
5. Conducting regular reviews on the appropriateness and quality of medical activities carried out by nurse practitioners and nurse practitioners in training under supervision.
The abovementioned working groups may be merged with the nurse practitioner incubator units set forth in Appendix 3 of the Regulations Governing Specialties and Examination of Nurse Practitioner.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[Physicians may pre-establish specific medical procedures for medical activities carried out by nurse practitioners and nurse practitioners in training under supervision.
The details of pre-established specific medical procedures shall include the following:
1. Conditions or diagnoses such as symptoms, medical history, physical assessments;
2. Implementation items;
3. Relevant treatments and measures;
4. Written records;
5. The supervising physician and supervision method;
6. Specific training standards or requirements that nurse practitioners and nurse practitioners in training shall meet.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[Pre-established specific medical procedures shall be implemented upon approval from medical institutions.
The implementation of pre-established specific medical procedures shall conform to the standard operating procedures set forth in Subparagraph 4 of Paragraph 1 of Article 4.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[The supervising physician shall complete the approval and signature process within 24 hours after nurse practitioners and nurse practitioners in training carry out pre-established specific medical procedures. In the case of other medical activities under supervision, the supervising physician shall also complete the medical orders and records in writing within 24 hours.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The Regulations came into effect on January 1, 2016.
Amendments to the Regulations come into effect on the date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
"""Support for KNX/IP switches."""
from __future__ import annotations

from typing import Any

from xknx import XKNX
from xknx.devices import Switch as XknxSwitch

from homeassistant.components.switch import SwitchEntity
from homeassistant.const import (
    CONF_ENTITY_CATEGORY,
    CONF_NAME,
    STATE_ON,
    STATE_UNAVAILABLE,
    STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from .const import CONF_RESPOND_TO_READ, DOMAIN, KNX_ADDRESS
from .knx_entity import KnxEntity
from .schema import SwitchSchema

async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up switch(es) for KNX platform."""
    if not discovery_info or not discovery_info["platform_config"]:
        return
    platform_config = discovery_info["platform_config"]
    xknx: XKNX = hass.data[DOMAIN].xknx

    async_add_entities(
        KNXSwitch(xknx, entity_config) for entity_config in platform_config
    )

class KNXSwitch(KnxEntity, SwitchEntity, RestoreEntity):
    """Representation of a KNX switch."""

    _device: XknxSwitch

    def __init__(self, xknx: XKNX, config: ConfigType) -> None:
        """Initialize of KNX switch."""
        super().__init__(
            device=XknxSwitch(
                xknx,
                name=config[CONF_NAME],
                group_address=config[KNX_ADDRESS],
                group_address_state=config.get(SwitchSchema.CONF_STATE_ADDRESS),
                respond_to_read=config[CONF_RESPOND_TO_READ],
                invert=config[SwitchSchema.CONF_INVERT],
            )
        )
        self._attr_entity_category = config.get(CONF_ENTITY_CATEGORY)
        self._attr_unique_id = str(self._device.switch.group_address)

    async def async_added_to_hass(self) -> None:
        """Restore last state."""
        await super().async_added_to_hass()
        if not self._device.switch.readable and (
            last_state := await self.async_get_last_state()
        ):
            if last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE):
                self._device.switch.value = last_state.state == STATE_ON

    @property
    def is_on(self) -> bool:
        """Return true if device is on."""
        return bool(self._device.state)

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the device on."""
        await self._device.set_on()

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the device off."""
        await self._device.set_off()


text:
<?php

namespace Alborq\SchemaGenerator\Ref\DataType;

class BooleanType extends AbstractType
{
    /**
     * @return string a php type name like 'array', 'string', ...
     */
    public function getPhpTypeName()
    {
        return 'bool';
    }

    public function isScalar()
    {
        return true;
    }
}


text:
<html>
<head>
<title>Manual</title>
</head>
<frameset frameborder=1>
<frame src="html/index.html"></frame>
</frameset>
</html>


text:
/**
 * @file hmm_util.hpp
 * @author Ryan Curtin
 *
 * Utility to read HMM type from file.
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef __MLPACK_METHODS_HMM_HMM_UTIL_HPP
#define __MLPACK_METHODS_HMM_HMM_UTIL_HPP

#include <mlpack/core.hpp>

namespace mlpack {
namespace hmm {

//! HMMType, to be stored on disk.  This is of type char, which is one byte.
//! (I'm not sure what will happen on systems where one byte is not eight bits.)
enum HMMType : char
{
  DiscreteHMM = 0,
  GaussianHMM,
  GaussianMixtureModelHMM
};

//! ActionType should implement static void Apply(HMMType&).
template<typename ActionType, typename ExtraInfoType = void>
void LoadHMMAndPerformAction(const std::string& modelFile,
                             ExtraInfoType* x = NULL);

//! Save an HMM to a file.  The file must also encode what type of HMM is being
//! stored.
template<typename HMMType>
void SaveHMM(HMMType& hmm, const std::string& modelFile);

} // namespace hmm
} // namespace mlpack

#include "hmm_util_impl.hpp"

#endif


text:
<?php

namespace Addons\SingIn\Model;
use Think\Model;

/**
 * SingIn模型
 */
class SingInModel extends Model{

}


text:
package cn.edu.tju.ina.estuary.repo.impl;

import org.springframework.stereotype.Repository;

import cn.edu.tju.ina.estuary.domain.info.Market;
import cn.edu.tju.ina.estuary.repo.InfoDao;

@Repository("marketDao")
public class MarketDaoImpl extends UntypedInfoDaoImpl<Market> implements InfoDao<Market> {
}


text:
{% extends "base.html" %}
{% block js_head %}

{% endblock %}

{% block content %}

{% endblock %}
{% block js %}

{% endblock %}


text:
import unittest

import eigen
import sva

import pytest

import numpy as np

import sys

TOL = 0.00001

class TestRotationMatrix(unittest.TestCase):
  def test(self):
    theta2d = eigen.Vector2d.Random()*10
    theta = theta2d[0]

    self.assertAlmostEqual((sva.RotX(theta) - eigen.AngleAxisd(-theta, eigen.Vector3d.UnitX()).matrix()).norm(), 0, delta = TOL)
    self.assertAlmostEqual((sva.RotY(theta) - eigen.AngleAxisd(-theta, eigen.Vector3d.UnitY()).matrix()).norm(), 0, delta = TOL)
    self.assertAlmostEqual((sva.RotZ(theta) - eigen.AngleAxisd(-theta, eigen.Vector3d.UnitZ()).matrix()).norm(), 0, delta = TOL)

class TestPTransformd(unittest.TestCase):
  def test(self):
    Em = eigen.AngleAxisd(np.pi/2, eigen.Vector3d.UnitX()).inverse().matrix()
    Eq = eigen.Quaterniond(eigen.AngleAxisd(np.pi/2, eigen.Vector3d.UnitX()).inverse())
    r = eigen.Vector3d.Random()*100

    pt1 = sva.PTransformd.Identity()
    self.assertEqual(pt1.rotation(), eigen.Matrix3d.Identity())
    self.assertEqual(pt1.translation(), eigen.Vector3d.Zero())

    pt2 = sva.PTransformd(Em, r)
    self.assertEqual(pt2.rotation(), Em)
    self.assertEqual(pt2.translation(), r)

    pt3 = sva.PTransformd(Eq, r)
    self.assertEqual(pt3.rotation(), Eq.toRotationMatrix())
    self.assertEqual(pt3.translation(), r)

    pt4 = sva.PTransformd(Eq)
    self.assertEqual(pt4.rotation(), Eq.toRotationMatrix())
    self.assertEqual(pt4.translation(), eigen.Vector3d.Zero())

    pt5 = sva.PTransformd(Em)
    self.assertEqual(pt5.rotation(), Em)
    self.assertEqual(pt5.translation(), eigen.Vector3d.Zero())

    pt6 = sva.PTransformd(r)
    self.assertEqual(pt6.rotation(), eigen.Matrix3d.Identity())
    self.assertEqual(pt6.translation(), r)

    pttmp = sva.PTransformd(eigen.AngleAxisd(np.pi/4, eigen.Vector3d.UnitY()).matrix(), eigen.Vector3d.Random()*100.)

    pt7 = pt2*pttmp
    ptm = pt2.matrix() * pttmp.matrix()
    self.assertAlmostEqual((pt7.matrix() - ptm).norm(), 0, delta = TOL)

    pt8 = pt2.inv()
    self.assertAlmostEqual((pt8.matrix() - pt2.matrix().inverse()).norm(), 0, delta = TOL)

    self.assertEqual(pt2, pt2)
    self.assertNotEqual(pt2, pt8)

    self.assertTrue(pt2 != pt8)
    self.assertTrue(not(pt2 != pt2))

class TestPTransformdLeftOperator(unittest.TestCase):
  def test(self):
    Eq = eigen.AngleAxisd(np.pi/2, eigen.Vector3d.UnitX())
    r = eigen.Vector3d.Random() * 100
    pt = sva.PTransformd(Eq, r)
    ptInv = pt.inv()
    pt6d = pt.matrix()
    ptInv6d = ptInv.matrix()
    ptDual6d = pt.dualMatrix()

    M = eigen.Matrix3d([[1,2,3],[2,1,4],[3,4,1]])
    H = eigen.Matrix3d.Random() * 100
    I = eigen.Matrix3d([[1,2,3],[2,1,4],[3,4,1]])
    ab = sva.ABInertiad(M, H, I)
    ab6d = ab.matrix()

    mass = 1.
    h = eigen.Vector3d.Random()*100
    rb = sva.RBInertiad(mass, h, I)
    rb6d = rb.matrix()

    w = eigen.Vector3d.Random()*100
    v = eigen.Vector3d.Random()*100
    n = eigen.Vector3d.Random()*100
    f = eigen.Vector3d.Random()*100

    mVec = sva.MotionVecd(w, v)
    mVec6d = mVec.vector()

    fVec = sva.ForceVecd(n, f)
    fVec6d = fVec.vector()

    mvRes1 = pt*mVec
    mvRes16d = pt6d*mVec6d

    self.assertAlmostEqual((mvRes1.vector() - mvRes16d).norm(), 0, delta = TOL)
    self.assertAlmostEqual((mvRes1.angular() - pt.angularMul(mVec)).norm(), 0, delta = TOL)
    self.assertAlmostEqual((mvRes1.linear() - pt.linearMul(mVec)).norm(), 0, delta = TOL)

    # Note: the C++ version would test the vectorized version here but this is not supported by the Python bindings

    mvRes2 = pt.invMul(mVec)
    mvRes26d = ptInv6d*mVec6d
    self.assertAlmostEqual((mvRes2.vector() - mvRes26d).norm(), 0, delta = TOL)
    self.assertAlmostEqual((mvRes2.angular() - pt.angularInvMul(mVec)).norm(), 0, delta = TOL)
    self.assertAlmostEqual((mvRes2.linear() - pt.linearInvMul(mVec)).norm(), 0, delta = TOL)

    # Same note about the vectorized version

    fvRes1 = pt.dualMul(fVec)
    fvRes16d = ptDual6d*fVec6d

    self.assertAlmostEqual((fvRes1.vector() - fvRes16d).norm(), 0, delta = TOL)
    self.assertAlmostEqual((fvRes1.couple() - pt.coupleDualMul(fVec)).norm(), 0, delta = TOL)
    self.assertAlmostEqual((fvRes1.force() - pt.forceDualMul(fVec)).norm(), 0, delta = TOL)

    # Same note about the vectorized version

    fvRes2 = pt.transMul(fVec)
    fvRes26d = pt6d.transpose() * fVec6d

    self.assertAlmostEqual((fvRes2.vector() - fvRes26d).norm(), 0, delta= TOL)
    self.assertAlmostEqual((fvRes2.couple() - pt.coupleTransMul(fVec)).norm(), 0, delta = TOL)
    self.assertAlmostEqual((fvRes2.force() - pt.forceTransMul(fVec)).norm(), 0, delta = TOL)

    # Same note about the vectorized version

    rbRes1 = pt.dualMul(rb)
    rbRes16d = ptDual6d * rb6d * ptInv6d
    self.assertAlmostEqual((rbRes1.matrix() - rbRes16d).norm(), 0, delta = TOL)

    rbRes2 = pt.transMul(rb);
    rbRes26d = pt6d.transpose()*rb6d*pt6d
    self.assertAlmostEqual((rbRes2.matrix() - rbRes26d).norm(), 0, delta = TOL);

    abRes1 = pt.dualMul(ab);
    abRes16d = ptDual6d*ab6d*ptInv6d
    self.assertAlmostEqual((abRes1.matrix() - abRes16d).norm(), 0, delta = TOL)

    abRes2 = pt.transMul(ab);
    abRes26d = pt6d.transpose()*ab6d*pt6d
    self.assertAlmostEqual((abRes2.matrix() - abRes26d).norm(), 0, delta = TOL)

class TestEulerAngle(unittest.TestCase):
  def test(self):
    res = eigen.Vector3d()

    res = sva.rotationError(eigen.Matrix3d.Identity(), sva.RotX(np.pi/2))
    self.assertAlmostEqual((res - eigen.Vector3d(np.pi/2, 0, 0)).norm(), 0, delta = TOL)

    res = sva.rotationError(eigen.Matrix3d.Identity(), sva.RotY(np.pi/2))
    self.assertAlmostEqual((res - eigen.Vector3d(0, np.pi/2, 0)).norm(), 0, delta = TOL)

    res = sva.rotationError(eigen.Matrix3d.Identity(), sva.RotZ(np.pi/2))
    self.assertAlmostEqual((res - eigen.Vector3d(0, 0, np.pi/2)).norm(), 0, delta = TOL)

    res = sva.rotationError(sva.RotZ(np.pi/4), sva.RotZ(np.pi/2))
    self.assertAlmostEqual((res - eigen.Vector3d(0, 0, np.pi/4)).norm(), 0, delta = TOL)

class TestInterpolate(unittest.TestCase):
  def test(self):
    from_ = sva.PTransformd(eigen.Matrix3d.Identity(), eigen.Vector3d.Zero())
    to = sva.PTransformd(eigen.AngleAxisd(np.pi, eigen.Vector3d.UnitZ()), eigen.Vector3d(1, 2, -3))

    res = sva.interpolate(from_, to, 0.5)
    self.assertAlmostEqual((res.rotation() - eigen.AngleAxisd(np.pi/2, eigen.Vector3d.UnitZ()).matrix()).norm(), 0, delta = TOL)
    self.assertAlmostEqual((res.translation() - eigen.Vector3d(0.5, 1., -1.5)).norm(), 0,  delta = TOL)

class TestTransformError(unittest.TestCase):
  def test(self):
    X_a_b = sva.PTransformd(eigen.Quaterniond(eigen.Vector4d.Random()).normalized(), eigen.Vector3d.Random())
    X_a_c = sva.PTransformd(eigen.Quaterniond(eigen.Vector4d.Random()).normalized(), eigen.Vector3d.Random())

    V_a_b = sva.transformVelocity(X_a_b)
    V_a_c = sva.transformVelocity(X_a_c)

    self.assertAlmostEqual((V_a_b.angular() - sva.rotationVelocity(X_a_b.rotation())).norm(), 0, delta = TOL)
    self.assertAlmostEqual((V_a_b.linear() - X_a_b.translation()).norm(), 0, delta = TOL)
    self.assertAlmostEqual((V_a_c.angular() - sva.rotationVelocity(X_a_c.rotation())).norm(), 0, delta = TOL)
    self.assertAlmostEqual((V_a_c.linear() - X_a_c.translation()).norm(), 0, delta = TOL)

    V_b_c_a = sva.transformError(X_a_b, X_a_c)
    w_b_c_a = sva.rotationError(X_a_b.rotation(), X_a_c.rotation())
    v_b_c_a = X_a_c.translation() - X_a_b.translation()

    self.assertAlmostEqual((V_b_c_a.angular() - w_b_c_a).norm(), 0, delta = TOL)
    self.assertAlmostEqual((V_b_c_a.linear() - v_b_c_a).norm(), 0, delta = TOL)

class Testsinc_inv(unittest.TestCase):
  def test(self):
    dummy_sinc_inv = lambda x : x/np.sin(x)
    eps = sys.float_info.epsilon

    t = -1.
    nrIter = 333
    for i in range(nrIter):
      self.assertAlmostEqual(dummy_sinc_inv(t), sva.sinc_inv(t), delta= TOL)
      t += 2./nrIter

    with pytest.warns(RuntimeWarning) as record:
        self.assertTrue(np.isnan(dummy_sinc_inv(0)))
    self.assertEqual(sva.sinc_inv(0), 1)

    self.assertAlmostEqual(dummy_sinc_inv(eps), sva.sinc_inv(eps), delta = TOL)

    self.assertAlmostEqual(dummy_sinc_inv(np.sqrt(eps)),
                     sva.sinc_inv(np.sqrt(eps)), delta = TOL)
    self.assertAlmostEqual(dummy_sinc_inv(np.sqrt(np.sqrt(eps))),
                     sva.sinc_inv(np.sqrt(np.sqrt(eps))), delta = TOL)

if __name__ == "__main__":
  suite = unittest.TestSuite()
  suite.addTest(TestRotationMatrix('test'))
  suite.addTest(TestPTransformd('test'))
  suite.addTest(TestPTransformdLeftOperator('test'))
  suite.addTest(TestEulerAngle('test'))
  suite.addTest(TestInterpolate('test'))
  suite.addTest(TestTransformError('test'))
  suite.addTest(Testsinc_inv('test'))
  unittest.TextTestRunner(verbosity=2).run(suite)


text:
<!DOCTYPE html>
<!--
This file cannot be upstreamed to WPT until:
* internals.setPermission() usage is replaced with a WebDriver API
-->
<title>Access to the Push API is deferred</title>
<meta name="timeout" content="long">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/utils.js"></script>
<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script>
<body>
<script>

promise_test(async t => {
  const bc = new BroadcastChannel('test-channel');
  t.add_cleanup(_ => bc.close());

  const gotMessage = new Promise(resolve => {
    bc.addEventListener('message', e => {
      resolve(e.data);
    }, {
      once: true
    });
  });

  // We grant the permission here to make a more discerning test because
  // pushManager.subscribe() waits until the permission is granted, which
  // is deferred during prerendering so the test would trivially pass without
  // the permission.
  await internals.setPermission({name: 'push', userVisibleOnly: true},
                                'granted', location.origin, location.origin);

  // Install the service worker first to test pushManager.subscribe in the
  // prerendering page.
  const scope = `resources/`;
  const script = `resources/do-nothing-worker.js`;
  const registration =
      await service_worker_unregister_and_register(t, script, scope);
  t.add_cleanup(() => registration.unregister());
  await wait_for_state(t, registration.installing, 'activated');

  const url = `resources/push.https.html`;
  window.open(url, '_blank', 'noopener');

  const result = await gotMessage;
  const expected = [
    {event: 'started waiting pushManager.subscribe',    prerendering: true},
    {event: 'prerendering change',                      prerendering: false},
    {event: 'finished waiting pushManager.subscribe',   prerendering: false},
  ];
  assert_equals(result.length, expected.length);
  for (let i = 0; i < result.length; i++) {
    assert_equals(result[i].event, expected[i].event, `event[${i}]`);
    assert_equals(result[i].prerendering, expected[i].prerendering,
      `prerendering[${i}]`);
  }
}, `The access to the Push API should be deferred until the prerendered page is
    activated`);

</script>
</body>


text:
package org.apache.hadoop.hbase.coordination;

import static org.apache.hadoop.hbase.executor.EventType.RS_ZK_REGION_SPLIT;
import static org.apache.hadoop.hbase.executor.EventType.RS_ZK_REGION_SPLITTING;
import static org.apache.hadoop.hbase.executor.EventType.RS_ZK_REQUEST_REGION_SPLIT;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.CoordinatedStateManager;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.RegionTransition;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.coordination.SplitTransactionCoordination;
import org.apache.hadoop.hbase.executor.EventType;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.regionserver.RegionServerServices;
import org.apache.hadoop.hbase.zookeeper.ZKAssign;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;

public class ZKSplitTransactionCoordination implements SplitTransactionCoordination {

  private CoordinatedStateManager coordinationManager;
  private final ZooKeeperWatcher watcher;

  private static final Log LOG = LogFactory.getLog(ZKSplitTransactionCoordination.class);

  public ZKSplitTransactionCoordination(CoordinatedStateManager coordinationProvider,
      ZooKeeperWatcher watcher) {
    this.coordinationManager = coordinationProvider;
    this.watcher = watcher;
  }

  /**
   * Creates a new ephemeral node in the PENDING_SPLIT state for the specified region. Create it
   * ephemeral in case regionserver dies mid-split.
   *

   * Does not transition nodes from other states. If a node already exists for this region, an
   * Exception will be thrown.
   * @param parent region to be created as offline
   * @param serverName server event originates from
   * @param hri_a daughter region
   * @param hri_b daughter region
   * @throws IOException
   */

  @Override
  public void startSplitTransaction(HRegion parent, ServerName serverName, HRegionInfo hri_a,
      HRegionInfo hri_b) throws IOException {

    HRegionInfo region = parent.getRegionInfo();
    try {

      LOG.debug(watcher.prefix("Creating ephemeral node for " + region.getEncodedName()
          + " in PENDING_SPLIT state"));
      byte[] payload = HRegionInfo.toDelimitedByteArray(hri_a, hri_b);
      RegionTransition rt =
          RegionTransition.createRegionTransition(RS_ZK_REQUEST_REGION_SPLIT,
            region.getRegionName(), serverName, payload);
      String node = ZKAssign.getNodeName(watcher, region.getEncodedName());
      if (!ZKUtil.createEphemeralNodeAndWatch(watcher, node, rt.toByteArray())) {
        throw new IOException("Failed create of ephemeral " + node);
      }

    } catch (KeeperException e) {
      throw new IOException("Failed creating PENDING_SPLIT znode on "
          + parent.getRegionInfo().getRegionNameAsString(), e);
    }

  }

  /**
   * Transitions an existing ephemeral node for the specified region which is currently in the begin
   * state to be in the end state. Master cleans up the final SPLIT znode when it reads it (or if we
   * crash, zk will clean it up).
   *

   * Does not transition nodes from other states. If for some reason the node could not be
   * transitioned, the method returns -1. If the transition is successful, the version of the node
   * after transition is returned.
   *

   * This method can fail and return false for three different reasons:
   *

   *
Node for this region does not exist

   *
Node for this region is not in the begin state

   *
After verifying the begin state, update fails because of wrong version (this should never
   * actually happen since an RS only does this transition following a transition to the begin
   * state. If two RS are conflicting, one would fail the original transition to the begin state and
   * not this transition)

   *

   *

   * Does not set any watches.
   *

   * This method should only be used by a RegionServer when splitting a region.
   * @param parent region to be transitioned to opened
   * @param a Daughter a of split
   * @param b Daughter b of split
   * @param serverName server event originates from
   * @param std split transaction details
   * @param beginState the expected current state the znode should be
   * @param endState the state to be transition to
   * @return version of node after transition, -1 if unsuccessful transition
   * @throws IOException
   */

  private int transitionSplittingNode(HRegionInfo parent, HRegionInfo a, HRegionInfo b,
      ServerName serverName, SplitTransactionDetails std, final EventType beginState,
      final EventType endState) throws IOException {
    ZkSplitTransactionDetails zstd = (ZkSplitTransactionDetails) std;
    byte[] payload = HRegionInfo.toDelimitedByteArray(a, b);
    try {
      return ZKAssign.transitionNode(watcher, parent, serverName, beginState, endState,
        zstd.getZnodeVersion(), payload);
    } catch (KeeperException e) {
      throw new IOException(
          "Failed transition of splitting node " + parent.getRegionNameAsString(), e);
    }
  }

  /**
   * Wait for the splitting node to be transitioned from pending_split to splitting by master.
   * That's how we are sure master has processed the event and is good with us to move on. If we
   * don't get any update, we periodically transition the node so that master gets the callback. If
   * the node is removed or is not in pending_split state any more, we abort the split.
   */
  @Override
  public void waitForSplitTransaction(final RegionServerServices services, Region parent,
      HRegionInfo hri_a, HRegionInfo hri_b, SplitTransactionDetails sptd) throws IOException {
    ZkSplitTransactionDetails zstd = (ZkSplitTransactionDetails) sptd;

    // After creating the split node, wait for master to transition it
    // from PENDING_SPLIT to SPLITTING so that we can move on. We want master
    // knows about it and won't transition any region which is splitting.
    try {
      int spins = 0;
      Stat stat = new Stat();
      ServerName expectedServer = coordinationManager.getServer().getServerName();
      String node = parent.getRegionInfo().getEncodedName();
      while (!(coordinationManager.getServer().isStopped() || services.isStopping())) {
        if (spins % 5 == 0) {
          LOG.debug("Still waiting for master to process " + "the pending_split for " + node);
          SplitTransactionDetails temp = getDefaultDetails();
          transitionSplittingNode(parent.getRegionInfo(), hri_a, hri_b, expectedServer, temp,
            RS_ZK_REQUEST_REGION_SPLIT, RS_ZK_REQUEST_REGION_SPLIT);
        }
        Thread.sleep(100);
        spins++;
        byte[] data = ZKAssign.getDataNoWatch(watcher, node, stat);
        if (data == null) {
          throw new IOException("Data is null, splitting node " + node + " no longer exists");
        }
        RegionTransition rt = RegionTransition.parseFrom(data);
        EventType et = rt.getEventType();
        if (et == RS_ZK_REGION_SPLITTING) {
          ServerName serverName = rt.getServerName();
          if (!serverName.equals(expectedServer)) {
            throw new IOException("Splitting node " + node + " is for " + serverName + ", not us "
                + expectedServer);
          }
          byte[] payloadOfSplitting = rt.getPayload();
          List<HRegionInfo> splittingRegions =
              HRegionInfo.parseDelimitedFrom(payloadOfSplitting, 0, payloadOfSplitting.length);
          assert splittingRegions.size() == 2;
          HRegionInfo a = splittingRegions.get(0);
          HRegionInfo b = splittingRegions.get(1);
          if (!(hri_a.equals(a) && hri_b.equals(b))) {
            throw new IOException("Splitting node " + node + " is for " + a + ", " + b
                + ", not expected daughters: " + hri_a + ", " + hri_b);
          }
          // Master has processed it.
          zstd.setZnodeVersion(stat.getVersion());
          return;
        }
        if (et != RS_ZK_REQUEST_REGION_SPLIT) {
          throw new IOException("Splitting node " + node + " moved out of splitting to " + et);
        }
      }
      // Server is stopping/stopped
      throw new IOException("Server is " + (services.isStopping() ? "stopping" : "stopped"));
    } catch (Exception e) {
      if (e instanceof InterruptedException) {
        Thread.currentThread().interrupt();
      }
      throw new IOException("Failed getting SPLITTING znode on " +
        parent.getRegionInfo().getRegionNameAsString(), e);
    }
  }

  /**
   * Finish off split transaction, transition the zknode
   * @param services Used to online/offline regions.
   * @param a daughter region
   * @param b daughter region
   * @param std split transaction details
   * @param parent
   * @throws IOException If thrown, transaction failed. Call
   *  {@link org.apache.hadoop.hbase.regionserver.SplitTransaction#rollback(
   *  Server, RegionServerServices)}
   */
  @Override
  public void completeSplitTransaction(final RegionServerServices services, Region a, Region b,
      SplitTransactionDetails std, Region parent) throws IOException {
    ZkSplitTransactionDetails zstd = (ZkSplitTransactionDetails) std;
    // Tell master about split by updating zk. If we fail, abort.
    if (coordinationManager.getServer() != null) {
      try {
        zstd.setZnodeVersion(transitionSplittingNode(parent.getRegionInfo(), a.getRegionInfo(),
          b.getRegionInfo(), coordinationManager.getServer().getServerName(), zstd,
          RS_ZK_REGION_SPLITTING, RS_ZK_REGION_SPLIT));

        int spins = 0;
        // Now wait for the master to process the split. We know it's done
        // when the znode is deleted. The reason we keep tickling the znode is
        // that it's possible for the master to miss an event.
        do {
          if (spins % 10 == 0) {
            LOG.debug("Still waiting on the master to process the split for "
                + parent.getRegionInfo().getEncodedName());
          }
          Thread.sleep(100);
          // When this returns -1 it means the znode doesn't exist
          zstd.setZnodeVersion(transitionSplittingNode(parent.getRegionInfo(), a.getRegionInfo(),
            b.getRegionInfo(), coordinationManager.getServer().getServerName(), zstd,
            RS_ZK_REGION_SPLIT, RS_ZK_REGION_SPLIT));
          spins++;
        } while (zstd.getZnodeVersion() != -1 && !coordinationManager.getServer().isStopped()
            && !services.isStopping());
      } catch (Exception e) {
        if (e instanceof InterruptedException) {
          Thread.currentThread().interrupt();
        }
        throw new IOException("Failed telling master about split", e);
      }
    }

    // Leaving here, the splitdir with its dross will be in place but since the
    // split was successful, just leave it; it'll be cleaned when parent is
    // deleted and cleaned up.
  }

  @Override
  public void clean(final HRegionInfo hri) {
    try {
      // Only delete if its in expected state; could have been hijacked.
      if (!ZKAssign.deleteNode(coordinationManager.getServer().getZooKeeper(),
        hri.getEncodedName(), RS_ZK_REQUEST_REGION_SPLIT, coordinationManager.getServer()
            .getServerName())) {
        ZKAssign.deleteNode(coordinationManager.getServer().getZooKeeper(), hri.getEncodedName(),
          RS_ZK_REGION_SPLITTING, coordinationManager.getServer().getServerName());
      }
    } catch (KeeperException.NoNodeException e) {
      LOG.info("Failed cleanup zk node of " + hri.getRegionNameAsString(), e);
    } catch (KeeperException e) {
      coordinationManager.getServer().abort("Failed cleanup of " + hri.getRegionNameAsString(), e);
    }
  }

  /**
   * ZK-based implementation. Has details about whether the state transition should be reflected in
   * ZK, as well as expected version of znode.
   */
  public static class ZkSplitTransactionDetails implements
      SplitTransactionCoordination.SplitTransactionDetails {
    private int znodeVersion;

    public ZkSplitTransactionDetails() {
    }

    /**
     * @return znode current version
     */
    public int getZnodeVersion() {
      return znodeVersion;
    }

    /**
     * @param znodeVersion znode new version
     */
    public void setZnodeVersion(int znodeVersion) {
      this.znodeVersion = znodeVersion;
    }
  }

  @Override
  public SplitTransactionDetails getDefaultDetails() {
    ZkSplitTransactionDetails zstd = new ZkSplitTransactionDetails();
    zstd.setZnodeVersion(-1);
    return zstd;
  }

  @Override
  public int processTransition(HRegionInfo p, HRegionInfo hri_a, HRegionInfo hri_b, ServerName sn,
      SplitTransactionDetails std) throws IOException {
    return transitionSplittingNode(p, hri_a, hri_b, sn, std, RS_ZK_REQUEST_REGION_SPLIT,
      RS_ZK_REGION_SPLITTING);

  }
}


text:
package com.nortal.petit.orm.persist;

import java.util.Collection;

import javax.persistence.PersistenceException;

import com.nortal.petit.beanmapper.BeanMapping;
import com.nortal.petit.beanmapper.BeanMappings;
import com.nortal.petit.beanmapper.Property;

/**
 * @author Aleksei Lissitsin
 *
 */
public class BeanHandler<B> implements ItemHandler<B> {

    private Property<B, Object> id;

    public BeanHandler() {
    }

    public BeanHandler(BeanMapping<B> mapping) {
        init(mapping);
    }

    public BeanHandler<B> init(Property<B, Object> id) {
        this.id = id;
        return this;
    }

    public BeanHandler<B> init(BeanMapping<B> mapping) {
        if (mapping.id() == null) {
            throw new PersistenceException("No id mapping in " + mapping);
        }
        return init(mapping.id());
    }

    public BeanHandler<B> init(Collection<B>... col) {
        Class<B> clazz = inferClass(col);
        if (clazz == null) {
            return null;
        }
        return init(BeanMappings.get(clazz));
    }

    @SuppressWarnings("unchecked")
    private static <B> Class<B> inferClass(Collection<B>[] col) {
        for (Collection<B> c : col) {
            if (c != null && !c.isEmpty()) {
                return (Class<B>) c.iterator().next().getClass();
            }
        }
        return null;
    }

    @Override
    public Object id(B b) {
        return id.read(b);
    }

    @Override
    public B initItem(B b) {
        return b;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>biz.aQute.bnd-test</groupId>
		<artifactId>test</artifactId>
		<version>0.0.2</version>
	</parent>
	<artifactId>test-bnd-process-tests-goal</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.opensource.org/licenses/apache2.0.php</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<properties>
		<someVar>value</someVar>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>osgi.cmpn</artifactId>
			<version>6.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>osgi.annotation</artifactId>
			<version>6.0.1</version>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>test.api.bundle</artifactId>
			<version>0.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.servicemix.bundles</groupId>
			<artifactId>org.apache.servicemix.bundles.junit</artifactId>
			<version>4.12_1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>biz.aQute.bnd</groupId>
				<artifactId>bnd-maven-plugin</artifactId>
				<executions>
					<execution>
						<id>bnd-process-tests</id>
						<goals>
							<goal>bnd-process-tests</goal>
						</goals>
						<configuration>
							<testCases>junit4</testCases>
							<bndfile>tests.bnd</bndfile>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>3.1.0</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<executions>
					<execution>
						<id>test-jar</id>
						<goals>
							<goal>test-jar</goal>
						</goals>
						<configuration>
							<archive>
								<manifestFile>${project.build.testOutputDirectory}/META-INF/MANIFEST.MF</manifestFile>
							</archive>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>