text:
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Pipeline.Configuration
{
    using System;
    using Exceptions;
    using Sinks;

    public class OutboundMessageInterceptorConfigurator
    {
        readonly IPipelineSink<ISendContext> _sink;

        public OutboundMessageInterceptorConfigurator(IPipelineSink<ISendContext> sink)
        {
            _sink = sink;
        }

        public OutboundMessageInterceptor Create(IOutboundMessageInterceptor messageInterceptor)
        {
            var scope = new OutboundMessageInterceptorConfiguratorScope();
            _sink.Inspect(scope);

            return ConfigureInterceptor(scope.InsertAfter, messageInterceptor);
        }

        static OutboundMessageInterceptor ConfigureInterceptor(
            Func<IPipelineSink<ISendContext>, IPipelineSink<ISendContext>> insertAfter,
            IOutboundMessageInterceptor messageInterceptor)
        {
            if (insertAfter == null)
                throw new PipelineException("Unable to insert filter into pipeline for message type " +
                                            typeof (object).FullName);

            var interceptor = new OutboundMessageInterceptor(insertAfter, messageInterceptor);

            return interceptor;
        }
    }
}


text:
import React from 'react';
import * as MaterialIcons from '@styled-icons/material';
import { Button, Box2 } from '../../..';
export default function ShrinkingIcon() {
  return React.createElement(Box2, {
    display: "flex"
  }, React.createElement(Box2, {
    width: "100%"
  }, "Some text"), React.createElement(Button, {
    iconBefore: React.createElement(MaterialIcons.AddCircle, null)
  }, "Button"));
}
//# sourceMappingURL=ShrinkingIcon.js.map

redpajama_set_name: RedPajamaGithub


text:
//////////////////////////////////////////////////////////////////////////
// glw_label class
//////////////////////////////////////////////////////////////////////////

class glw_label : glw_window
{
public:
	// constructor & destructor
	glw_label();
	virtual ~glw_label();

public:
	// draws the window
	virtual void render() const;

protected:
	// mouse button was pressed
	virtual bool wm_mousedown(glw_mousekey button, int x, int y) { return true; }

	// mouse button was released
	virtual bool wm_mouseup(glw_mousekey button, int x, int y) { return true; }

	// keyboard has been pressed
	virtual bool wm_keydown(glw_key key) { return true; }

	// keyboard has been released
	virtual bool wm_keyup(glw_key key) { return true; }
};

//////////////////////////////////////////////////////////////////////////
// End
//////////////////////////////////////////////////////////////////////////

#endif


text:
package mflagext

import (
	"fmt"

	"github.com/docker/docker/pkg/mflag"
)

type listOpts struct {
	value      *[]string
	hasBeenSet bool
}

func ListVar(p *[]string, names []string, value []string, usage string) {
	*p = value
	mflag.Var(&listOpts{p, false}, names, usage)
}

func (opts *listOpts) Set(value string) error {
	if opts.hasBeenSet {
		(*opts.value) = append((*opts.value), value)
	} else {
		(*opts.value) = []string{value}
		opts.hasBeenSet = true
	}
	return nil
}

func (opts *listOpts) String() string {
	return fmt.Sprintf("%v", []string(*opts.value))
}


text:
"""Fix UserDict.

Incomplete!

TODO: base this on fix_urllib perhaps?
"""

# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name, attr_chain
from lib2to3.fixes.fix_imports import alternates, build_pattern, FixImports

MAPPING = {'UserDict':  'collections',
}

# def alternates(members):
#     return "(" + "|".join(map(repr, members)) + ")"
#
#
# def build_pattern(mapping=MAPPING):
#     mod_list = ' | '.join(["module_name='%s'" % key for key in mapping])
#     bare_names = alternates(mapping.keys())
#
#     yield """name_import=import_name< 'import' ((%s) |
#                multiple_imports=dotted_as_names< any* (%s) any* >) >
#           """ % (mod_list, mod_list)
#     yield """import_from< 'from' (%s) 'import' ['(']
#               ( any | import_as_name< any 'as' any > |
#                 import_as_names< any* >)  [')'] >
#           """ % mod_list
#     yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > |
#                multiple_imports=dotted_as_names<
#                  any* dotted_as_name< (%s) 'as' any > any* >) >
#           """ % (mod_list, mod_list)
#
#     # Find usages of module members in code e.g. thread.foo(bar)
#     yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names

# class FixUserDict(fixer_base.BaseFix):
class FixUserdict(FixImports):

    BM_compatible = True
    keep_line_order = True
    # This is overridden in fix_imports2.
    mapping = MAPPING

    # We want to run this fixer late, so fix_import doesn't try to make stdlib
    # renames into relative imports.
    run_order = 6

    def build_pattern(self):
        return "|".join(build_pattern(self.mapping))

    def compile_pattern(self):
        # We override this, so MAPPING can be pragmatically altered and the
        # changes will be reflected in PATTERN.
        self.PATTERN = self.build_pattern()
        super(FixImports, self).compile_pattern()

    # Don't match the node if it's within another match.
    def match(self, node):
        match = super(FixImports, self).match
        results = match(node)
        if results:
            # Module usage could be in the trailer of an attribute lookup, so we
            # might have nested matches when "bare_with_attr" is present.
            if "bare_with_attr" not in results and \
                    any(match(obj) for obj in attr_chain(node, "parent")):
                return False
            return results
        return False

    def start_tree(self, tree, filename):
        super(FixImports, self).start_tree(tree, filename)
        self.replace = {}

    def transform(self, node, results):
        import_mod = results.get("module_name")
        if import_mod:
            mod_name = import_mod.value
            new_name = unicode(self.mapping[mod_name])
            import_mod.replace(Name(new_name, prefix=import_mod.prefix))
            if "name_import" in results:
                # If it's not a "from x import x, y" or "import x as y" import,
                # marked its usage to be replaced.
                self.replace[mod_name] = new_name
            if "multiple_imports" in results:
                # This is a nasty hack to fix multiple imports on a line (e.g.,
                # "import StringIO, urlparse"). The problem is that I can't
                # figure out an easy way to make a pattern recognize the keys of
                # MAPPING randomly sprinkled in an import statement.
                results = self.match(node)
                if results:
                    self.transform(node, results)
        else:
            # Replace usage of the module.
            bare_name = results["bare_with_attr"][0]
            new_name = self.replace.get(bare_name.value)
            if new_name:
                bare_name.replace(Name(new_name, prefix=bare_name.prefix))


text:
/**
 * @file
 **/

#define protected public
#define private public
#include "modules/planning/scenarios/traffic_light/unprotected_right_turn/traffic_light_unprotected_right_turn_scenario.h"

#include "gtest/gtest.h"

#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace traffic_light {

class TrafficLightUnprotectedRightTurnScenarioTest : public ::testing::Test {
 public:
  virtual void SetUp() {}

 protected:
  std::unique_ptr<TrafficLightUnprotectedRightTurnScenario> scenario_;
};

TEST_F(TrafficLightUnprotectedRightTurnScenarioTest, VerifyConf) {
  FLAGS_scenario_traffic_light_unprotected_right_turn_config_file =
      "/apollo/modules/planning/conf/"
      "scenario/traffic_light_unprotected_right_turn_config.pb.txt";

  ScenarioConfig config;
  EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
      FLAGS_scenario_traffic_light_unprotected_right_turn_config_file,
      &config));
}

TEST_F(TrafficLightUnprotectedRightTurnScenarioTest, Init) {
  FLAGS_scenario_traffic_light_unprotected_right_turn_config_file =
      "/apollo/modules/planning/testdata/conf/"
      "scenario/traffic_light_unprotected_right_turn_config.pb.txt";

  ScenarioConfig config;
  EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile(
      FLAGS_scenario_traffic_light_unprotected_right_turn_config_file,
      &config));

  ScenarioContext context;
  scenario_.reset(
      new TrafficLightUnprotectedRightTurnScenario(config, &context));
  EXPECT_EQ(scenario_->scenario_type(),
            ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN);
}

}  // namespace traffic_light
}  // namespace scenario
}  // namespace planning
}  // namespace apollo


text:
<?php

namespace Symfony\Component\Config\Definition;

@trigger_error('The '.__NAMESPACE__.'\ReferenceDumper class is deprecated since version 2.4 and will be removed in 3.0. Use the Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper class instead.', E_USER_DEPRECATED);

use Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper;

/**
 * @deprecated since version 2.4, to be removed in 3.0.
 *             Use {@link \Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper} instead.
 */
class ReferenceDumper extends YamlReferenceDumper
{
}


text:
'use strict';

const assert = require('assert');
const logging = require('lib/loggingService');
const libCC = require('lib/commandCenter');
const CommandCenter = libCC.CommandCenter;

describe('commandCenter', function () {
	describe('CommandCenter', function () {
		let cc;

		before(function () {
			// Hide "User command response cache disabled" log
			logging.filterContexts('responseCache');
			cc = new CommandCenter({
				name: 'test'
			});
			logging.filterContexts();
		});

		describe('registerMessageHook()', function () {
			it('Tests input types', function () {
				const badHook = function () {
				};

				const goodHook = function (state, data, batch, cb) {
					cb();
				};

				assert.throws(() => { libCC.registerMessageHook(123, false, goodHook); });
				assert.throws(() => { libCC.registerMessageHook('myhook', 123, goodHook); });
				assert.throws(() => { libCC.registerMessageHook('myhook', false, 123); });
				assert.throws(() => { libCC.registerMessageHook('myhook', false, badHook); });
				assert.doesNotThrow(() => { libCC.registerMessageHook('myhook', false, goodHook); });
			});
		});

		describe('setupUserCommand()', function () {
			it('Tests input types', function () {
				const mod = {
					execute: function (state, cb) {
						cb();
					}
				};

				assert.throws(() => { cc.setupUserCommand(123, 'login', mod); });
				assert.throws(() => { cc.setupUserCommand('user', 123, mod); });
				assert.throws(() => { cc.setupUserCommand('user', 'login', 123); });
				assert.throws(() => { cc.setupUserCommand('user', 'login', {}); }); // no execute
				assert.throws(() => { cc.setupUserCommand('user', 'login', { acl: 123, execute: () => {} }); });
				assert.throws(() => { cc.setupUserCommand('user', 'login', { execute: () => {} }); });
				assert.throws(() => { cc.setupUserCommand('user', 'login', { execute: (state) => {} }); }); // eslint-disable-line
			});

			it('Registers a user command', function () {
				const mod = {
					execute: function (state, cb) {
						cb();
					}
				};

				cc.setupUserCommand('user', 'login', mod);
			});

			it('If exports.default is present, its content is used for the user command (for TypeScript)', function () {
				const mod = {
					default: {
						execute: function (state, cb) {
							cb();
						}
					}
				};

				cc.setupUserCommand('user', 'login', mod);
			});

			it('User commands may be classes with static methods', function () {
				class mod {
					static execute(state, cb) {
						cb();
					}
				};

				cc.setupUserCommand('user', 'login', mod);
			});
		});

		describe('getPublicConfig()', function () {
			it('Communicates a user command', function () {
				const mod = {
					execute: function (state, foo, cb) {
						cb();
					}
				};

				cc.setupUserCommand('user', 'login', mod);
				const config = cc.getPublicConfig('');

				assert.equal(config.url, '/test');
				assert.deepEqual(config.commands, {
					user: [
						{ name: 'login', params: ['foo'] }
					]
				});
			});
		});

		describe('buildParamList()', function () {
			const cmdInfoModParams = ['a', 'b', 'c'];

			it('Tests input types', function () {
				assert.throws(() => { cc.buildParamList(123, []); });
				assert.throws(() => { cc.buildParamList([], 123); });
				assert.doesNotThrow(() => { cc.buildParamList([], []); });
				assert.doesNotThrow(() => { cc.buildParamList([], {}); });
			});

			it('should build the param list from an array of the same size', function () {
				const cmdParams = ['1', '2', '3'];
				const paramList = cc.buildParamList(cmdInfoModParams, cmdParams);
				assert.strictEqual(Array.isArray(paramList), true);
				assert.strictEqual(paramList.length, 3);
				assert.deepEqual(paramList, cmdParams);
			});

			it('should build the param list from a smaller array', function () {
				const cmdParams = ['1', '2'];
				const paramList = cc.buildParamList(cmdInfoModParams, cmdParams);
				assert.strictEqual(Array.isArray(paramList), true);
				assert.strictEqual(paramList.length, 3);
				assert.deepEqual(paramList, ['1', '2', undefined]);
			});

			it('should throw an exception if the array is too big', function () {
				const cmdParams = ['1', '2', '4', '5'];
				assert.throws(() => { cc.buildParamList(cmdInfoModParams, cmdParams); });
			});

			it('should build the param list from an object', function () {
				const cmdParams = {
					a: '1',
					b: '2',
					c: '3'
				};
				const paramList = cc.buildParamList(cmdInfoModParams, cmdParams);
				assert.strictEqual(Array.isArray(paramList), true);
				assert.strictEqual(paramList.length, 3);
				assert.deepEqual(paramList, ['1', '2', '3']);
			});

			it('should build the param list from an object with missing params', function () {
				const cmdParams = {
					a: '1',
					c: '2',
					e: '3'
				};
				const paramList = cc.buildParamList(cmdInfoModParams, cmdParams);
				assert.strictEqual(Array.isArray(paramList), true);
				assert.strictEqual(paramList.length, 3);
				assert.deepEqual(paramList, ['1', undefined, '2']);
			});

			it('should build the param list from an object with too many params', function () {
				const cmdParams = {
					a: '1',
					c: '2',
					e: '3',
					b: '4',
					g: '5'
				};
				const paramList = cc.buildParamList(cmdInfoModParams, cmdParams);
				assert.strictEqual(Array.isArray(paramList), true);
				assert.strictEqual(paramList.length, 3);
				assert.deepEqual(paramList, ['1', '4', '2']);
			});
		});
	});
});


text:
require "rails_helper"

RSpec.feature "Searching for Users" do

  before do
    @john = User.create!(first_name: "John", last_name: "Doe", email: "john@example.com", password: "password")
    @sarah = User.create!(first_name: "Sarah", last_name: "Doe", email: "sarah@example.com", password: "password")
  end

  scenario "using last name to find multiple members" do
    visit "/"
    fill_in "search_name", with: "Doe"
    click_button "Search"

    expect(page).to have_content(@john.full_name)
    expect(page).to have_content(@sarah.full_name)
    expect(page.current_path).to eq("/dashboards/search")
  end

end


text:
<?php

namespace NetSuite\Classes;

class SearchColumnEnumSelectField extends SearchColumnField {
    public $searchValue;
    static $paramtypesmap = array(
        "searchValue" => "string",
    );
}


text:
<?php

class Google_Service_Dfareporting_VideoFormatsListResponse extends Google_Collection
{
  protected $collection_key = 'videoFormats';
  public $kind;
  protected $videoFormatsType = 'Google_Service_Dfareporting_VideoFormat';
  protected $videoFormatsDataType = 'array';

  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setVideoFormats($videoFormats)
  {
    $this->videoFormats = $videoFormats;
  }
  public function getVideoFormats()
  {
    return $this->videoFormats;
  }
}


text:
{-# LANGUAGE TypeFamilies,RankNTypes,ImpredicativeTypes,FlexibleContexts,DeriveDataTypeable #-}
{-| Provides a common interface for all backend types.
 -}
module Language.GTL.Backend.All where

import Language.GTL.Expression
import Language.GTL.Backend
import Language.GTL.Backend.Scade
import Language.GTL.Backend.None
import Language.GTL.Types
import Data.Map
import Data.Typeable

import Control.Monad.Error (MonadError(..))

import Misc.ProgramOptions as Opts

-- | Essentially a `GTLBackend' with the parameters instantiated, thus eliminating
--   the type variable.
data AllBackend = AllBackend
                  { allTypecheck :: MonadError String m => ModelInterface -> m ModelInterface
                  , allAliases :: Map String GTLType
                  , allCInterface :: CInterface
                  , allVerifyLocal :: Integer -> [TypedExpr String] -> Map String GTLType -> Map String (Maybe GTLConstant) -> Map String (GTLType, GTLConstant) -> Opts.Options -> String -> IO (Maybe Bool)
                  } deriving Typeable

instance Show AllBackend where
  show _ = "AllBackend"

instance Eq AllBackend where
  (==) _ _ = False

instance Ord AllBackend where
  compare _ _ = LT

-- | Try to initialize a given backend with a name and arguments.
--   If it works, it'll return Just with the 'AllBackend' representation.
tryInit :: GTLBackend b => b -> String -> Opts.Options -> [String] -> IO (Maybe AllBackend)
tryInit be name opts args
  | backendName be == name = do
    dat <- initBackend be opts args
    return $ Just $ AllBackend
      { allTypecheck = typeCheckInterface be dat
      , allAliases = backendGetAliases be dat
      , allCInterface = cInterface be dat
      , allVerifyLocal = backendVerify be dat
      }
  | otherwise = return Nothing

-- | Returns the first result that is not 'Nothing' from a list of functions
--   by applying the arguments to them.
firstM :: Monad m => [x -> y -> z -> m (Maybe a)] -> x -> y -> z -> m (Maybe a)
firstM (x:xs) p q r = do
  res <- x p q r
  case res of
    Nothing -> firstM xs p q r
    Just rr -> return (Just rr)
firstM [] _ _ _ = return Nothing

-- | Try to initialize the correct backend for a given backend name and arguments.
initAllBackend :: String -- ^ The name of the backend
                  -> Opts.Options -- ^ Options for the whole program
                  -> [String] -- ^ The arguments with which to initialize the backend
                  -> IO (Maybe AllBackend)
initAllBackend = firstM [tryInit Scade,tryInit None]


text:
package com.app.social.simplesocialapp.registration;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.app.social.simplesocialapp.R;

import model.User;
import util.Utils;

public class SignUpActivity extends BaseRegistrationActivity {

    private EditText mEmailView;
    private EditText mPasswordView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        mEmailView = (EditText) findViewById(R.id.email);

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    signUp();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                signUp();
            }
        });

    }

    public void signUp() {
        mEmailView.setError(null);
        mPasswordView.setError(null);

        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (!TextUtils.isEmpty(password) && !Utils.isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!Utils.isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        Utils.hideKeyboard(mEmailView);

        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);
            User newUser = new User();
            newUser.setEmail(email);
            try {
                String hash = Utils.generateUserHash(email + password);
                newUser.setUserHash(hash);
                if (checkIfUserExistsInDB(newUser)) {
                    showErrorToast(getString(R.string.already_registered_error_message));
                    return;
                }
                mDatabaseHelper.getDao().createIfNotExists(newUser);
                goToProfileActivity(newUser);
            } catch (Exception e) {
                e.printStackTrace();
                showErrorToast(null);
            }
        }
    }
}


text:
<?php
use Vks\Core\XmlSettingsManager;

$xml = new XmlSettingsManager('config/ipPhones-settings.xml');
$firstPart = (array) $xml->getXmlSettings('first-part')->val;
$limit = (array) $xml->getXmlSettings('second-part')[0];
$limit = (int)$limit['limit'];
?>

                <select class="form-control text-center fp-ip-phone" name="fp-ip-phone">
                    <?php foreach ($firstPart as $val)
                                echo "<option>{$val}</option>";
                    ?>
                </select>

                <input class='form-control sp-ip-phone'  name="sp-ip-phone" maxlength="<?= $limit; ?>"/>

                    <button class='btn btn-info' type='button' id='add-ip-phone'> Добавить</button>


text:
module EducatorResourcesHelper
end


text:
require File.dirname(__FILE__) + '/test_helper'

class TableizeHelperTest < Test::Unit::TestCase
  include Widgets

  EXPECTED_INSTANCE_METHODS = %w{tableize}

  def setup
    @view = ActionView::Base.new
    @view.extend ApplicationHelper
    @view.extend TableHelper
  end

  def test_presence_of_instance_methods
    EXPECTED_INSTANCE_METHODS.each do |instance_method|
      assert @view.respond_to?(instance_method), "#{instance_method} is not defined in #{@controller.inspect}"
    end
  end

  def test_should_fail_if_wrong_args
    assert_raise(ArgumentError) do
      @view.tableize nil
    end
    assert_raise(ArgumentError) do
      @view.tableize []
    end
    assert_raise(ArgumentError) do
      @view.tableize nil, :name => 'main'
    end
    assert_raise(ArgumentError) do
      @view.tableize [], :name => 'main'
    end
    assert_raise(ArgumentError) do
      @view.tableize [], :cols => 1, :name => :the_name do
        # nothing
      end
    end
  end

  def test_block_invariance
    _erbout = ''
    assert_nothing_raised do
      @view.tableize ['IS', 'Same!', 'Thing?'], :name => :the_name do |i|
        _erbout.concat i
      end
    end
    expected, _erbout = _erbout, ''
    assert_nothing_raised do
      @view.tableize(['IS', 'Same!', 'Thing?'], :name => :the_name) { |i| _erbout.concat i }
    end
    assert_dom_equal expected, _erbout, 'Block vs Proc generation differs'
  end

  def test_empty_layout
    _erbout = ''
    @view.tableize [], :cols => 2, :name => :empty_layout do |i|
      _erbout.concat 'nowhere'
    end
    root = HTML::Document.new(_erbout).root
    assert_select root, 'table.empty_layout_table:root', :count => 1 do
      assert_select 'tbody:only-of-type' do
        assert_select 'tr', :count => 1
        assert_select 'tr td', :count => 0
      end
    end
  end

  def test_1_item_layout
    _erbout = ''
    @view.tableize [1], :name => '1_item_layout' do |i|
      _erbout.concat i.to_s
    end
    root = HTML::Document.new(_erbout).root
    assert_select root, 'table.1_item_layout_table:root', :count => 1 do
      assert_select 'tbody:only-of-type' do
        assert_select 'tr', :count => 1
        assert_select 'tr:first-of-type td', :count => 3 do
          assert_select 'td:first-of-type', '1'
          assert_select 'td.blank:nth-of-type(2)', ' '
          assert_select 'td.blank:last-of-type', ' '
        end
      end
    end
  end

  def test_row_less_1_item_layout
    _erbout = ''
    @view.tableize %w{1 2 3 4 5}, :cols => 6, :name => 'row_less_1_item_layout' do |i|
      _erbout.concat i.to_s
    end
    root = HTML::Document.new(_erbout).root
    assert_select root, 'table.row_less_1_item_layout_table:root', :count => 1 do
      assert_select 'tbody:only-of-type' do
        assert_select 'tr', :count => 1
        assert_select 'tr:first-of-type td', 6 do
          assert_select 'td:first-of-type', '1'
          assert_select 'td:nth-of-type(2)', '2'
          assert_select 'td:nth-of-type(3)', '3'
          assert_select 'td:nth-of-type(4)', '4'
          assert_select 'td:nth-of-type(5)', '5'
          assert_select 'td.blank:last-of-type', ' '
        end
      end
  end
  end

  def test_full_row_layout
    _erbout = ''
    @view.tableize %w{1 2 3 4 5}, :cols => 5, :name => :full_row_layout  do |i|
      _erbout.concat i.to_s
    end
    root = HTML::Document.new(_erbout).root
    assert_select root, 'table.full_row_layout_table:root', :count => 1 do
      assert_select 'tbody:only-of-type' do
        assert_select 'tr', :count => 1
        assert_select 'tr:first-of-type td', :count => 5 do
          assert_select 'td:first-of-type', '1'
          assert_select 'td:nth-of-type(2)', '2'
          assert_select 'td:nth-of-type(3)', '3'
          assert_select 'td:nth-of-type(4)', '4'
          assert_select 'td:last-of-type', '5'
        end
      end
    end
  end

  def test_row_plus_1_item_layout
    _erbout = ''
    @view.tableize %w{1 2 3 4 5}, :cols => 4, :name=> 'row_plus_1_item_layout' do |i|
      _erbout.concat i.to_s
    end
    root = HTML::Document.new(_erbout).root
    assert_select root, 'table.row_plus_1_item_layout_table:root', :count => 1 do
      assert_select 'tbody:only-of-type' do
        assert_select 'tr', :count => 2
        assert_select 'tr:first-of-type td', :count => 4 do
          assert_select 'td:first-of-type', '1'
          assert_select 'td:nth-of-type(2)', '2'
          assert_select 'td:nth-of-type(3)', '3'
          assert_select 'td:last-of-type', '4'
        end
        assert_select 'tr:last-of-type td', :count => 4 do
          assert_select 'td:first-of-type', '5'
          assert_select 'td.blank:nth-of-type(2)', ' '
          assert_select 'td.blank:nth-of-type(3)', ' '
          assert_select 'td.blank:last-of-type', ' '
        end
      end
    end
  end

  def test_options
    _erbout = ''
    @view.tableize nil,
    :name => :options,
    :collection => %w{1 2 3 4 5},
    :generate_css => true,
    :header => 'TiTlE',
    :html => {:id => 'number', :class => 'demo'},
    :cols => 4 do |i|
      _erbout.concat i.to_s
    end
    root = HTML::Document.new(_erbout).root
    assert_select root, 'style:root', :count => 1
    assert_select root, 'table[class=demo][id=number]:root', :count => 1 do
      assert_select 'tbody:only-of-type' do
        assert_select 'tr', :count => 2
        assert_select 'tr:first-of-type th, tr:first-of-type td', :count => 4 do
          assert_select 'th:first-child', 'TiTlE'
          assert_select 'th:only-of-type', 'TiTlE'
          assert_select 'td:first-of-type', '1'
          assert_select 'td:nth-child(2)', '1'
          assert_select 'td:nth-of-type(2)', '2'
          assert_select 'td:last-of-type', '3'
          assert_select 'td:nth-child(4)', '3'
        end
        assert_select 'tr:last-of-type td', :count => 4 do
          assert_select 'td:first-of-type', '4'
          assert_select 'td:nth-of-type(2)', '5'
          assert_select 'td.blank:nth-of-type(3)', ' '
          assert_select 'td.blank:last-of-type', ' '
        end
      end
    end
  end

end


text:
package com.abewy.android.apps.klyph.fragment;

import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import com.abewy.android.apps.klyph.R;
import com.abewy.android.apps.klyph.adapter.MultiObjectAdapter;
import com.abewy.android.apps.klyph.core.graph.GraphObject;
import com.abewy.android.apps.klyph.core.request.RequestError;
import com.abewy.android.apps.klyph.core.request.Response;
import com.abewy.android.apps.klyph.request.AsyncRequest;
import com.abewy.android.apps.klyph.request.AsyncRequest.Query;
import com.abewy.android.apps.klyph.view.ListEmptyView;
import com.abewy.app.BaseDialogListFragment;
import com.abewy.klyph.items.Progress;
import com.abewy.klyph.items.TextButtonItem;
import com.abewy.net.ConnectionState;

public class KlyphDialogFragment extends BaseDialogListFragment implements OnScrollListener
{
	private final String	TAG							= "KlyphDialogFragment " + this.getClass().getSimpleName();

	private AsyncRequest	request;
	private boolean			userScroll					= false;
	private boolean			loading						= false;
	private boolean			firstLoad					= true;
	private boolean			isError						= false;
	private boolean			viewDestroyed				= false;
	private boolean			noMoreData					= false;
	private boolean			loadingObjectAsFirstItem	= false;
	private GraphObject		loadingObject;
	private int				emptyText;
	private int				errorText = R.string.error;
	private View			loadingView;
	private boolean			listVisible					= false;

	private int				requestType;
	private String			elementId;
	private String			offset;
	private String			initialOffset;

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState)
	{
		super.onViewCreated(view, savedInstanceState);

		getListView().setOnScrollListener(this);

		getListView().setVisibility(View.GONE);
		((View) getListView().getParent()).setVisibility(View.GONE);
		loadingView = view.findViewById(android.R.id.progress);

		defineEmptyView();

		loadingObject = getLoadingObject();
		loadingObject.setLoading(true);

		// setListVisible(false);
		// setEmptyViewVisible(false);
	}

	/**
	 * Create, add and set the list empty view Override this method if you want
	 * a custom empty view, or if you replaced listview by a gridview for
	 * example
	 */
	protected void defineEmptyView()
	{
		ListEmptyView lev = new ListEmptyView(getActivity());
		((ViewGroup) getListView().getParent()).addView(lev);

		getListView().setEmptyView(lev);

		if (this.emptyText > 0)
			setEmptyText(emptyText);
	}

	public void setElementId(String id)
	{
		this.elementId = id;
	}

	public void setListAdapter(ListAdapter adapter)
	{
		getListView().setAdapter(adapter);
	}

	protected String getElementId()
	{
		return elementId;
	}

	protected void setOffset(String offset)
	{
		this.offset = offset;
	}

	protected void setInitialOffset(String offset)
	{
		this.initialOffset = offset;
	}

	protected void setRequestType(int requestType)
	{
		this.requestType = requestType;
	}

	protected void setNoMoreData(boolean noMoreData)
	{
		this.noMoreData = noMoreData;
	}

	protected void setLoadingObjectAsFirstItem(boolean loadingObjectAsFirstItem)
	{
		this.loadingObjectAsFirstItem = loadingObjectAsFirstItem;
	}

	private void setViewDestroyed(boolean viewDestroyed)
	{
		this.viewDestroyed = viewDestroyed;
	}

	protected boolean isViewDestroyed()
	{
		return viewDestroyed;
	}

	protected boolean isLoading()
	{
		return loading;
	}

	protected boolean isFirstLoad()
	{
		return firstLoad;
	}

	protected boolean hasNoMoreData()
	{
		return noMoreData;
	}

	protected boolean requestHasMoreData()
	{
		return request.hasMoreData();
	}

	protected void defineEmptyText(int resId)
	{
		this.emptyText = resId;
		setEmptyText(resId);
	}

	protected void setEmptyText(int resId)
	{
		if (getListView().getEmptyView() != null)
		{
			((ListEmptyView) getListView().getEmptyView()).setText(resId);
		}
	}

	protected void setErrorText(int resId)
	{
		this.errorText = resId;
	}

	public void load()
	{
		// Log.i(TAG, "load");

		if ((isFirstLoad() && !isLoading()) || isViewDestroyed())
		{
			setViewDestroyed(false);
			setOffset(initialOffset);
			setNoMoreData(false);
			firstLoad = true;

			refresh();
		}
	}

	protected void refresh()
	{
		startLoading();
		Log.d(TAG, "request = " + requestType + ", id = " + elementId + ", offset = " + offset);

		request = new AsyncRequest(requestType, elementId, offset, new AsyncRequest.Callback() {

			@Override
			public void onComplete(Response response)
			{
				Log.i(TAG, "onCompleted");
				onRequestComplete(response);
			}
		});
		request.execute();
	}

	private void onRequestComplete(final Response response)
	{
		if (getActivity() != null)
		{
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run()
				{
					if (response.getError() == null)
					{
						onRequestSuccess(response.getGraphObjectList());
					}
					else
					{
						onRequestError(response.getError());
					}
				}
			});
		}
	}

	private void onRequestSuccess(List<GraphObject> result)
	{
		if (getView() != null) // Check if view is created
			populate(result);
	}

	private void onRequestError(RequestError error)
	{
		Log.i(TAG, "error " + error.toString());
		if (getView() != null)
		{
			isError = true;
			loading = false;

			int errorText = this.errorText;

			if (!ConnectionState.getInstance(getActivity()).isOnline())
			{
				errorText = R.string.request_connexion_error;
			}

			TextButtonItem errorItem = new TextButtonItem();
			errorItem.setText(getString(errorText));

			// TODO This is not a good copding practice !
			errorItem.setButtonListener(new View.OnClickListener() {

				@Override
				public void onClick(View v)
				{
					retryRequestAfterError();
				}
			});

			getAdapter().add(errorItem);
			endLoading();
		}
	}

	protected MultiObjectAdapter getAdapter()
	{
		return (MultiObjectAdapter) getListView().getAdapter();
	}

	protected void populate(List<GraphObject> data)
	{
		for (GraphObject graphObject : data)
		{
			getAdapter().add(graphObject);
		}
		// adapter.addAll(data); is only available in api 11

		// getAdapter().notifyDataSetChanged();

		endLoading();

		if (data.size() == 0 || (request != null && !request.hasMoreData()))
			noMoreData = true;
		else
			offset = String.valueOf(getAdapter().getCount());
	}

	protected void startLoading()
	{
		loading = true;

		if (isError == true && getAdapter().getCount() > 0)
		{
			GraphObject lastObject = getAdapter().getLastItem();

			if (lastObject instanceof TextButtonItem)
			{
				getAdapter().remove(lastObject);
			}
		}

		isError = false;

		if (!firstLoad)
		{
			if (!loadingObjectAsFirstItem)
				getAdapter().add(loadingObject);
			else
				getAdapter().insert(loadingObject, 0);

			getAdapter().notifyDataSetChanged();
		}
	}

	protected void endLoading()
	{
		loading = false;
		firstLoad = false;

		getAdapter().remove(loadingObject);
		getAdapter().notifyDataSetChanged();

		setLoadingViewVisible(false);
		setListVisible(true);
	}

	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	{
		if (userScroll)
		{
			if (!loading && !firstLoad && !noMoreData && !isError)
			{
				boolean  loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;

				if (loadMore)
				{
					// Log.i(TAG, "onScroll refresh");
					refresh();
				}
			}
		}
	}

	public void onScrollStateChanged(AbsListView view, int scrollState)
	{
		userScroll = scrollState != OnScrollListener.SCROLL_STATE_IDLE;
	}

	protected GraphObject getLoadingObject()
	{
		return new Progress();
	}

	protected int getLayout()
	{
		return R.layout.list;
	}

	@Override
	protected void setListVisible(boolean visible)
	{
		setListVisibility(visible, true);
	}

	protected void setListVisible(boolean visible, boolean animate)
	{
		setListVisibility(visible, animate);
	}

	private void setListVisibility(boolean visible, boolean animate)
	{
		ensureList();

		if (listVisible == visible)
		{
			return;
		}

		listVisible = visible;

		View parent = (View) getListView().getParent();

		if (visible)
		{
			if (animate)
			{
				loadingView.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
				parent.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
			}
			else
			{
				loadingView.clearAnimation();
				parent.clearAnimation();
			}
			loadingView.setVisibility(View.GONE);
			parent.setVisibility(View.VISIBLE);
		}
		else
		{
			if (animate)
			{
				loadingView.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
				parent.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
			}
			else
			{
				loadingView.clearAnimation();
				parent.clearAnimation();
			}
			loadingView.setVisibility(View.VISIBLE);
			parent.setVisibility(View.GONE);
		}
	}

	protected void ensureList()
	{
		//getListView().setEmptyView(getView().findViewById(android.R.id.empty));
	}

	@Override
	public void onPause()
	{
		super.onPause();
		// Log.i(TAG, "onPause");
	}

	@Override
	public void onStop()
	{
		super.onStop();
		Log.i(TAG, "onStop");
	}

	@Override
	public void onDestroyView()
	{
		super.onDestroyView();
		setViewDestroyed(true);
		// Log.i(TAG, "onDestroyView");
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		request = null;
		loadingObject = null;
		loadingView = null;
		requestType = Query.NONE;
		Log.i(TAG, "onDestroy");
	}

	@Override
	public void onDetach()
	{
		super.onDetach();
		Log.i(TAG, "onDetach");
	}

	@Override
	public void onStart()
	{
		super.onStart();
		// Log.i(TAG, "onStart");
	}

	@Override
	public void onResume()
	{
		super.onResume();

		if (getAdapter() != null)
		{
			getAdapter().notifyDataSetChanged();
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
		Log.i(TAG, "onSaveInstanceState");
	}

	public void retryRequestAfterError()
	{
		Log.d(TAG, "retryRequestAfterError ");
		setEmptyText(emptyText);
		refresh();
	}
}


text:
function Invoke-RivetTestQuery
{
    [CmdletBinding(DefaultParameterSetName='AsReader')]
    param(
        [string]
        $Query,

        [Data.SqlClient.SqlConnection]
        $Connection,

        [Switch]
        # Use the master connection, instead of the database connection.
        $Master,

        [Parameter(ParameterSetName='AsScalar')]
        [Switch]
        $AsScalar,

        [Parameter()]
        # The timeout to use, in seconds.
        $Timeout,

        [string]
        $DatabaseName
    )

    Set-StrictMode -Version Latest

    if( -not $DatabaseName )
    {
        $DatabaseName = $RTDatabaseName
    }

    if( $Master )
    {
        $DatabaseName = 'master'
    }

    if( -not $connection -or $connection.State -ne [Data.ConnectionState]::Open )
    {
        $Connection = New-SqlConnection -Database $DatabaseName
        Write-Debug -Message ('                {0}' -f $Connection.ConnectionString)
    }

    if( -not $PSBoundParameters.ContainsKey('Connection') )
    {
        if( $Connection.Database -ne $DatabaseName )
        {
            $Connection.ChangeDatabase( $DatabaseName )
            Write-Debug -Message ('                {0}' -f $Connection.ConnectionString)
        }
    }

    $cmdStartedAt = Get-Date
    try
    {
        $cmd = New-Object Data.SqlClient.SqlCommand ($Query,$Connection)
        if( $PSBoundParameters.ContainsKey( 'Timeout' ) )
        {
            $cmd.CommandTimeout = $Timeout
        }

        if( $PSCmdlet.ParameterSetName -eq 'AsScalar' )
        {
            return $cmd.ExecuteScalar()
        }
        else
        {
            $cmdReader = $cmd.ExecuteReader()
            try
            {
                if( -not $cmdReader.HasRows )
                {
                    return
                }

                while( $cmdReader.Read() )
                {
                    $row = @{ }
                    for ($i= 0; $i -lt $cmdReader.FieldCount; $i++)
                    {
                        $name = $cmdReader.GetName( $i )
                        if( -not $name )
                        {
                            $name = 'Column{0}' -f $i
                        }
                        $value = $cmdReader.GetValue($i)
                        if( $cmdReader.IsDBNull($i) )
                        {
                            $value = $null
                        }
                        $row[$name] = $value
                    }
                    New-Object PsObject -Property $row
                }
            }
            finally
            {
                $cmdReader.Close()
            }
        }

    }
    finally
    {
        $cmd.Dispose()
        $queryLines = $Query -split ([TExt.RegularExpressions.Regex]::Escape([Environment]::NewLine))
        Write-Verbose -Message ('{0,8} (ms)   {1}' -f ([int]((Get-Date) - $cmdStartedAt).TotalMilliseconds),($queryLines | Select-Object -First 1))
        $queryLines | Select-Object -Skip 1 | ForEach-Object {  Write-Verbose -Message ('{0}   {1}' -f (' ' * 13),$_) }
    }
}


text:
package livequery

import (
	"strings"

	"github.com/freeznet/tomato/config"
	"github.com/freeznet/tomato/livequery/pubsub"
	"github.com/freeznet/tomato/livequery/t"
)

// LiveQuery 接收指定类的对象保存与对象删除的通知,发送对象数据到发布者,由发布者通知订阅者,订阅者实时接收数据
type LiveQuery struct {
	classNames         map[string]bool
	liveQueryPublisher *pubsub.CloudCodePublisher
}

// TLiveQuery ...
var TLiveQuery *LiveQuery

func init() {
	classNames := strings.Split(config.TConfig.LiveQueryClasses, "|")
	pubType := config.TConfig.PublisherType
	pubURL := config.TConfig.PublisherURL
	pubConfig := config.TConfig.PublisherConfig
	TLiveQuery = NewLiveQuery(classNames, pubType, pubURL, pubConfig)
}

// NewLiveQuery 初始化 LiveQuery
// classNames 支持的类列表
// pubType 发布者类型
// pubURL 发布者的 URL
func NewLiveQuery(classNames []string, pubType, pubURL, pubConfig string) *LiveQuery {
	liveQuery := &LiveQuery{}
	liveQuery.classNames = map[string]bool{}
	if len(classNames) > 0 {
		for _, n := range classNames {
			liveQuery.classNames[n] = true
		}
	}
	liveQuery.liveQueryPublisher = pubsub.NewCloudCodePublisher(pubType, pubURL, pubConfig)

	return liveQuery
}

// OnAfterSave 保存对象之后调用
func (l *LiveQuery) OnAfterSave(className string, currentObject, originalObject map[string]interface{}) {
	if l.HasLiveQuery(className) == false {
		return
	}
	req := l.makePublisherRequest(currentObject, originalObject)
	l.liveQueryPublisher.OnCloudCodeAfterSave(req)
}

// OnAfterDelete 删除对象之后调用
func (l *LiveQuery) OnAfterDelete(className string, currentObject, originalObject map[string]interface{}) {
	if l.HasLiveQuery(className) == false {
		return
	}
	req := l.makePublisherRequest(currentObject, originalObject)
	l.liveQueryPublisher.OnCloudCodeAfterDelete(req)
}

// HasLiveQuery 是否有对应的 className
func (l *LiveQuery) HasLiveQuery(className string) bool {
	return l.classNames[className]
}

// makePublisherRequest 组装待发布的消息,格式如下
// {
// 	"object": {...},
// 	"original": {...}
// }
func (l *LiveQuery) makePublisherRequest(currentObject, originalObject t.M) t.M {
	req := t.M{
		"object": currentObject,
	}
	if currentObject != nil {
		req["original"] = originalObject
	}
	return req
}


text:
@ECHO OFF

SET LIB_PATH=..\lib
SET OUTPUT_FOLDER=..\bin

SET CLASSPATH=%OUTPUT_FOLDER%;%LIB_PATH%\terasoluna-batch-3.2.0.jar

SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\aspectjweaver-1.6.12.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\cglib-nodep-2.1_3.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-beanutils-1.8.3.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-collections-3.2.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-dbcp-1.2.2.patch_DBCP264_DBCP372.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-digester-1.8.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-jxpath-1.3.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-lang-2.5.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-logging-1.1.1.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-pool-1.6.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\commons-validator-1.3.1.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\mybatis-2.3.5.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\jakarta-oro-2.0.8.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\log4j-1.2.16.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-modules-validation-0.8.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-batch-update-1.1.2.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-collector-1.1.0.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-commons-2.0.5.0.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-dao-2.0.5.0.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-filedao-2.0.3.2.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-ibatis-2.0.5.0.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-validator-2.0.5.0.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\terasoluna-logger-1.0.0.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-aop-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-asm-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-beans-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-context-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-core-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-expression-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-jdbc-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-orm-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\spring-tx-3.1.3.RELEASE.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\aopalliance-1.0.jar

SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\ojdbc5.jar
SET CLASSPATH=%CLASSPATH%;%LIB_PATH%\postgresql-8.4-702.jdbc3.jar


text:
package net.kebernet.configuration.server;

import dagger.Module;
import dagger.Provides;
import net.kebernet.configuration.server.endpoint.DeviceResource;
import net.kebernet.configuration.server.endpoint.SettingsResource;
import net.kebernet.configuration.server.model.SettingValueRepository;
import net.kebernet.configuration.server.system.ScriptsInspector;
import net.kebernet.configuration.server.system.SystemInspector;

import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.time.Clock;

/**
 * Created by rcooper on 7/17/17.
 */

@SuppressWarnings("unused")
@Module(
        injects = {
                DefaultFileExporter.class,
                DeviceResource.class,
                SettingsResource.class,
                MulticastDNSService.class,
                WifiConfigWriter.class,
                SystemInspector.class,
                WifiMonitor.class
        }, library =  true
)
public class ServerModule {

    private final StartupParameters parameters;

    public ServerModule(StartupParameters parameters) {
        this.parameters = parameters;
    }

    @Provides
    @Named("storageDirectory")
    @Singleton
    public File storageDirectory(@Named("targetDirectory") File target) {
        return new File(target, parameters.getStorageDirectory());
    }

    @Provides
    @Named("targetDirectory")
    @Singleton
    public File targetDirectory() {
        return new File(parameters.getTargetDirectory());
    }

    @Provides
    @Singleton
    public StartupParameters parameters(){
        return parameters;
    }

    @Provides
    @Singleton
    @Named("hostMatchRegex")
    public String hostMatchRegex(){
        return parameters.getHostMatchRegex();
    }

    @Provides
    @Singleton
    @Named("defaultDeviceName")
    public String defaultDeviceName(){
        return WifiConfigWriter.computeDefaultName(parameters);
    }

    @Provides
    @Singleton
    public SystemInspector systemInspector(@Named("storageDirectory") File storageDir, SettingValueRepository valueRepository, ScriptExecutor executor){
        return new ScriptsInspector(storageDir, executor, valueRepository, parameters);
    }

    @Provides
    @Singleton
    public Clock clock(){
        return Clock.systemUTC();
    }

}


text:
The PyPore package is based off of a few core data analysis packages in order to provide a consistent and easy framework for handling nanopore data in the UCSC nanopore lab. The packages it requires are:

* numpy
* scipy
* matplotlib
* sklearn

Packages which are not required, but can be used, are:

* mySQLdb
* cython
* PyQt4

Let's get started!

# DataTypes

There are several core datatypes implemented in order to speed up analysis. These are currently File, Event, and Segment. Each of these is a way to store a full, or parts of, a .abf file and perform common tasks.

### Files

* **Attributes**: duration, mean, std, min, max, n *(# events)*, second, current, sample, events, event_parser, filename
* **Instance Methods**: parse( parser ), delete(), to\_meta(), to\_json( filename ), to\_dict(), to\_database( database, host, user, password ), plot( color_events )
* **Class Methods**: from\_json( filename ), from\_database( ... )

Nanopore data files consist primarily of current levels corresponding to ions passing freely through the nanopore ("open channel"), and a blockages as something passes through the pore, such as a DNA strand ("events"). Data from nanopore experiments are stored in Axon Binary Files (extension .abf), as a sequence 32 bit floats, and supporting information about the hardware. They can be opened and loaded with the following:

```
from PyPore.DataTypes import *
file = File( "My_File.abf" )
```

The File class contains many methods to simplify the analysis of these files. The simplest analysis to do is to pull the events, or blockages of current, from the file, while ignoring open channel. Let's say that we are looking for any blockage of current which causes the current to dip from an open channel of ~120 pA. To be conservative, we set the threshold the current has to dip before being significant to 110 pA. This can be done simply with the file's parse method, which requires a parser class which will perform the parsing. The simplest event detector is the *lambda_event_parser*, which has a keyword *threshold*, indicating the raw current that serves as the threshold.

```
from PyPore.DataTypes import *
file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=50 ) )
```

The events are now stored as Event objects in file.events. The only other important file methods involve loading and saving them to a cache, which we'll cover later. Files also have the properties mean, std, and n (number of events). If we wanted to look at what it thought were events, we could use the plot method. By default, this method will plot detected events in a different color.

```
from PyPore.DataTypes import *
file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=50 ) )
file.plot()
```

![](https://lh3.googleusercontent.com/-YGRe4s_XqNc/UzMuY3CeasI/AAAAAAAAABM/bbyXkXUFj1E/w1598-h332-no/file_plot.png)

Given that a file is huge, only every 100th point is used in the black regions, and every 5th point is used in events. This may lead to some problems, such as there are two regions which seem like they should be called events, but are colored black and not cyan. This is because in reality, there are spikes below 0 in each of these segments, and the parsing method filtered out any events which went below 0 pA at any point. However, the downsampling removed this spike (because it was less than 100 points long).

### Events

* **Attributes**: duration, start, end, mean, std, min, max, n, current, sample, segments, state\_parser, filtered, filter\_order, filter\_cutoff
* **Instance Methods**: filter( order, cutoff ), parse( parser ), delete(), apply\_hmm( hmm ), plot( [hmm, kwargs), to\_meta(), to\_dict(), to\_json()
* **Class Methods**: from\_json( filename ), from\_database( ... ), from\_segments( segments )

Events are segments of current which correspond to something passing through the nanopore. We hope that it is something which we are interested in, such as DNA or protein. An event is usually made up of a sequence of discrete segments of current, which should correspond to reading some region of whatever is passing through. In the best case, each discrete segment in an event corresponds to a single nucleotide of DNA, or a single amino acid of a protein passing through.

Events are often noisy, and transitions between them are quick, making filtering a good option for trying to see the underlying signal. Currently only [bessel filters](http://en.wikipedia.org/wiki/Bessel_filter) are supported for filtering tasks, as they've been shown to perform very well.

Let's continue with our example, and imagine that now we want to filter each event, and look at it! The filter method has two parameters, order and cutoff, defaulting to order=1 and cutoff=2000. (Note that we now import pyplot as well.)

```
from PyPore.DataTypes import *
from matplotlib import pyplot as plt

file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=50 ) )

for event in file.events:
    event.filter( order=1, cutoff=2000 )
    event.plot()
    plt.show()
```

![](https://lh3.googleusercontent.com/-VtVrNVUmiJ8/UzMwn559UqI/AAAAAAAAABk/tZqoOYw_PMk/w800-h547-no/event_plot.png)

The first event plotted in this loop is shown.

Currently, *lambda_event_parser* and *MemoryParse* are the most used File parsers. MemoryParse takes in two lists, one of starts of events, and one of ends of events, and will cut a file into it's respective events. This is useful if you've done an analysis before and remember where the split points are.

The plot command will draw the event on whatever canvas you have, allowing you to make subplots with the events or add them into GUIs (such as Abada!), with the downside being that you need to use plt.show() after calling the plot command. The plot command wraps the pyplot.plot command, allowing you pass in any argument that could be used by pyplot.plot, for example:

```
event.plot( alpha=0.5, marker='o' )
```

![](https://lh4.googleusercontent.com/-f3OE4YU4vv0/UzMxSzAi2eI/AAAAAAAAACI/m1R6XYzyZyE/w800-h547-no/event_plot_mod.png)

This plot doesn't look terrible good, and takes longer to plot, but it is possible to do!

Subplot handling is extremely easy. All of the plotting commands plot to whichever canvas is currently open, allowing for you to do something like this:

```
from PyPore.DataTypes import *
from matplotlib import pyplot as plt

file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=50 ) )

for event in file.events:
    plt.subplot(211)
    event.plot()
    plt.subplot(212)
    event.filter()
    event.plot()
    plt.show()
```

![](https://lh6.googleusercontent.com/-X3R3tlF1AYs/UzMyLzQI8hI/AAAAAAAAACc/bPLbVLY28xc/w800-h547-no/event_plot_comp.png)

This plot shows how easy it is to show a comparison between an event which is not filtered versus one which is filtered.

The next step is usually to try to segment this event into it's discrete states. There are several segmenters which have been written to do this, of which currently *StatSplit is the best, written by Dr. Kevin Karplus and based on a recursive maximum likelihood algorithm.  This algorithm was sped up by rewritting it in Cython, leading to *SpeedyStatSplit, which is a python wrapper for the cython code. Segmenting an event is the same process as detecting events in a file, by using the parse method on an event and passing in a parser.

Let's say that now we want to segment an event and view it. Using the same plot command for the event, we can specify to color by 'cycle', which colors the segments in a four-color cycle for easy viewing. SpeedyStatSplit takes in several parameters, of which *min_gain_per_sample is the most important, and 0.50 to 1.50 usually provide an adequate level to parse at, with higher numbers leading to less segments.

```
from PyPore.DataTypes import *
from matplotlib import pyplot as plt

file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=50 ) )

for event in file.events:
    event.filter( order=1, cutoff=2000 )
    event.parse( parser=SpeedyStatSplit( min_gain_per_sample=0.50 ) )
    event.plot( color='cycle' )
    plt.show()
```

![](https://lh3.googleusercontent.com/-DkJuj7bJLl4/UzMy3EvOP5I/AAAAAAAAACs/VMgr513sYq8/w800-h547-no/event_seg.png)

The color cycle goes blue-red-green-cyan.

The most reliable segmenter currently is *SpeedyStatSplit*. For more documentation on the parsers, see the parsers segment of this documentation. Both Files and Events inherit from the Segment class, described below. This means that any of the parsers will work on either files or events.

The last core functionality is the ability to apply an hidden markov model (HMM) to an event, and see which segments correspond to which hidden states. HMM functionality is made possible through the use of the yahmm class, which has a Model class and a viterbi method, which is called to find the best path through the HMM. A good example of one of these HMMs is tRNAbasic or tRNAbasic2, which were both made for this purpose. Lets say we want to compare the two HMMs to see which one we agree with more.

```
from PyPore.DataTypes import *
from PyPore.hmm import tRNAbasic
from matplotlib import pyplot as plt

file = File( "My_File.abf" )
file.parse( lambda_event_parser( threshold=50 ) )

for i, event in enumerate( file.events ):
	event.filter()
	event.parse( SpeedyStatSplit( min_gain_per_sample=.2 ) )
	plt.subplot( 411 )
	event.plot( color='cycle' )

	plt.subplot( 412 )
	event.plot( color='hmm', hmm=tRNAbasic() )

	plt.subplot( 413 )
	event.plot( color='hmm', hmm=tRNAbasic2() )

	plt.subplot( 414 )
	plt.imshow( [ np.arange(11) ], interpolation='nearest', cmap="Set1" )
	plt.grid( False )

	means = [ 33, 29.1, 24.01, 26.04, 24.4, 29.17, 27.1, 25.7, 22.77, 30.06, 24.9 ]
	for i, mean in enumerate( means ):
		plt.text( i-0.2, 0.1, str(mean), fontsize=16 )

	plt.show()
```

![](https://lh4.googleusercontent.com/-6fXyFjSiunw/UzM0J7WLl7I/AAAAAAAAADE/77-4iBsnWRY/w1598-h811-no/event_hmm_apply.png)

You'll notice that the title of an image and the xlabel of the image above it will always conflict. This is unfortunate, but an acceptable consequence in my opinion. If you're making more professional grade images, you may need to go in and manually fix this conflict. We see the original segmentation on the top, the first HMM applied next, and the second HMM on the bottom. The color coding of each HMM hidden state (sequentially) along with the mean ionic current of their emission distribution are shown at the very bottom. We see that the bottom HMM seems to progress more sequentially, progressing to the purple state instead of regressing back to the blue-green state in the middle of the trace. It also does not go backwards to the yellow state once it's in the gold state later on in the trace. It seems like a more robust HMM, and this way of comparing them is super easy to do.

Event objects also have the properties start, end, duration, mean, std, and n (number of segments after segmentation has been performed).

### Segments

* **Attributes**: duration, start, end, mean, std, min, max, current
* **Instance Methods**: to\_json( filename ), to\_dict(), to\_meta(), delete()
* **Class Methods**: from\_json( filename )

A segment stores the series of floats in a given range of ionic current. This abstract notion allows for both Event and File to inherit from it, as both a file and an event are a range of floats. The context in which you will most likely interact with a Segment is in representing a discrete step of the biopolymer through the pore, with points usually coming from the same distribution.

Segments are short sequences of current samples, usually which appear to be from the same distribution. They are the core place where data are stored, as usually an event is analyzed by the metadata stored in each state. Segments have the attributes current, which stores the raw current samples, in addition to mean, std, duration, start, end, min, and max.

### Metadata

If storing the raw sequence of current samples is too memory intensive, there are two ways to get rid of lists of floats representing the current, which take up the vast majority of the memory ( >~99% ).

1) Initialize a MetaSegment object, instead of a Segment one, and feed in whatever statistics you'd like to save. This will prevent the current from ever being saved to a second object. For this example, lets assume you have a list of starts and ends of segments in an event, such as loading them from a cache.

```
event = Event( current=[...], start=..., file=... )
event.segments =  [ MetaSegment( mean=np.mean( event.current[start:end] ),
                                 std=np.std( event.current[start:end] ),
                                 duration=(end-start)/100000 ) for start, end in zip( starts, ends ) ]
```

In this example, references to the current are not stored in both the event and the segment, which may save memory if you wish to not store the raw current after analyzing a file. The duration here is divided by 100,000 because abf files store 100,000 samples per second, and we wished to convert from the integer index of the start and end to the second index of the start and end.

2) If you have the memory to store the references, but don't want to accumulate them past a single event, you can parse a file normally, and produce normal segments, then call the function to_meta() to turn them into MetaSegments. This does not require any calculation on the user part, but does require the segment have contained all current samples at one point.

```
event = Event( current=[...], start=..., file=... )
event.parse( parser=SpeedyStatSplit() )
for segment in event.segments:
    segment.to_meta()
```

You may have noticed that every datatype implements a to\_meta() method, which removes simply retypes the object to "Meta...", and removes the current attribute, and all references to that list. Remember that in python, if any references exist to a list, the list still exists. This means that your file contains the list of ionic current, and all events or segments simply contain pointers to that list, so meta-izing a list or segment by itself probably won't help that much in terms of memory. However, you can meta-ize the File, which will meta-ize everything in the file tree. This means that calling to\_meta() on a file will cause to\_meta() to be called on each event, which will cause to\_meta() to be called on every segment, removing every reference to that list, and tagging that list for garbage collection.

# Parsers

Given that both Events and Files inherit from the Segment class, any parser can be used on both Events and Files. However, some were written for the express purpose of event detection or segmentation, and are better suited for that task.

### Event Detector Intended Parsers

These parsers were intended to be use for event detection. They include:

* *lambda_event_parser( threshold )* : This parser will define an event to be any consecutive points of ionic current between a drop below threshold to a jump above the threshold. This is a very simplistic parser, built on the idea that the difference between open channel current and the highest biopolymer related state in ~30-40% of open channel, meaning that setting this threshold anywhere in that range will quickly yield the events.

### Segmenter Intended Parsers

* *SpeedyStatSplit( min_gain_per_sample, min_width, max_width, window_width, use_log )* : This parser uses maximum likelihood in order to split segments. This is the current best segmenter, as it can handle segments which have different variances but the same mean, and segments with very similar means. It is the cython implementation of StatSplit, speeding up the implementation ~40x. The min gain per sample attribute is the most important one, with ~0.5 being a good default, and higher numbers producing less segments, smaller numbers producing more segments. The min width and max width parameters are in points, and their default values are usually good.

* *StatSplit( ... )* : The same as SpeedyStatSplit, except slower. Use if masochistic.

* *novakker_parser( low_thresh, high_thresh )* : This is an implementation of the derivative part of a  filter-derivative method to segmentation. It has two thresholds on the derivative, of which the high thresh must be reached before a segmentation is made. However, before the next segmentation is made, the derivative must go below the low threshold. This ensures that a region of rapid change does not get overly segmented.

* *snakebase_parser( threshold )* : This parser takes the attitude that transitions between segments occurs when the peak-to-peak amplitude between two consecutive waves is higher than threshold. This method seems to work decently when segments have significantly different means, especially when over-segmenting is not a problem.

### Misc.

* *MemoryParser( starts, ends )* : This parser is mostly used internally in order to load up saved analyses, however it is available for all to use. The starts of segments, and the ends, are provided in a list with the *i*-th element of starts and ends correspond to the *i*-th segment you wish to make. This can be used for event detection or segmentation.

# HMMs

### Making Hidden Markov Models

PyPore is set up to accept YAHMM hidden Markov models by default. The YAHMM package is a general HMM package, which is written in Cython for speed. The original yahmm package was written by Adam Novak, but has been converted to Cython and expanded upon by myself. Here is an example of making a model:

```
from yahmm import *

model = Model( "happy model" )
a = State( NormalDistribution( 3, 4 ), 'a' )
b = State( NormalDistribution( 10, 1 ), 'b' )

model.add_transition( model.start, a, 0.50 )
model.add_transition( model.start, b, 0.50 )
model.add_transition( a, b, 0.50 )
model.add_transition( b, a, 0.50 )
model.add_transition( a, model.end, 0.50 )
model.add_transition( b, model.end, 0.50 )
model.bake()
```

In order to use cython modules, you must import them properly using the pyximport package. The next step is to create a Model object, then various State objects, then connect the beginning of the model to the states, the states to each other, and the states to the end of the model in the appropriate manner! Then you can call forward, backward, and viterbi as needed on any sequence of observations. It is important to bake the model in the end, as that solidifies the internals of the HMM.

I usually create a function with the name of the HMM, and have the code to build that HMM inside the function, and return a baked model.

### Using HMMs

There are three ways to use HMMs on event objects.

1) The first is to simply use event.apply_hmm( hmm, algorithm ). Algorithm can be forward, backward, or viterbi, depending on what you want. Forward gives the log probability of the event given the model going forward, backward is the same but using the backwards algorithm, and viterbi returns a tuple of the log probability, and most likely path. This defaults to viterbi.

```
print event.apply_hmm( tRNAbasic(), algorithm='forward' )
print event.apply_hmm( tRNAbasic(), algorithm='backward' )
print event.apply_hmm( tRNAbasic() )
```

1) The second is in the parse class, to create HMM-assisted segmentation. This will concatenate states of the same hidden state which are next to each other, allowing you to add prior information to your segmentation.

```
event.parse( parser=SpeedyStatSplit( min_gain_per_sample=.2 ), hmm=tRNAbasic() )
```

2) Lastly, you can pass it in in the plot function. This does not change the underlying event at all, but will simply color it differently when it plots. An example is similar to what we did earlier when comparing different HMM models on an event. Here are two examples of HMM usage for plotting. cmap allows you to define the colormap you use on the serial ID of sequential HMM matching states, and defaults to Set1 due to its wide range of colors.

```
event.plot( color='hmm', hmm=tRNAbasic(), cmap='Reds' )
event.plot( color='hmm', hmm=tRNAbasic2(), cmap='Greens' )
```

# Saving Analyses

If you perform an analysis and wish to save the results, there are multiple ways for you to do such. These operation seems common, for applications such as testing a HMM. If you write a HMM and want to make modifications to it, it would be useful to not have to redo the segmentation, but instead simply load up the same segmentation from the last time you did it. Alternatively, you may have a large batch of files you wish to analyze, and want to grab the metadata for each file to easily read after you go eat lunch, so you don't need to deal with the whole files.

### MySQL Database:
The first is to store it to a MySQL database. The tables must be properly made for this-- see database.py if you want to see how to set up your own database to store PyPore results. If you are connected to the UCSC SoE secure network, there is a MySQL database, named chenoo, which will allow you to store an analysis. This is done on the file level, in order to preserve RDBMS format.

```
from PyPore.DataTypes import *

file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=110 ) )

for event in file.events:
    event.filter( order=1, cutoff=2000 )
    event.parse( parser=SpeedyStatSplit( min_gain_per_sample=0.50 ) )
    event.plot( color='cycle' )
    plt.show()
file.to_database( database="chenoo", host="...", password="...", user="..." )
```

Host, password, and user must be set for your specific database. These files can then be read back by the following code.

```
from PyPore.DataTypes import *

file = File.from_database( database="chenoo", host="...", password="...", user="...", AnalysisID, filename, eventDetector, eventDetectorParams, segmenter, segmenterParams, filterCutoff, filterOrder )
```

This will load the file back, with the previous segmentations. This will be anywhere from 10x to 1000x faster than performing the segmentation again. The time depends on how stable your connection with the database is, and how complex the analysis you did was.

Now, it seems like there are a lot of parameters after user! You need to fill in as many of these as you can, to help identify which analysis you meant. AnalysisID is a primary key, but is also assigned by the database automatically when you stored it, so it is possible you do not know it. If you connect to MySQL independently and look up that ID, you can use it solely to identify which file you meant. If you do not provide enough information to uniquely identify a file, you may get an incorrect analysis.

### JSON File
A more portable and simple way to store analyses is to save the file to a json. This can be done simply with the following code.

```
from PyPore.DataTypes import *

file = File( "My_File.abf" )
file.parse( parser=lambda_event_parser( threshold=110 ) )

for event in file.events:
    event.filter( order=1, cutoff=2000 )
    event.parse( parser=SpeedyStatSplit( min_gain_per_sample=0.50 ) )
    event.plot( color='cycle' )
    plt.show()
file.to_json( filename="My_File.json" )
```

The representation of your analysis will then be available as a human-readable json format. It may not be particularly fun to look at, but you will be able to read the metadata from the file. A snippet from an example file looks like the following:

```
{
     "name" : "File",
     "n" : 16,
     "event_parser" : {
         "threshold" : 50.0,
         "name" : "lambda_event_parser"
     },
     "duration" : 750.0,
     "filename" : "13823006-s06",
     "events" : [
         {
             "std" : 1.9335278997265508,
             "end" : 31.26803,
             "state_parser" : {
                 "min_gain_per_sample" : 0.5,
                 "min_width" : 1000,
                 "window_width" : 10000,
                 "max_width" : 1000000,
                 "name" : "SpeedyStatSplit"
             },
             "name" : "Event",
             "min" : 16.508111959669066,
             "max" : 48.73997069621818,
             "segments" : [
                 {
                     "std" : 2.8403093295527646,
                     "end" : 0.01,
                     "name" : "Segment",
                     "min" : 22.330505378907066,
                     "max" : 48.73997069621818,
                     "start" : 0.0,
                     "duration" : 0.01,
                     "mean" : 27.341223956001969
                 },
                 {
                     "std" : 0.5643329015609988,
                     "end" : 2.5060499999999997,
                     "name" : "Segment",
                     "min" : 17.67660726490438,
                     "max" : 26.554361458946911,
                     "start" : 0.01,
                     "duration" : 2.49605,
                     "mean" : 24.084380592526145
                ....
```
The file continues to list every event, and every segment in every event. The code to reconstruct an analysis from a json file is just as long as the code to reconstruct from the database.

```
from PyPore.DataTypes import *

file = File.from_json( "My_File.json" )
```

This is usually faster than loading from a database, solely due to not having to connect across a network and stream data, and instead reading locally.


text:
package org.apache.yoko.orb.OBPortableServer;

import java.util.logging.Level;
import java.util.logging.Logger;

final class POALocator {
    static final Logger logger = Logger.getLogger(POALocator.class.getName());

    java.util.Hashtable poas_ = new java.util.Hashtable(63);

    //
    // Locate a POA
    //
    synchronized org.omg.PortableServer.POA locate(
            org.apache.yoko.orb.OB.ObjectKeyData data)
            throws org.apache.yoko.orb.OB.LocationForward {
        logger.fine("Searching for POA " + data);
        //
        // If length of poa name sequence is zero we are looking
        // for a root POA and are doomed to fail.
        //
        if (data.poaId.length == 0) {
            return null;
        }

        org.omg.PortableServer.POA poa = (org.omg.PortableServer.POA) poas_.get(new POANameHasher(data.poaId));
        if (poa == null) {
            logger.fine("POA not found by direct lookup, searching the hierarchy");
            //
            // Arrange for POA activation. The algorithm for this is
            // to find the first POA in the `path' that exists. We
            // then call find_POA on each remaining POA in the path to
            // cause the activation.
            //
            String[] poaId = new String[data.poaId.length];
            System.arraycopy(data.poaId, 0, poaId, 0, data.poaId.length);
            java.util.Vector remaining = new java.util.Vector();
            do {
                remaining.addElement(poaId[poaId.length - 1]);
                String[] newID = new String[poaId.length - 1];
                System.arraycopy(poaId, 0, newID, 0, poaId.length - 1);
                poaId = newID;
                POANameHasher key = new POANameHasher(poaId);
                logger.fine("Searching POA hierarchy for " + key);
                poa = (org.omg.PortableServer.POA) poas_.get(key);
                if (poa != null) {
                    logger.fine("Located POA using " + key);
                    break;
                }
            } while (poaId.length > 0);

            //
            // Now find each POA in the path until we fail to find one of
            // the POA's or we're done.
            //
            for (int i = remaining.size(); i > 0 && poa != null; i--) {
                String key = (String) remaining.elementAt(i - 1);
                try {
                    logger.fine("Searching up hierarchy using key " + key);
                    poa = poa.find_POA(key, true);
                } catch (org.omg.PortableServer.POAPackage.AdapterNonExistent ex) {
                    logger.fine("Failure locating POA using key " + key);
                    poa = null;
                }
            }
        }
        return poa;
    }

    //
    // Add a POA
    //
    synchronized void add(org.omg.PortableServer.POA poa, String[] id) {
        POANameHasher idkey = new POANameHasher(id);
        logger.fine("Adding POA to locater using key " + idkey);
        org.apache.yoko.orb.OB.Assert._OB_assert(!poas_.containsKey(idkey));
        poas_.put(idkey, poa);
    }

    //
    // Remove a POA
    //
    synchronized void remove(String[] id) {
        POANameHasher idkey = new POANameHasher(id);
        logger.fine("Removing POA from locater using key " + idkey);
        org.apache.yoko.orb.OB.Assert._OB_assert(poas_.containsKey(idkey));
        poas_.remove(idkey);
    }
}


text:
package org.apache.tomcat.util.digester;

import java.util.ArrayList;
import java.util.EmptyStackException;

/**
 *
Imported copy of the ArrayStack class from
 * Commons Collections, which was the only direct dependency from Digester.

 *
 *
WARNNG - This class is public solely to allow it to be
 * used from subpackages of org.apache.commons.digester.
 * It should not be considered part of the public API of Commons Digester.
 * If you want to use such a class yourself, you should use the one from
 * Commons Collections directly.

 *
 *
An implementation of the {@link java.util.Stack} API that is based on an
 * ArrayList instead of a Vector, so it is not
 * synchronized to protect against multi-threaded access.  The implementation
 * is therefore operates faster in environments where you do not need to
 * worry about multiple thread contention.

 *
 *
Unlike Stack, ArrayStack accepts null entries.
 *

 *
 * @see java.util.Stack
 * @since Digester 1.6 (from Commons Collections 1.0)
 */
public class ArrayStack extends ArrayList {

    /** Ensure serialization compatibility */
    private static final long serialVersionUID = 2130079159931574599L;

    /**
     * Constructs a new empty ArrayStack. The initial size
     * is controlled by ArrayList and is currently 10.
     */
    public ArrayStack() {
        super();
    }

    /**
     * Constructs a new empty ArrayStack with an initial size.
     *
     * @param initialSize  the initial size to use
     * @throws IllegalArgumentException  if the specified initial size
     *  is negative
     */
    public ArrayStack(int initialSize) {
        super(initialSize);
    }

    /**
     * Return true if this stack is currently empty.
     *

     * This method exists for compatibility with java.util.Stack.
     * New users of this class should use isEmpty instead.
     *
     * @return true if the stack is currently empty
     */
    public boolean empty() {
        return isEmpty();
    }

    /**
     * Returns the top item off of this stack without removing it.
     *
     * @return the top item on the stack
     * @throws EmptyStackException  if the stack is empty
     */
    public Object peek() throws EmptyStackException {
        int n = size();
        if (n <= 0) {
            throw new EmptyStackException();
        } else {
            return get(n - 1);
        }
    }

    /**
     * Returns the n'th item down (zero-relative) from the top of this
     * stack without removing it.
     *
     * @param n  the number of items down to go
     * @return the n'th item on the stack, zero relative
     * @throws EmptyStackException  if there are not enough items on the
     *  stack to satisfy this request
     */
    public Object peek(int n) throws EmptyStackException {
        int m = (size() - n) - 1;
        if (m < 0) {
            throw new EmptyStackException();
        } else {
            return get(m);
        }
    }

    /**
     * Pops the top item off of this stack and return it.
     *
     * @return the top item on the stack
     * @throws EmptyStackException  if the stack is empty
     */
    public Object pop() throws EmptyStackException {
        int n = size();
        if (n <= 0) {
            throw new EmptyStackException();
        } else {
            return remove(n - 1);
        }
    }

    /**
     * Pushes a new item onto the top of this stack. The pushed item is also
     * returned. This is equivalent to calling add.
     *
     * @param item  the item to be added
     * @return the item just pushed
     */
    public Object push(Object item) {
        add(item);
        return item;
    }

    /**
     * Returns the one-based position of the distance from the top that the
     * specified object exists on this stack, where the top-most element is
     * considered to be at distance 1.  If the object is not
     * present on the stack, return -1 instead.  The
     * equals() method is used to compare to the items
     * in this stack.
     *
     * @param object  the object to be searched for
     * @return the 1-based depth into the stack of the object, or -1 if not found
     */
    public int search(Object object) {
        int i = size() - 1;        // Current index
        int n = 1;                 // Current distance
        while (i >= 0) {
            Object current = get(i);
            if ((object == null && current == null) ||
                (object != null && object.equals(current))) {
                return n;
            }
            i--;
            n++;
        }
        return -1;
    }

}


text: export { LicenseGlobal32 as default } from "../../";


text:
class WebServicesController < ApplicationController
  def show
    return render(:template => 'articles/missing') unless WebService.exists? params[:id]

    @article = WebService.find(params[:id])

    authorize! :read, @article

    #redirection of old permalinks
    if request.path != web_service_path(@article)
      logger.info "Old permalink: #{request.path}"
      return redirect_to @article, status: :moved_permanently
    end

    # basic statistics on how many times an article has been accessed
    @article.increment! :access_count
    @article.category.increment!(:access_count) if @article.category

    unless @article.published?
      flash.now[:info] = "This article has not been published."
    end

    @content_main =  @article.md_to_html(:content_main)
    @content_main_extra = @article.md_to_html(:content_main_extra)
    @content_need_to_know =  @article.md_to_html(:content_need_to_know)

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @article }
    end
  end
end


text:
package de.rnd7.imagegrid;

import java.util.List;
import java.util.Optional;

import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;

class ImageGridLayout {

	private final int itemWidth = 80;
	private final int itemHeight = 80;

	private final int spacer = 10;

	private final ImageGrid grid;

	ImageGridLayout(final ImageGrid grid) {
		this.grid = grid;
	}

	int getItemWidth() {
		return this.itemWidth;
	}

	int getItemHeight() {
		return this.itemHeight;
	}

	int getSpacer() {
		return this.spacer;
	}

	int getColumns() {
		final Rectangle clientArea = this.grid.getClientArea();
		return Math.max(1, clientArea.width / (this.itemWidth + this.spacer));
	}

	int getRows() {
		final int columns = this.getColumns();
		final int size = this.grid.getItems().size();

		int rows = size / columns;
		if (size % columns > 0) {
			rows++;
		}
		rows = Math.max(1, rows);
		return rows;
	}

	int getMargin() {
		return this.getSpacer() / 2;
	}

	int getTotalHeight() {
		return this.getRows() * (this.itemHeight + this.spacer);
	}

	Optional<ImageItem> elementAt(final int x, final int y) {
		final List<ImageItem> items = this.grid.getItems();

		final int margin = this.getMargin();
		return this.indexAt(x - margin, y - margin).filter(index -> this.boundsOf(index).contains(new Point(x, y)))
				.map(items::get);
	}

	Rectangle boundsOf(final int index) {
		final int columns = this.getColumns();

		final int row = index / columns;
		final int column = index % columns;

		final int margin = this.getMargin();

		final int x = column * (this.itemWidth + this.spacer) + margin;
		final int y = row * (this.itemHeight + this.spacer) + margin;

		return new Rectangle(x, y, this.itemWidth, this.itemHeight);
	}

	private Optional<Integer> indexAt(final int x, final int y) {
		final int columns = this.getColumns();

		final int column = x / (this.itemWidth + this.spacer);
		final int row = y / (this.itemHeight + this.spacer);

		final int index = row * columns + column;
		final List<ImageItem> items = this.grid.getItems();
		if (index < items.size()) {
			return Optional.of(index);
		} else {
			return Optional.empty();
		}
	}
}


text: SELECT func1_mod_setint_vol(func2_read_int_stb(5)) FROM foo order by 1;


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Doctrine\Dbal;

use Doctrine\DBAL\Connection;
use Rollerworks\Component\Search\Doctrine\Dbal\Query\QueryField;

class ConversionHints
{
    /**
     * @var QueryField
     */
    public $field;

    /**
     * @var Connection
     */
    public $connection;

    /**
     * @var int
     */
    public $conversionStrategy = 0;

    /**
     * @var string
     */
    public $column;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using ArcGIS.Desktop.Mapping;

namespace ImportPlatToFabric
{
	internal class FixupImportData : Button
	{
		private const string LyrNameImport = "ImportPlats";

		protected override async void OnClick()
		{
			var map = MapView.Active?.Map;
			if (map == null) return;
			try
			{
				var lyr = map.GetLayersAsFlattenedList().FirstOrDefault((fl) => fl.Name == LyrNameImport) as FeatureLayer;
        var msg = await QueuedTask.Run(() =>
        {
          var attribs = new Dictionary<long, Dictionary<string, object>>();
          using (var cursor = lyr.Search())
            while (cursor.MoveNext())
            {
              using (var feat = cursor.Current as Feature)
              {
                var path = feat.GetShape() as Polyline;
                var ls = LineBuilderEx.CreateLineSegment(path.Points[0], path.Points[path.PointCount-1]);
                attribs.Add(feat.GetObjectID(), new Dictionary<string, object>() { { "Direction", ls.Angle } });
              }
            }

          // create an edit operation
          var editOperation = new EditOperation() { Name = $@"Update {LyrNameImport}" };
          foreach (var key in attribs.Keys)
					{
            editOperation.Modify(lyr, key, attribs[key]);
          }
          if (!editOperation.Execute()) return editOperation.ErrorMessage;
          return "update complete";
        });
        MessageBox.Show(msg);
      }
			catch (Exception ex)
			{
        MessageBox.Show($@"Error: {ex}");
			}
		}
	}
}


text:
/*
 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package javax.xml.ws;

import javax.xml.ws.soap.AddressingFeature;

/**
 * This feature clarifies the use of the wsdl:binding
 * in a JAX-WS runtime.
 *
 * This feature can be used during the creation of SEI proxy, and
 * {@link Dispatch} instances on the client side and {@link Endpoint}
 * instances on the server side. This feature cannot be used for {@link Service}
 * instance creation on the client side.
 *

 * This feature is only useful with web services that have an
 * associated WSDL. Enabling this feature requires that a JAX-WS
 * implementation inspect the wsdl:binding for an
 * endpoint at runtime to make sure that all wsdl:extensions
 * that have the required attribute set to true
 * are understood and are being used.
 *

 * The following describes the affects of this feature with respect
 * to be enabled or disabled:
 *

 *
 ENABLED: In this Mode, a JAX-WS runtime MUST assure that all
 *  required wsdl:binding extensions(including policies) are
 *  either understood and used by the runtime, or explicitly disabled by the
 *  web service application. A web service can disable a particular
 *  extension if there is a corresponding {@link WebServiceFeature} or annotation.
 *  Similarly, a web service client can disable
 *  particular extension using the corresponding WebServiceFeature while
 *  creating a proxy or Dispatch instance.
 *  The runtime MUST also make sure that binding of
 *  SEI parameters/return values respect the wsdl:binding.
 *  With this feature enabled, if a required (wsdl:required="true")
 *  wsdl:binding extension is in the WSDL and it is not
 *  supported by a JAX-WS runtime and it has not
 *  been explicitly turned off by the web service developer, then
 *  that JAX-WS runtime MUST behave appropriately based on whether it is
 *  on the client or server:
 *

 *
Client: runtime MUST throw a
 *  {@link WebServiceException} no sooner than when one of the methods
 *  above is invoked but no later than the first invocation of an endpoint
 *  operation.
 *
Server: throw a {@link WebServiceException} and the endpoint MUST fail to deploy
 *

 *
 *
 DISABLED: In this Mode, an implementation may choose whether
 *  to inspect the wsdl:binding or not and to what degree
 *  the wsdl:binding will be inspected.  For example,
 *  one implementation may choose to behave as if this feature is enabled,
 *  another implementation may only choose to verify the SEI's
 *  parameter/return type bindings.
 *

 *
 * @see AddressingFeature
 *
 * @since JAX-WS 2.1
 */
public final class RespectBindingFeature extends WebServiceFeature {
    /**
     *
     * Constant value identifying the RespectBindingFeature
     */
    public static final String ID = "javax.xml.ws.RespectBindingFeature";

    /**
     * Creates an RespectBindingFeature.
     * The instance created will be enabled.
     */
    public RespectBindingFeature() {
        this.enabled = true;
    }

    /**
     * Creates an RespectBindingFeature
     *
     * @param enabled specifies whether this feature should
     * be enabled or not.
     */
    public RespectBindingFeature(boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * {@inheritDoc}
     */
    public String getID() {
        return ID;
    }
}


text:
<!DOCTYPE html>

    <title>PureStatic blog design Page Improve - TimeMachine</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="canonical" href="/blog/pages/2016/09/07/my-super-post-global-design-page-improve/">

        <meta name="author" content="Alexis Metaireau" />
        <meta name="keywords" content="pelican,publishing,Design" />
        <meta name="description" content="Short summary of what need to do in page design and font size,scale.And find out some problems." />

        <meta property="og:site_name" content="TimeMachine" />
        <meta property="og:type" content="article"/>
        <meta property="og:title" content="PureStatic blog design Page Improve"/>
        <meta property="og:url" content="/blog/pages/2016/09/07/my-super-post-global-design-page-improve/"/>
        <meta property="og:description" content="Short summary of what need to do in page design and font size,scale.And find out some problems."/>
        <meta property="article:published_time" content="2016-09-07" />
            <meta property="article:section" content="Init" />
            <meta property="article:tag" content="pelican" />
            <meta property="article:tag" content="publishing" />
            <meta property="article:tag" content="Design" />
            <meta property="article:author" content="Alexis Metaireau" />

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

    <link href="/theme/css/pygments/native.css" rel="stylesheet">
    <link rel="stylesheet" href="/theme/css/style.css" type="text/css"/>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                Toggle navigation

            </button>

TimeMachine

                            Init

                            Language

                        PureStatic blog design Page Improve

    Date

        <time datetime="2016-09-07T03:27:51+08:00"> 周三 07 九月 2016</time>

Tags
	pelican
        /
	publishing
        /
	Design

Font Size

this piece theme has a problem whois font size is too small.Hard to read.

Font Famliy

chinese font should use other font,eg.msyh

Comments

        Please enable JavaScript to view the comments powered by
            Disqus.
        comments powered by Disqus

Social

 You can add links in your config file

 github

Links

                Pelican

                Python.org

                Jinja2

                You can modify those links in your config file

© 2016 5pipi
            · Powered by pelican-bootstrap3,
            Pelican,
            Bootstrap

 Back to top


text:
This package was temporarily forked from <https://github.com/ros-drivers/joystick_drivers> to include fixes in our distribution.  See <https://github.com/ros-drivers/joystick_drivers/pull/101>

# Wiimote Nodes

See http://wiki.ros.org/wiimote for details.

## wiimote_node.py

Original Python version of the wiimote node.

## wiimote_node

The C++ implementation was designed with focus on reduced resource consumption.

### Parameters

* `bluetooth_addr` [str] - Bluetooth address for pairing. Default: `00:00:00:00:00:00` (first device)
* `pair_timeout` [int] - Pair timeout in seconds. `-1` means never timeout. Default: `5`

### Differences from Python Implementation
* Both "/wiimote/nunchuk" and "/wiimote/classic" topics are only published
if the Nunchuk or Classic Controller are connected to the wiimote respectively.
* Wiimote data is only polled from the controller if the data is required
to publish for a topic which has at least one subscriber.
* During Calibration the joysticks (Nunchuk & Classic Controller) are polled
to find the current position which is assumed to be the center. Not all joysticks
rest at the theoretical center position.
* Joysticks (Nunchuk & Classic Controller) minimum and maximum values start at
80% of the theoretical minimum/maximum values and are dynamically updated as
the joystick is used. The full range of values may not be reached on all joysticks
due to physical limitations. Without this adjust, the full range from -1.0 to 1.0
would not be reached on many joysticks.
* Joysticks (Nunchuk & Classic Controller) center deadzone is scaled based on
the granularity of the joystick; python code assumed the same for all.
* Connecting an accessory (Nunchuk, Classic Controller, or MotionPlus) will
automatically start a new calibration sequence.