text:
using namespace v8::internal;

static Isolate* GetIsolateFrom(LocalContext* context) {
  return reinterpret_cast<Isolate*>((*context)->GetIsolate());
}

static Handle<JSWeakMap> AllocateJSWeakMap(Isolate* isolate) {
  Factory* factory = isolate->factory();
  Heap* heap = isolate->heap();
  Handle<Map> map = factory->NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
  Handle<JSObject> weakmap_obj = factory->NewJSObjectFromMap(map);
  Handle<JSWeakMap> weakmap(JSWeakMap::cast(*weakmap_obj));
  // Do not use handles for the hash table, it would make entries strong.
  Object* table_obj = ObjectHashTable::Allocate(heap, 1)->ToObjectChecked();
  ObjectHashTable* table = ObjectHashTable::cast(table_obj);
  weakmap->set_table(table);
  weakmap->set_next(Smi::FromInt(0));
  return weakmap;
}

static void PutIntoWeakMap(Handle<JSWeakMap> weakmap,
                           Handle<JSObject> key,
                           Handle<Object> value) {
  Handle<ObjectHashTable> table = ObjectHashTable::Put(
      Handle<ObjectHashTable>(ObjectHashTable::cast(weakmap->table())),
      Handle<JSObject>(JSObject::cast(*key)),
      value);
  weakmap->set_table(*table);
}

static int NumberOfWeakCalls = 0;
static void WeakPointerCallback(v8::Isolate* isolate,
                                v8::Persistent<v8::Value>* handle,
                                void* id) {
  ASSERT(id == reinterpret_cast<void*>(1234));
  NumberOfWeakCalls++;
  handle->Reset();
}

TEST(Weakness) {
  FLAG_incremental_marking = false;
  LocalContext context;
  Isolate* isolate = GetIsolateFrom(&context);
  Factory* factory = isolate->factory();
  Heap* heap = isolate->heap();
  HandleScope scope(isolate);
  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);
  GlobalHandles* global_handles = isolate->global_handles();

  // Keep global reference to the key.
  Handle<Object> key;
  {
    HandleScope scope(isolate);
    Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
    Handle<JSObject> object = factory->NewJSObjectFromMap(map);
    key = global_handles->Create(*object);
  }
  CHECK(!global_handles->IsWeak(key.location()));

  // Put entry into weak map.
  {
    HandleScope scope(isolate);
    PutIntoWeakMap(weakmap,
                   Handle<JSObject>(JSObject::cast(*key)),
                   Handle<Smi>(Smi::FromInt(23), isolate));
  }
  CHECK_EQ(1, ObjectHashTable::cast(weakmap->table())->NumberOfElements());

  // Force a full GC.
  heap->CollectAllGarbage(false);
  CHECK_EQ(0, NumberOfWeakCalls);
  CHECK_EQ(1, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
  CHECK_EQ(
      0, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());

  // Make the global reference to the key weak.
  {
    HandleScope scope(isolate);
    global_handles->MakeWeak(key.location(),
                             reinterpret_cast<void*>(1234),
                             &WeakPointerCallback);
  }
  CHECK(global_handles->IsWeak(key.location()));

  // Force a full GC.
  // Perform two consecutive GCs because the first one will only clear
  // weak references whereas the second one will also clear weak maps.
  heap->CollectAllGarbage(false);
  CHECK_EQ(1, NumberOfWeakCalls);
  CHECK_EQ(1, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
  CHECK_EQ(
      0, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
  heap->CollectAllGarbage(false);
  CHECK_EQ(1, NumberOfWeakCalls);
  CHECK_EQ(0, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
  CHECK_EQ(
      1, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
}

TEST(Shrinking) {
  LocalContext context;
  Isolate* isolate = GetIsolateFrom(&context);
  Factory* factory = isolate->factory();
  Heap* heap = isolate->heap();
  HandleScope scope(isolate);
  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);

  // Check initial capacity.
  CHECK_EQ(32, ObjectHashTable::cast(weakmap->table())->Capacity());

  // Fill up weak map to trigger capacity change.
  {
    HandleScope scope(isolate);
    Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
    for (int i = 0; i < 32; i++) {
      Handle<JSObject> object = factory->NewJSObjectFromMap(map);
      PutIntoWeakMap(weakmap, object, Handle<Smi>(Smi::FromInt(i), isolate));
    }
  }

  // Check increased capacity.
  CHECK_EQ(128, ObjectHashTable::cast(weakmap->table())->Capacity());

  // Force a full GC.
  CHECK_EQ(32, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
  CHECK_EQ(
      0, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
  heap->CollectAllGarbage(false);
  CHECK_EQ(0, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
  CHECK_EQ(
      32, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());

  // Check shrunk capacity.
  CHECK_EQ(32, ObjectHashTable::cast(weakmap->table())->Capacity());
}

// Test that weak map values on an evacuation candidate which are not reachable
// by other paths are correctly recorded in the slots buffer.
TEST(Regress2060a) {
  FLAG_always_compact = true;
  LocalContext context;
  Isolate* isolate = GetIsolateFrom(&context);
  Factory* factory = isolate->factory();
  Heap* heap = isolate->heap();
  HandleScope scope(isolate);
  Handle<JSFunction> function =
      factory->NewFunction(factory->function_string(), factory->null_value());
  Handle<JSObject> key = factory->NewJSObject(function);
  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);

  // Start second old-space page so that values land on evacuation candidate.
  Page* first_page = heap->old_pointer_space()->anchor()->next_page();
  factory->NewFixedArray(900 * KB / kPointerSize, TENURED);

  // Fill up weak map with values on an evacuation candidate.
  {
    HandleScope scope(isolate);
    for (int i = 0; i < 32; i++) {
      Handle<JSObject> object = factory->NewJSObject(function, TENURED);
      CHECK(!heap->InNewSpace(object->address()));
      CHECK(!first_page->Contains(object->address()));
      PutIntoWeakMap(weakmap, key, object);
    }
  }

  // Force compacting garbage collection.
  CHECK(FLAG_always_compact);
  heap->CollectAllGarbage(Heap::kNoGCFlags);
}

// Test that weak map keys on an evacuation candidate which are reachable by
// other strong paths are correctly recorded in the slots buffer.
TEST(Regress2060b) {
  FLAG_always_compact = true;
#ifdef VERIFY_HEAP
  FLAG_verify_heap = true;
#endif

  LocalContext context;
  Isolate* isolate = GetIsolateFrom(&context);
  Factory* factory = isolate->factory();
  Heap* heap = isolate->heap();
  HandleScope scope(isolate);
  Handle<JSFunction> function =
      factory->NewFunction(factory->function_string(), factory->null_value());

  // Start second old-space page so that keys land on evacuation candidate.
  Page* first_page = heap->old_pointer_space()->anchor()->next_page();
  factory->NewFixedArray(900 * KB / kPointerSize, TENURED);

  // Fill up weak map with keys on an evacuation candidate.
  Handle<JSObject> keys[32];
  for (int i = 0; i < 32; i++) {
    keys[i] = factory->NewJSObject(function, TENURED);
    CHECK(!heap->InNewSpace(keys[i]->address()));
    CHECK(!first_page->Contains(keys[i]->address()));
  }
  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);
  for (int i = 0; i < 32; i++) {
    PutIntoWeakMap(weakmap,
                   keys[i],
                   Handle<Smi>(Smi::FromInt(i), isolate));
  }

  // Force compacting garbage collection. The subsequent collections are used
  // to verify that key references were actually updated.
  CHECK(FLAG_always_compact);
  heap->CollectAllGarbage(Heap::kNoGCFlags);
  heap->CollectAllGarbage(Heap::kNoGCFlags);
  heap->CollectAllGarbage(Heap::kNoGCFlags);
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = getDaysInYear;

var _index = require('../toDate/index.js');

var _index2 = _interopRequireDefault(_index);

var _index3 = require('../isLeapYear/index.js');

var _index4 = _interopRequireDefault(_index3);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @name getDaysInYear
 * @category Year Helpers
 * @summary Get the number of days in a year of the given date.
 *
 * @description
 * Get the number of days in a year of the given date.
 *
 * @param {Date|String|Number} date - the given date
 * @param {Options} [options] - the object with options. See [Options]{@link https://date-fns.org/docs/Options}
 * @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
 * @returns {Number} the number of days in a year
 * @throws {TypeError} 1 argument required
 * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
 *
 * @example
 * // How many days are in 2012?
 * var result = getDaysInYear(new Date(2012, 0, 1))
 * //=> 366
 */
function getDaysInYear(dirtyDate, dirtyOptions) {
  if (arguments.length < 1) {
    throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
  }

  var date = (0, _index2.default)(dirtyDate, dirtyOptions);

  if (isNaN(date)) {
    return NaN;
  }

  return (0, _index4.default)(date, dirtyOptions) ? 366 : 365;
}
module.exports = exports['default'];

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Flymake for Perl"
category: posts
---
Flymake应该成为emacs或vim的标配,该工具可以很方便的找出代码中的语法错误,提高开发效率. However, Emacs24的package-list里貌似并没有flymake for perl, so 需要我们自己做一些简单的设置.

首先需要去下载个set-perl5lib.el, 地址[点我][1],将它放在你的emacs的loadpath里. 然后将下列代码加到emacs的配置文件.

{% highlight lisp %}
;; flymake (Emacs22から標準添付されている)
(require 'flymake)

;; set-perl5lib
;; 開いたスクリプトのパスに応じて、@INCにlibを追加してくれる
;; 以下からダウンロードする必要あり
;; http://svn.coderepos.org/share/lang/elisp/set-perl5lib/set-perl5lib.el
(require 'set-perl5lib)

;; エラー、ウォーニング時のフェイス
(set-face-background 'flymake-errline "red4")
(set-face-foreground 'flymake-errline "black")
(set-face-background 'flymake-warnline "yellow")
(set-face-foreground 'flymake-warnline "black")

;; エラーをミニバッファに表示
;; http://d.hatena.ne.jp/xcezx/20080314/1205475020
(defun flymake-display-err-minibuf ()
  "Displays the error/warning for the current line in the minibuffer"
  (interactive)
  (let* ((line-no             (flymake-current-line-no))
         (line-err-info-list  (nth 0 (flymake-find-err-info flymake-err-info line-no)))
         (count               (length line-err-info-list)))
    (while (> count 0)
      (when line-err-info-list
        (let* ((file       (flymake-ler-file (nth (1- count) line-err-info-list)))
               (full-file  (flymake-ler-full-file (nth (1- count) line-err-info-list)))
               (text (flymake-ler-text (nth (1- count) line-err-info-list)))
               (line       (flymake-ler-line (nth (1- count) line-err-info-list))))
          (message "[%s] %s" line text)))
      (setq count (1- count)))))

;; Perl用設定
;; http://unknownplace.org/memo/2007/12/21#e001
(defvar flymake-perl-err-line-patterns
  '(("\\(.*\\) at \\([^ \n]+\\) line \\([0-9]+\\)[,.\n]" 2 3 nil 1)))

(defconst flymake-allowed-perl-file-name-masks
  '(("\\.pl$" flymake-perl-init)
    ("\\.pm$" flymake-perl-init)
    ("\\.t$" flymake-perl-init)))

(defun flymake-perl-init ()
  (let* ((temp-file (flymake-init-create-temp-buffer-copy
                     'flymake-create-temp-inplace))
         (local-file (file-relative-name
                      temp-file
                      (file-name-directory buffer-file-name))))
    (list "perl" (list "-wc" local-file))))

(defun flymake-perl-load ()
  (interactive)
  (defadvice flymake-post-syntax-check (before flymake-force-check-was-interrupted)
    (setq flymake-check-was-interrupted t))
  (ad-activate 'flymake-post-syntax-check)
  (setq flymake-allowed-file-name-masks (append flymake-allowed-file-name-masks flymake-allowed-perl-file-name-masks))
  (setq flymake-err-line-patterns flymake-perl-err-line-patterns)
  (set-perl5lib)
  (flymake-mode t))

(add-hook 'cperl-mode-hook 'flymake-perl-load)
{% endhighlight %}

以上,大功告成.

  [1]: http://svn.coderepos.org/share/lang/elisp/set-perl5lib/set-perl5lib.el


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

    angular.module('myApp.customers', ['ngRoute'])
        .controller('CustomersCtrl', ['$location', 'Customer', function ($location, Customer) {
            var customers = this;
            customers.customerList = Customer.query();
            customers.editCustomer = function (id) {
                $location.url('/customers/' + id);
            }
        }]);
})();


text:
namespace i2p
{
namespace client
{
	MatchedTunnelDestination::MatchedTunnelDestination(const i2p::data::PrivateKeys & keys, const std::string & remoteName, const std::map<std::string, std::string> * params)
		: ClientDestination(keys, false, params),
			m_RemoteName(remoteName) {}

	void MatchedTunnelDestination::ResolveCurrentLeaseSet()
	{
		if(i2p::client::context.GetAddressBook().GetIdentHash(m_RemoteName, m_RemoteIdent))
		{
			auto ls = FindLeaseSet(m_RemoteIdent);
			if(ls)
			{
				HandleFoundCurrentLeaseSet(ls);
			}
			else
				RequestDestination(m_RemoteIdent, std::bind(&MatchedTunnelDestination::HandleFoundCurrentLeaseSet, this, std::placeholders::_1));
		}
		else
			LogPrint(eLogWarning, "Destination: failed to resolve ", m_RemoteName);
	}

	void MatchedTunnelDestination::HandleFoundCurrentLeaseSet(std::shared_ptr<const i2p::data::LeaseSet> ls)
	{
		if(ls)
		{
			LogPrint(eLogDebug, "Destination: resolved remote lease set for ", m_RemoteName);
			m_RemoteLeaseSet = ls;
		}
		else
		{
			m_ResolveTimer->expires_from_now(boost::posix_time::seconds(1));
			m_ResolveTimer->async_wait([&](const boost::system::error_code & ec) {
					if(!ec)	ResolveCurrentLeaseSet();
			});
		}
	}

	bool MatchedTunnelDestination::Start()
	{
		if(ClientDestination::Start())
		{
			m_ResolveTimer = std::make_shared<boost::asio::deadline_timer>(GetService());
			GetTunnelPool()->SetCustomPeerSelector(this);
			ResolveCurrentLeaseSet();
			return true;
		}
		else
			return false;
	}

	bool MatchedTunnelDestination::Stop()
	{
		if(ClientDestination::Stop())
		{
			if(m_ResolveTimer)
				m_ResolveTimer->cancel();
			return true;
		}
		else
			return false;
	}

	bool MatchedTunnelDestination::SelectPeers(i2p::tunnel::Path & path, int hops, bool inbound)
	{
		auto pool = GetTunnelPool();
		if(!i2p::tunnel::StandardSelectPeers(path, hops, inbound, std::bind(&i2p::tunnel::TunnelPool::SelectNextHop, pool, std::placeholders::_1)))
			return false;
		// more here for outbound tunnels
		if(!inbound && m_RemoteLeaseSet)
		{
			if(m_RemoteLeaseSet->IsExpired())
			{
				ResolveCurrentLeaseSet();
			}
			if(m_RemoteLeaseSet && !m_RemoteLeaseSet->IsExpired())
			{
				// remote lease set is good
				auto leases = m_RemoteLeaseSet->GetNonExpiredLeases();
				// pick lease
				std::shared_ptr<i2p::data::RouterInfo> obep;
				while(!obep && leases.size() > 0) {
					auto idx = rand() % leases.size();
					auto lease = leases[idx];
					obep = i2p::data::netdb.FindRouter(lease->tunnelGateway);
					leases.erase(leases.begin()+idx);
				}
				if(obep) {
					path.push_back(obep->GetRouterIdentity());
					LogPrint(eLogDebug, "Destination: found OBEP matching IBGW");
				} else
					LogPrint(eLogWarning, "Destination: could not find proper IBGW for matched outbound tunnel");
			}
		}
		return true;
	}

	bool MatchedTunnelDestination::OnBuildResult(const i2p::tunnel::Path & path, bool inbound, i2p::tunnel::TunnelBuildResult result)
	{
		return true;
	}
}
}


text:
require_relative 'spec_helper'

module Aws::AppRunner
  describe EndpointProvider do
    subject { Aws::AppRunner::EndpointProvider.new }

    context 'For region us-west-2 with FIPS enabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.us-west-2.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>true, :region=>"us-west-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-west-2 with FIPS enabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.us-west-2.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>false, :region=>"us-west-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-west-2 with FIPS disabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.us-west-2.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>true, :region=>"us-west-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-west-2 with FIPS disabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.us-west-2.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>false, :region=>"us-west-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region eu-west-1 with FIPS enabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.eu-west-1.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>true, :region=>"eu-west-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region eu-west-1 with FIPS enabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.eu-west-1.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>false, :region=>"eu-west-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region eu-west-1 with FIPS disabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.eu-west-1.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>true, :region=>"eu-west-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region eu-west-1 with FIPS disabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.eu-west-1.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>false, :region=>"eu-west-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region ap-northeast-1 with FIPS enabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.ap-northeast-1.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>true, :region=>"ap-northeast-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region ap-northeast-1 with FIPS enabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.ap-northeast-1.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>false, :region=>"ap-northeast-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region ap-northeast-1 with FIPS disabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.ap-northeast-1.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>true, :region=>"ap-northeast-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region ap-northeast-1 with FIPS disabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.ap-northeast-1.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>false, :region=>"ap-northeast-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-1 with FIPS enabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.us-east-1.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>true, :region=>"us-east-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-1 with FIPS enabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.us-east-1.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>false, :region=>"us-east-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-1 with FIPS disabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.us-east-1.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>true, :region=>"us-east-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-1 with FIPS disabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.us-east-1.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>false, :region=>"us-east-1"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-2 with FIPS enabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.us-east-2.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>true, :region=>"us-east-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-2 with FIPS enabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner-fips.us-east-2.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>false, :region=>"us-east-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-2 with FIPS disabled and DualStack enabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.us-east-2.api.aws"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>true, :region=>"us-east-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For region us-east-2 with FIPS disabled and DualStack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://apprunner.us-east-2.amazonaws.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>false, :region=>"us-east-2"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For custom endpoint with fips disabled and dualstack disabled' do
      let(:expected) do
        {"endpoint"=>{"url"=>"https://example.com"}}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>false, :region=>"us-east-1", :endpoint=>"https://example.com"})
        endpoint = subject.resolve_endpoint(params)
        expect(endpoint.url).to eq(expected['endpoint']['url'])
        expect(endpoint.headers).to eq(expected['endpoint']['headers'] || {})
        expect(endpoint.properties).to eq(expected['endpoint']['properties'] || {})
      end
    end

    context 'For custom endpoint with fips enabled and dualstack disabled' do
      let(:expected) do
        {"error"=>"Invalid Configuration: FIPS and custom endpoint are not supported"}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>true, :use_dual_stack=>false, :region=>"us-east-1", :endpoint=>"https://example.com"})
        expect do
          subject.resolve_endpoint(params)
        end.to raise_error(ArgumentError, expected['error'])
      end
    end

    context 'For custom endpoint with fips disabled and dualstack enabled' do
      let(:expected) do
        {"error"=>"Invalid Configuration: Dualstack and custom endpoint are not supported"}
      end

      it 'produces the expected output from the EndpointProvider' do
        params = EndpointParameters.new(**{:use_fips=>false, :use_dual_stack=>true, :region=>"us-east-1", :endpoint=>"https://example.com"})
        expect do
          subject.resolve_endpoint(params)
        end.to raise_error(ArgumentError, expected['error'])
      end
    end

  end
end


text:
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Spell_LightenItem extends Spell
{

	@Override
	public String ID()
	{
		return "Spell_LightenItem";
	}

	private final static String localizedName = CMLib.lang().L("Lighten Item");

	@Override
	public String name()
	{
		return localizedName;
	}

	@Override
	protected int canAffectCode()
	{
		return CAN_ITEMS;
	}

	@Override
	protected int canTargetCode()
	{
		return CAN_ITEMS;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_SPELL|Ability.DOMAIN_ENCHANTMENT;
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_INDIFFERENT;
	}

	@Override
	public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
	{
		super.affectPhyStats(affected,affectableStats);
		affectableStats.setWeight(0);
	}

	@Override
	public void unInvoke()
	{
		if((canBeUninvoked())
		&&((affected instanceof Item)))
		{
			final Item item=(Item)affected;
			if((item.owner()!=null)
			&&(item.owner() instanceof MOB)
			&&(((MOB)item.owner()).isMine(item)))
			{
				final MOB mob=(MOB)item.owner();
				mob.tell(L("@x1 grows heavy again.",item.name()));
				if((mob.phyStats().weight()+item.basePhyStats().weight())>mob.maxCarry())
				{
					if(!item.amWearingAt(Wearable.IN_INVENTORY))
						CMLib.commands().postRemove(mob,item,false);
					if(item.amWearingAt(Wearable.IN_INVENTORY))
						CMLib.commands().postDrop(mob,item,false,false,false);
				}
			}
		}
		super.unInvoke();
	}

	@Override
	public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
	{
		final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
		if(target==null)
		{
			final String str=CMParms.combine(commands,0).toUpperCase();
			if(str.equals("MONEY")||str.equals("GOLD")||str.equals("COINS"))
				mob.tell(L("You can't cast this spell on your own coins."));
			return false;
		}

		if(target.fetchEffect(this.ID())!=null)
		{
			mob.tell(L("@x1 is already light!",target.name(mob)));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>, incanting.^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> grow(s) much lighter."));
				beneficialAffect(mob,target,asLevel,100);
				target.recoverPhyStats();
				mob.recoverPhyStats();
				mob.location().recoverRoomStats();
			}
		}
		else
			beneficialVisualFizzle(mob,target,L("<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>, incanting, but nothing happens."));

		// return whether it worked
		return success;
	}
}


text:
mass
================
Multimedia as a Service!

## Directory Tree
* arch/

  > system implementation

* archive/

  > summaries on some topics

* demo/

  > demo code and docs

* doc/

  > design doc

* industry/

  > mass-related industry news, frontiers

* resources/

  > resource lists collected from internet, techical details

## Home
----------
[SJTU Medialab](http://medialab.sjtu.edu.cn/)


text:
<?php
app\assets\EchartsAsset::register($this);
?>

数据统计

        <?=\app\modules\analysis\widgets\Analysis::widget(['name'=>'guideYearPercent'])?>
        <?=\app\modules\analysis\widgets\Analysis::widget(['name'=>'guideYearCompare'])?>
        <?=\app\modules\analysis\widgets\Analysis::widget(['name'=>'guideSelfMonth'])?>
        <?=\app\modules\analysis\widgets\Analysis::widget(['name'=>'guideMonthPercent'])?>
        <?=\app\modules\analysis\widgets\Analysis::widget(['name'=>'guideMonthCompare'])?>


text:
module VagrantPlugins
  module CaCertificates
    module Cap
      module Windows
        module CertificateFileBundle
          def self.certificate_file_bundle(m)
            'C:/ssl/cacert.pem'
          end
        end
      end
    end
  end
end


text:
import util from 'util';

/**
 * Factory which produces a multi-keyed container based on the provided set of
 * constructors
 * @param {mixed} containers
 * @returns {Container}
 */
function make(...containers) {
  const TopContainer = containers.shift();

  const data = new WeakMap();
  const sizes = new WeakMap();

  const ChildContainer = containers.length > 1 ? make(...containers) : containers[0];

  const name = `(${[TopContainer.name].concat(containers.map((container) => container.name)).join(`, `)})`;

  /**
   * Container that wraps an arbitrary set of tupples to their values
   */
  class Container {
    /**
     * @constructs Container
     */
    constructor(...args) {
      data.set(this, new TopContainer(...args));
      sizes.set(this, 0);
    }

    /**
     * getter for .size
     * @returns {number}
     */
    get size() {
      return sizes.get(this);
    }

    /**
     * Identical to Container#set() but leads slightly more intuitive code when
     * the container is based on a Set rather than a Map.
     * @returns {Container}
     */
    add(...args) {
      return this.set(...args);
    }

    /**
     * Removes all items from the container
     * @returns {undefined}
     */
    clear() {
      const ret = data.get(this).clear();
      sizes.set(this, 0);
      return ret;
    }

    /**
     * Removes the specified item to the container
     * @param {mixed} key
     * @param {Array<mixed>} keys
     * @returns {boolean}
     */
    delete(key, ...keys) {
      const mine = data.get(this);
      if (!keys.length) {
        return mine.delete(key);
      }

      const next = mine.get(key);
      if (!next) {
        return false;
      }

      const ret = next.delete(...keys);

      if (ret) {
        sizes.set(this, sizes.get(this) - 1);
      }

      if (next.size === 0) {
        mine.delete(key);
      }

      return ret;
    }

    /**
     * Retrieves the specified item from the container
     * @param {mixed} key
     * @param {Array<mixed>} keys
     * @returns {mixed}
     */
    get(key, ...keys) {
      const mine = data.get(this);

      if (!mine.get) {
        return mine;
      }

      if (!keys.length) {
        return mine.get(key);
      }

      const next = mine.get(key);
      if (!next) {
        return undefined;
      }

      if (!next.get) {
        return next;
      }
      return next.get(...keys);
    }

    /**
     * Indicates whether the container holds the specified item
     * @param {mixed} key
     * @param {Array<mixed>} keys
     * @returns {Boolean}
     */
    has(...args) {
      return typeof this.get(...args) !== `undefined`;
    }

    /**
     * Stores the specified item in the container
     * @param {mixed} key
     * @param {Array<mixed>} args
     * @param {mixed} value
     * @returns {Container}
     */
    set(...args) {
      let overwrite = false;
      if (this.has(...args)) {
        overwrite = true;
      }
      const mine = data.get(this);

      const key = args.shift();

      if (!mine.get) {
        insert(mine, key, ...args);
        return this;
      }

      let next = mine.get(key);
      if (!next) {
        if (!ChildContainer) {
          insert(mine, key, ...args);
          return this;
        }
        next = new ChildContainer();
        insert(mine, key, next);
      }
      insert(next, ...args);

      if (!overwrite) {
        sizes.set(this, sizes.get(this) + 1);
      }
      return this;
    }

    /**
     * @private
     * @returns {string}
     */
    inspect() {
      return `Container${name} {
  ${util.inspect(data.get(this), {depth: null})}
}`;
    }
  }

  return Container;
}

/**
 * Inserts into an arbitrary container
 * @param {Map|WeakMap|Set|WeakSet} container
 * @param {Array<mixed>} args
 * @private
 * @returns {undefined}
 */
function insert(container, ...args) {
  if (container.add) {
    container.add(...args);
    return;
  }

  if (container.set) {
    container.set(...args);
    return;
  }

  if (container.push) {
    container.push(...args);
    return;
  }
  throw new TypeError(`Could not determine how to insert into the specified container`);
}
export {make as default};


text:
/*
 * 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.
 */
package io.trino.execution;

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Multimap;
import io.trino.Session;
import io.trino.client.NodeVersion;
import io.trino.execution.scheduler.FlatNetworkTopology;
import io.trino.execution.scheduler.NetworkLocation;
import io.trino.execution.scheduler.NetworkTopology;
import io.trino.execution.scheduler.NodeScheduler;
import io.trino.execution.scheduler.NodeSchedulerConfig;
import io.trino.execution.scheduler.NodeSelector;
import io.trino.execution.scheduler.NodeSelectorFactory;
import io.trino.execution.scheduler.TopologyAwareNodeSelectorConfig;
import io.trino.execution.scheduler.TopologyAwareNodeSelectorFactory;
import io.trino.execution.scheduler.UniformNodeSelectorFactory;
import io.trino.jmh.Benchmarks;
import io.trino.metadata.InMemoryNodeManager;
import io.trino.metadata.InternalNode;
import io.trino.metadata.InternalNodeManager;
import io.trino.metadata.Split;
import io.trino.spi.HostAddress;
import io.trino.spi.connector.ConnectorSplit;
import io.trino.sql.planner.plan.PlanNodeId;
import io.trino.testing.TestingSession;
import io.trino.util.FinalizerService;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jol.info.ClassLayout;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.airlift.slice.SizeOf.estimatedSizeOf;
import static io.trino.SystemSessionProperties.MAX_UNACKNOWLEDGED_SPLITS_PER_TASK;
import static io.trino.testing.TestingHandles.TEST_CATALOG_HANDLE;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newScheduledThreadPool;

@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(1)
@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkNodeScheduler
{
    private static final int MAX_SPLITS_PER_NODE = 100;
    private static final int MAX_PENDING_SPLITS_PER_TASK_PER_NODE = 50;
    private static final int NODES = 200;
    private static final int DATA_NODES = 10_000;
    private static final int RACKS = DATA_NODES / 25;
    private static final int SPLITS = NODES * (MAX_SPLITS_PER_NODE + MAX_PENDING_SPLITS_PER_TASK_PER_NODE / 3);
    private static final int SPLIT_BATCH_SIZE = 100;

    @Benchmark
    @OperationsPerInvocation(SPLITS)
    public Object benchmark(BenchmarkData data)
    {
        List<RemoteTask> remoteTasks = ImmutableList.copyOf(data.getTaskMap().values());
        Iterator<MockRemoteTaskFactory.MockRemoteTask> finishingTask = Iterators.cycle(data.getTaskMap().values());
        Iterator<Split> splits = data.getSplits().iterator();
        Set<Split> batch = new HashSet<>();
        while (splits.hasNext() || !batch.isEmpty()) {
            Multimap<InternalNode, Split> assignments = data.getNodeSelector().computeAssignments(batch, remoteTasks).getAssignments();
            for (InternalNode node : assignments.keySet()) {
                MockRemoteTaskFactory.MockRemoteTask remoteTask = data.getTaskMap().get(node);
                remoteTask.addSplits(ImmutableMultimap.<PlanNodeId, Split>builder()
                        .putAll(new PlanNodeId("sourceId"), assignments.get(node))
                        .build());
                remoteTask.startSplits(MAX_SPLITS_PER_NODE);
            }
            if (assignments.size() == batch.size()) {
                batch.clear();
            }
            else {
                batch.removeAll(assignments.values());
            }
            while (batch.size() < SPLIT_BATCH_SIZE && splits.hasNext()) {
                batch.add(splits.next());
            }
            finishingTask.next().finishSplits((int) Math.ceil(MAX_SPLITS_PER_NODE / 50.0));
        }

        return remoteTasks;
    }

    @SuppressWarnings("FieldMayBeFinal")
    @State(Scope.Thread)
    public static class BenchmarkData
    {
        @Param({"uniform",
                "benchmark",
                "topology"})
        private String policy = "uniform";

        private FinalizerService finalizerService = new FinalizerService();
        private NodeSelector nodeSelector;
        private Map<InternalNode, MockRemoteTaskFactory.MockRemoteTask> taskMap = new HashMap<>();
        private List<Split> splits = new ArrayList<>();

        @Setup
        public void setup()
        {
            finalizerService.start();
            NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService);

            ImmutableList.Builder<InternalNode> nodeBuilder = ImmutableList.builder();
            for (int i = 0; i < NODES; i++) {
                nodeBuilder.add(new InternalNode("node" + i, URI.create("http://" + addressForHost(i).getHostText()), NodeVersion.UNKNOWN, false));
            }
            List<InternalNode> nodes = nodeBuilder.build();
            MockRemoteTaskFactory remoteTaskFactory = new MockRemoteTaskFactory(
                    newCachedThreadPool(daemonThreadsNamed("remoteTaskExecutor-%s")),
                    newScheduledThreadPool(2, daemonThreadsNamed("remoteTaskScheduledExecutor-%s")));
            for (int i = 0; i < nodes.size(); i++) {
                InternalNode node = nodes.get(i);
                ImmutableList.Builder<Split> initialSplits = ImmutableList.builder();
                for (int j = 0; j < MAX_SPLITS_PER_NODE + MAX_PENDING_SPLITS_PER_TASK_PER_NODE; j++) {
                    initialSplits.add(new Split(TEST_CATALOG_HANDLE, new TestSplitRemote(i)));
                }
                TaskId taskId = new TaskId(new StageId("test", 1), i, 0);
                MockRemoteTaskFactory.MockRemoteTask remoteTask = remoteTaskFactory.createTableScanTask(taskId, node, initialSplits.build(), nodeTaskMap.createPartitionedSplitCountTracker(node, taskId));
                nodeTaskMap.addTask(node, remoteTask);
                taskMap.put(node, remoteTask);
            }

            for (int i = 0; i < SPLITS; i++) {
                splits.add(new Split(TEST_CATALOG_HANDLE, new TestSplitRemote(ThreadLocalRandom.current().nextInt(DATA_NODES))));
            }

            NodeScheduler nodeScheduler = new NodeScheduler(getNodeSelectorFactory(new InMemoryNodeManager(), nodeTaskMap));
            Session session = TestingSession.testSessionBuilder()
                    .setSystemProperty(MAX_UNACKNOWLEDGED_SPLITS_PER_TASK, Integer.toString(Integer.MAX_VALUE))
                    .build();
            nodeSelector = nodeScheduler.createNodeSelector(session, Optional.of(TEST_CATALOG_HANDLE));
        }

        @TearDown
        public void tearDown()
        {
            finalizerService.destroy();
        }

        private NodeSchedulerConfig getNodeSchedulerConfig()
        {
            return new NodeSchedulerConfig()
                    .setMaxSplitsPerNode(MAX_SPLITS_PER_NODE)
                    .setIncludeCoordinator(false)
                    .setNodeSchedulerPolicy(policy)
                    .setMaxPendingSplitsPerTask(MAX_PENDING_SPLITS_PER_TASK_PER_NODE);
        }

        private NodeSelectorFactory getNodeSelectorFactory(InternalNodeManager nodeManager, NodeTaskMap nodeTaskMap)
        {
            NodeSchedulerConfig nodeSchedulerConfig = getNodeSchedulerConfig();
            switch (policy) {
                case "uniform":
                    return new UniformNodeSelectorFactory(nodeManager, nodeSchedulerConfig, nodeTaskMap);
                case "topology":
                    return new TopologyAwareNodeSelectorFactory(new FlatNetworkTopology(), nodeManager, nodeSchedulerConfig, nodeTaskMap, new TopologyAwareNodeSelectorConfig());
                case "benchmark":
                    return new TopologyAwareNodeSelectorFactory(new BenchmarkNetworkTopology(), nodeManager, nodeSchedulerConfig, nodeTaskMap, getBenchmarkNetworkTopologyConfig());
                default:
                    throw new IllegalStateException();
            }
        }

        public Map<InternalNode, MockRemoteTaskFactory.MockRemoteTask> getTaskMap()
        {
            return taskMap;
        }

        public NodeSelector getNodeSelector()
        {
            return nodeSelector;
        }

        public List<Split> getSplits()
        {
            return splits;
        }
    }

    public static void main(String[] args)
            throws Exception
    {
        Benchmarks.benchmark(BenchmarkNodeScheduler.class).run();
    }

    private static class BenchmarkNetworkTopology
            implements NetworkTopology
    {
        @Override
        public NetworkLocation locate(HostAddress address)
        {
            List<String> parts = new ArrayList<>(ImmutableList.copyOf(Splitter.on(".").split(address.getHostText())));
            Collections.reverse(parts);
            return new NetworkLocation(parts);
        }
    }

    private static TopologyAwareNodeSelectorConfig getBenchmarkNetworkTopologyConfig()
    {
        return new TopologyAwareNodeSelectorConfig()
                .setLocationSegmentNames(ImmutableList.of("rack", "machine"));
    }

    private static class TestSplitRemote
            implements ConnectorSplit
    {
        private static final int INSTANCE_SIZE = ClassLayout.parseClass(TestSplitRemote.class).instanceSize();

        private final List<HostAddress> hosts;

        public TestSplitRemote(int dataHost)
        {
            hosts = ImmutableList.of(addressForHost(dataHost));
        }

        @Override
        public boolean isRemotelyAccessible()
        {
            return true;
        }

        @Override
        public List<HostAddress> getAddresses()
        {
            return hosts;
        }

        @Override
        public Object getInfo()
        {
            return this;
        }

        @Override
        public long getRetainedSizeInBytes()
        {
            return INSTANCE_SIZE
                    + estimatedSizeOf(hosts, HostAddress::getRetainedSizeInBytes);
        }
    }

    private static HostAddress addressForHost(int host)
    {
        int rack = Integer.hashCode(host) % RACKS;
        return HostAddress.fromParts("host" + host + ".rack" + rack, 1);
    }
}


text:
package de.uniulm.omi.cloudiator.sword.domain;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by daniel on 01.07.16.
 */
public class SecurityGroupRuleBuilder {

  private IpProtocol ipProtocol;
  private int fromPort;
  private int toPort;
  private Cidr cidr;

  private SecurityGroupRuleBuilder() {

  }

  private SecurityGroupRuleBuilder(SecurityGroupRule securityGroupRule) {
    ipProtocol = securityGroupRule.ipProtocol();
    fromPort = securityGroupRule.fromPort();
    toPort = securityGroupRule.toPort();
    cidr = securityGroupRule.cidr();
  }

  public static SecurityGroupRuleBuilder newBuilder() {
    return new SecurityGroupRuleBuilder();
  }

  private SecurityGroupRuleBuilder of(SecurityGroupRule securityGroupRule) {
    checkNotNull(securityGroupRule, "SecurityGroupRule is null");
    return new SecurityGroupRuleBuilder(securityGroupRule);
  }

  public SecurityGroupRuleBuilder ipProtocol(IpProtocol ipProtocol) {
    this.ipProtocol = ipProtocol;
    return this;
  }

  public SecurityGroupRuleBuilder fromPort(int fromPort) {
    this.fromPort = fromPort;
    return this;
  }

  public SecurityGroupRuleBuilder toPort(int toPort) {
    this.toPort = toPort;
    return this;
  }

  public SecurityGroupRuleBuilder cidr(Cidr cidr) {
    this.cidr = cidr;
    return this;
  }

  public SecurityGroupRule build() {
    return new SecurityGroupRuleImpl(ipProtocol, fromPort, toPort, cidr);
  }

}


text:
//
// @file validation_service.hpp
// @brief The entity validation service.
//
// YANG Development Kit
// Copyright 2016 Cisco Systems. All rights reserved
//
////////////////////////////////////////////////////////////////
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
//
//////////////////////////////////////////////////////////////////

#ifndef VALIDATION_SERVICE_HPP
#define VALIDATION_SERVICE_HPP

#include <string>
#include <memory>

namespace ydk {

class Entity;
namespace path
{
class Session;
}

class ValidationService {

  public:

    ///
    /// @brief Options for validation.
    ///
    /// All validation is performed in the context of some yfilter.
    /// These options capture the context of use.
    ///
    enum class Option {
        DATASTORE,  /// Datastore validation. Note the DataNode Tree should contain everything for cross reference resolution
        GET_CONFIG, // Get config validation. Checks to see if only config nodes are references
        GET, // Get validation
        EDIT_CONFIG // Edit validation. Checks on the values of leafs etc
    };

    ValidationService()
    {
    }
    ~ValidationService(){}

    void validate(const ydk::path::Session& session, ydk::Entity& entity, ydk::ValidationService::Option option);
};

}

#endif /* VALIDATION_SERVICE_HPP */


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

namespace PivotalTrackerDotNet.Domain {
    public class Note {
        public int Id { get; set; }
        public string Text { get; set; }
        public string Author { get; set; }
        public string NotedAt { get; set; }

        public DateTime? Timestamp {
            get {
                if (!string.IsNullOrEmpty(NotedAt)) {
                    return DateTime.Parse(NotedAt.Replace(" UTC", "")).ToLocalTime();
                }
                return null;
            }
        }

        //<note>
        //  <id type="integer">18904723</id>
        //  <text>asdf</text>
        //  <author>pivotaltrackerdotnet</author>
        //  <noted_at type="datetime">2012/02/21 18:48:30 UTC</noted_at>
        //</note>
    }
}


text:
package com.gdx.musicevents.effects;

import com.gdx.musicevents.MusicState;

public class Stop implements StopEffect {
    private MusicState nextState;

    public Stop() {
    }

    @Override
    public void initialize(MusicState nextState, MusicState previousState) {
        this.nextState = nextState;
    }

    @Override
    public void beginStop() {
        nextState.stop();
    }

    @Override
    public void endStop() {

    }

    @Override
    public void update(float dt) {
    }

    @Override
    public boolean isDone() {
        return true;
    }
}


text:
from skdaccess.framework.data_class import DataFetcherCache, TableWrapper
from skdaccess.framework.param_class import *
from pkg_resources import resource_filename
from skdaccess.utilities.mahali_util import convert_date, parseIonoFile
from skdaccess.utilities.support import retrieveCommonDatesHDF

# Standard library imports
from urllib import parse
from collections import OrderedDict
from collections import defaultdict
from itertools import repeat

# 3rd party imports
from tqdm import tqdm
import pandas as pd

class DataFetcher(DataFetcherCache):
    '''
    Data Fetcher for Mahali Data
    '''

    def __init__(self, ap_paramList=[], start_date=None, end_date=None):
        '''
        Initialize Mahali Data Fetcher

        @param ap_paramList[stations]: Autolist of stations (Defaults to all stations)
        @param start_date: Starting date for seelcting data (Defaults to beginning of available data)
        @param end_date: Ending date for selecting data (Defaults to end of available data)
        '''

        # Get start date
        if start_date == None:
            self.start_date = pd.to_datetime('2015275', format='%Y%j')
        else:
            self.start_date = convert_date(start_date)

        # Get end date
        if end_date == None:
            self.end_date = pd.to_datetime('2015307', format='%Y%j')
        else:
            self.end_date = convert_date(end_date)

        self.date_range = pd.date_range(self.start_date, self.end_date)

        # Set station list if none is given
        if len(ap_paramList) == 0:
            station_list = [
                'mh02',
                'mh03',
                'mh04',
                'mh05',
                'mh06',
                'mh07',
                'mh08',
                'mh09',
                'mh13',
            ]
            ap_paramList = [ AutoList(station_list) ]

        super(DataFetcher, self).__init__(ap_paramList)

    def output(self):
        '''
        Generate data wrapper for Mahali tec data

        @return Mahali data wrapper
        '''

        def generatePath(base_url, station, in_date):
            '''
            Generate path to file based on station, date, and base url

            @param base_url: Base url to put in front of generated url
            @param station: Name of station
            @param in_date: Date of data to create path for

            @return The url for the station data
            '''
            year = in_date.strftime('%Y')
            day = in_date.strftime('%j')
            date = in_date.strftime('%Y%m%d')

            path = 'tec/{year}/{day}/{station}-{date}.iono.gz'.format(year=year,
                                                                      day=day,
                                                                      station=station,
                                                                      date=date)
            return parse.urljoin(base_url, path)

        # Get station lists
        station_list = self.ap_paramList[0]()

        # Retrieve dates containing data for station list
        available_data_dict = retrieveCommonDatesHDF('mahali_tec_info.hdf', station_list, self.date_range)

        # Location of data
        base_url = 'http://apollo.haystack.mit.edu/mahali-data/'
        url_list = []

        # Generate url list
        for station, dates in available_data_dict.items():
            url_list += list(map(generatePath, repeat(base_url), repeat(station), dates))

        # Cache data
        file_list = self.cacheData('mahali_tec', url_list)

        # Dictionary to hold parsed data
        parsed_data_dict = defaultdict(list)

        # Parse data
        for filename in file_list:
            station = filename[-21:-17]
            parsed_data_dict[station].append(parseIonoFile(filename))

        # combine data frames for each station into a single
        combined_data_dict = OrderedDict()

        for station,data in parsed_data_dict.items():
            combined_data_dict[station] = pd.concat(data)

        # Return data wrapper
        return TableWrapper(combined_data_dict, default_columns=['vertical_tec'])


text:
foreach my $file (@ARGV) {
	my $attribs = &attributes($file);
	print "'$file' $attribs.\n";
}

sub attributes {
	my $file = shift @_;
	return "does not exist" unless -e $file;
	my @attrib;
	push @attrib, "readable" if -r $file;
	push @attrib, "writable" if -w $file;
	push @attrib, "excutable" if -x $file;
	return "exists" unless @attrib;
	'is ' . join " and ", @attrib;
}


text:
package main.design.pattern.adapter.example1;

/**
 * Title : main.design.pattern.adapter.example1 <br>
 * Description :
 *
 *
 * @author chile
 * @version 1.0
 * @date 2020/12/10 11:07
 */
public class SmallDrillBit implements IDrillBit {

    /**
     * drill a hole, size is {#size}
     * @param size
     */
    @Override
    public void drill(int size) {
        System.out.println("drill small hole! size : " + size);
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	kubeconfig := flag.String("kubeconfig", "./config", "absolute path to the kubeconfig file")
	flag.Parse()
	// uses the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}
	// creates the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	for {
		pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
		if err != nil {
			panic(err.Error())
		}
		fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
		time.Sleep(10 * time.Second)
	}
}


text:
<!DOCTYPE html>

    <title>Suspended message</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="<?php echo base_url() ?>img/logo.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="<?php echo base_url() ?>img/logo.ico" type="image/x-icon"/>
    <link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <img src="<?php echo base_url() ?>img/logo.png"/>

Your account has been temporarily suspended

You have broken a morale rule.

If you think this was a mistake, please contact us at diarme@diarme.com

    <button onclick="location.href = '<?php echo site_url("home/logout"); ?>'" class="logout btn btn-primary">Logout</button>


text:
using System;
using System.Linq;
using System.Transactions;
using Dapper;
using Hangfire.Oracle.JobQueue;
using Xunit;
using Oracle.ManagedDataAccess.Client;

namespace Hangfire.Oracle.Tests.JobQueue
{
    public class OracleJobQueueMonitoringApiTests : IClassFixture<TestDatabaseFixture>, IDisposable
    {
        private readonly OracleJobQueueMonitoringApi _sut;
        private readonly OracleStorage _storage;
        private readonly OracleConnection _connection;
        private readonly string _queue = "default";

        public OracleJobQueueMonitoringApiTests()
        {
            _connection = new OracleConnection(ConnectionUtils.GetConnectionString());
            _connection.Open();

            _storage = new OracleStorage(_connection);

            _sut = new OracleJobQueueMonitoringApi(_storage);
        }

        public void Dispose()
        {
            _connection.Dispose();
            _storage.Dispose();
        }

        [Fact, CleanDatabase(IsolationLevel.ReadUncommitted)]
        public void GetEnqueuedAndFetchedCount_ReturnsEqueuedCount_WhenExists()
        {
            EnqueuedAndFetchedCountDto result = null;

            _storage.UseConnection(connection =>
            {
                connection.Execute(
                    "insert into HANGFIRE_JOBQUEUE (JobId, Queue) values (1, :queue)",
                    new { queue = _queue });

                result = _sut.GetEnqueuedAndFetchedCount(_queue);

                connection.Execute("delete from HANGFIRE_JOBQUEUE");
            });

            Assert.Equal(1, result.EnqueuedCount);
        }

        [Fact, CleanDatabase(IsolationLevel.ReadUncommitted)]
        public void GetEnqueuedJobIds_ReturnsEmptyCollection_IfQueueIsEmpty()
        {
            var result = _sut.GetEnqueuedJobIds(_queue, 5, 15);

            Assert.Empty(result);
        }

        [Fact, CleanDatabase(IsolationLevel.ReadUncommitted)]
        public void GetEnqueuedJobIds_ReturnsCorrectResult()
        {
            int[] result = null;
            _storage.UseConnection(connection =>
            {
                for (var i = 1; i <= 10; i++)
                {
                    connection.Execute(
                        "insert into HANGFIRE_JOBQUEUE (JobId, Queue) " +
                        "values (:jobId, :queue)", new {jobId = i, queue = _queue});
                }

                result = _sut.GetEnqueuedJobIds(_queue, 3, 2).ToArray();

                connection.Execute("delete from HANGFIRE_JOBQUEUE");
            });

            Assert.Equal(2, result.Length);
            Assert.Equal(4, result[0]);
            Assert.Equal(5, result[1]);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RegionalFF.Models
{
    public class MenuAdmin
    {
        [HiddenInput(DisplayValue = true)]
        public int Id { get; set; }

        public virtual int PadreId { get; set; }

        [Required(ErrorMessage = "El nombre del menú es requerido")]
        public string Nombre { get; set; }

        [Required(ErrorMessage = "La descripción del menú es requerida")]
        public string Descripcion { get; set; }

        public string Accion { get; set; }

        public string Controlador { get; set; }

        public bool Activo { get; set; }

        public List<MenuAdmin> Hijo()
        {
            ApplicationDbContext db = new ApplicationDbContext();
            return db.MenuAdmins.Where(b => b.PadreId == this.Id).ToList();
        }
    }
}


text:
package com.iluwatar.factory.method;

/**
 *
 * The Factory Method is a creational design pattern which uses factory methods to deal with the
 * problem of creating objects without specifying the exact class of object that will be created.
 * This is done by creating objects via calling a factory method either specified in an interface
 * and implemented by child classes, or implemented in a base class and optionally overridden by
 * derived classes—rather than by calling a constructor.
 * <p>
 * In this Factory Method example we have an interface ({@link Blacksmith}) with a method for
 * creating objects ({@link Blacksmith#manufactureWeapon}). The concrete subclasses (
 * {@link OrcBlacksmith}, {@link ElfBlacksmith}) then override the method to produce objects of
 * their liking.
 *
 */
public class App {

  /**
   * Program entry point
   *
   * @param args command line args
   */
  public static void main(String[] args) {
    Blacksmith blacksmith;
    Weapon weapon;

    blacksmith = new OrcBlacksmith();
    weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
    System.out.println(weapon);
    weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
    System.out.println(weapon);

    blacksmith = new ElfBlacksmith();
    weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
    System.out.println(weapon);
    weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
    System.out.println(weapon);
  }
}


text:
$(document).ready(function(){
	$('table').tablesorter();
	$('a').tooltip();
});
//= require_tree .


text:
lp = File.expand_path(File.join(*%w[.. .. lib]), File.dirname(__FILE__))
unless $LOAD_PATH.include?(lp)
  $LOAD_PATH.unshift(lp)
end


text:
package com.rental.account.service;

import com.rental.account.domain.Account;
import com.rental.account.domain.User;

public interface AccountService {

	Account findByName(String accountName);

	Account create(User user);

	void saveChanges(String name, Account update);
}


text:
const React = require('react');

class Footer extends React.Component {
  docUrl(doc, language) {
    const baseUrl = this.props.config.baseUrl;
    return baseUrl + 'docs/' + (language ? language + '/' : '') + doc;
  }

  pageUrl(doc, language) {
    const baseUrl = this.props.config.baseUrl;
    return baseUrl + (language ? language + '/' : '') + doc;
  }

  render() {
    const currentYear = new Date().getFullYear();
    return (

            {this.props.config.footerIcon && (

            )}

Docs

              Getting Started

              API Reference

Community

              User Showcase

              Stack Overflow

            {/* Project Chat */}
            {/*  */}
            {/* Twitter */}
            {/*  */}

More

            Blog
            GitHub

              Star

          {/*  */}

            Copyright © {currentYear} Matteo Joliveau.

    );
  }
}

module.exports = Footer;


text:
module Enumerable
  # Applies a method to the collection of various arguments.
  #
  # @example Requires multiple files
  #   # Without Nutella:
  #   %w[several libs to include].each { |r| require r }
  #   # With Nutella:
  #   %w[several libs to include].apply :require
  #
  # @example Passes in multiple arguments
  #   # Without Nutella:
  #   [1, 2, 3].each { |n| foo n, 5 }
  #   # With Nutella:
  #   [1, 2, 3].apply :foo, 5
  #
  # @example Uses a multi-dimensional array to get the extra arguments
  #   arr = [[1, 2], [3, 4], [5, 6]]
  #   # Without Nutella:
  #   arr.each { |a, b| foo a, b }
  #   # With Nutella:
  #   arr.apply :foo
  #
  # @param [Symbol] method the method to apply
  # @param [*Object] args any extra arguments to use
  # @return [Array] a list of the return values of the method calls
  def apply(method, *args)
    map { |elem| method(method).(*elem, *args) }
  end
end


text:
var express = require('express')
    , router = express.Router();

var User = require('../models/user');
var pautils = require('../util/pautils');
var authSvc = require('../services/auth-service');

// ROUTES FOR OUR API
// =============================================================================

router.route('/auth')
/**
 * Simple validation of username in order to play with value point - the passcard
 */
// authenticate a user (accessed at POST http://localhost:8080/api/users)
    .post(function(req, res) {
        authSvc.auth(req.body.username, req.body.password)
            .then(function(svcResult, err) {
                if (err) throw(err);
                console.log(svcResult);
                res.json(svcResult);
            });
        /*
        authSvc.auth(req.body.username, req.body.password, function(err, svcResult) {
            res.json(svcResult);
        });
         */
        /*
        var username = req.body.username;  // set the users name (comes from the request)
        if (username.length > 0) {
            // get the user
            User
                .find({ username: username }, function(err, user) {
                    if (err) throw err;
                    if (user.length === 1 && user[0].username.toLowerCase() === username.toLowerCase()) {
                        var token = pautils.generateToken(user[0].username);
                        res.json({ result: 200, message: 'Success', token: token, user: user[0] });
                        return;
                    }
                    res.json({ result: -1, message: 'The username or password is incorrect.  Please try again.' });
                })
                .populate('group');
        } else {
            res.json({ result: -1, message: 'The username or password is incorrect.  Please try again.' });

        }
        */

    });

router.route('/apiauth/:identity')
/**
 * simple api version of authenticate. Should validate with a known "identity" key
 */
    .get(function(req, res) {

        authSvc.auth(req.params.identity)
            .then(function(svcResult, err) {
                if (err) throw(err);
                res.json(svcResult);
            });
        /*
        authSvc.auth(req.params.identity, function(svcResult) {
            res.json(svcResult);
        });

        var identity = req.params.identity;  // get the identity from the URL
        if (identity.length > 0) {
            var token = pautils.generateToken(identity);
            res.json({ result: 200, message: 'Success', token: token });
        } else {
            res.json({ result: -1, message: 'The username or password is incorrect.  Please try again.' });
        }
        */

    });

module.exports = router;


text:
var React = require('react');
var ReactDOM = require('react-dom');

var Routes = require('./components/Routes');

ReactDOM.render(<Routes />, document.getElementById('main'));


text:
<?php

namespace Hazbo\Component\Utils;

/**
 * Convert a string into valid UTF-8. This function is quite slow.
 *
 * When invalid byte subsequences are encountered, they will be replaced with
 * U+FFFD, the Unicode replacement character.
 *
 * @param   string  String to convert to valid UTF-8.
 * @return  string  String with invalid UTF-8 byte subsequences replaced with
 *                  U+FFFD.
 * @group utf8
 */

class Utf8
{
function phutil_utf8ize($string) {
  if (self::phutil_is_utf8($string)) {
    return $string;
  }

  // There is no function to do this in iconv, mbstring or ICU to do this, so
  // do it (very very slowly) in pure PHP.

  // TODO: Provide an optional fast C implementation ala fb_utf8ize() if this
  // ever shows up in profiles?

  $result = array();

  $regex =
    "/([\x01-\x7F]".
    "|[\xC2-\xDF][\x80-\xBF]".
    "|[\xE0-\xEF][\x80-\xBF][\x80-\xBF]".
    "|[\xF0-\xF4][\x80-\xBF][\x80-\xBF][\x80-\xBF])".
    "|(.)/";

  $offset = 0;
  $matches = null;
  while (preg_match($regex, $string, $matches, 0, $offset)) {
    if (!isset($matches[2])) {
      $result[] = $matches[1];
    } else {
      // Unicode replacement character, U+FFFD.
      $result[] = "\xEF\xBF\xBD";
    }
    $offset += strlen($matches[0]);
  }

  return implode('', $result);
}

/**
 * Determine if a string is valid UTF-8.
 *
 * @param string  Some string which may or may not be valid UTF-8.
 * @return bool    True if the string is valid UTF-8.
 * @group utf8
 */
public function phutil_is_utf8($string) {
  if (function_exists('mb_check_encoding')) {
    // If mbstring is available, this is significantly faster than using PHP
    // regexps.
    return mb_check_encoding($string, 'UTF-8');
  }

  $regex =
    "/^(".
      "[\x01-\x7F]+".
    "|([\xC2-\xDF][\x80-\xBF])".
    "|([\xE0-\xEF][\x80-\xBF][\x80-\xBF])".
    "|([\xF0-\xF4][\x80-\xBF][\x80-\xBF][\x80-\xBF]))*\$/";

  return preg_match($regex, $string);
}

/**
 * Find the character length of a UTF-8 string.
 *
 * @param string A valid utf-8 string.
 * @return int   The character length of the string.
 * @group utf8
 */
function phutil_utf8_strlen($string) {
  return strlen(utf8_decode($string));
}

/**
 * Find the console display length of a UTF-8 string. This may differ from the
 * character length of the string if it contains double-width characters, like
 * many Chinese characters.
 *
 * This method is based on a C implementation here, which is based on the IEEE
 * standards. The source has more discussion and addresses more considerations
 * than this implementation does.
 *
 *   http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
 *
 * NOTE: We currently do not handle combining characters correctly.
 *
 * NOTE: We currently assume width 1 for East-Asian ambiguous characters.
 *
 * NOTE: This function is VERY slow.
 *
 * @param   string  A valid UTF-8 string.
 * @return  int     The console display length of the string.
 * @group   utf8
 */
function phutil_utf8_console_strlen($string) {
  $string_v = phutil_utf8v_codepoints($string);

  $len = 0;
  foreach ($string_v as $c) {
    if ($c == 0) {
      continue;
    }

    $len += 1 +
      ($c >= 0x1100 &&
        ($c <= 0x115f ||                    /* Hangul Jamo init. consonants */
          $c == 0x2329 || $c == 0x232a ||
          ($c >= 0x2e80 && $c <= 0xa4cf &&
            $c != 0x303f) ||                  /* CJK ... Yi */
          ($c >= 0xac00 && $c <= 0xd7a3) || /* Hangul Syllables */
          ($c >= 0xf900 && $c <= 0xfaff) || /* CJK Compatibility Ideographs */
          ($c >= 0xfe10 && $c <= 0xfe19) || /* Vertical forms */
          ($c >= 0xfe30 && $c <= 0xfe6f) || /* CJK Compatibility Forms */
          ($c >= 0xff00 && $c <= 0xff60) || /* Fullwidth Forms */
          ($c >= 0xffe0 && $c <= 0xffe6) ||
          ($c >= 0x20000 && $c <= 0x2fffd) ||
          ($c >= 0x30000 && $c <= 0x3fffd)));
  }

  return $len;
}

/**
 * Split a UTF-8 string into an array of characters. Combining characters are
 * also split.
 *
 * @param string A valid utf-8 string.
 * @return list  A list of characters in the string.
 * @group utf8
 */
function phutil_utf8v($string) {
  $res = array();
  $len = strlen($string);
  $ii = 0;
  while ($ii < $len) {
    $byte = $string[$ii];
    if ($byte <= "\x7F") {
      $res[] = $byte;
      $ii += 1;
      continue;
    } else if ($byte < "\xC0") {
      throw new Exception("Invalid UTF-8 string passed to phutil_utf8v().");
    } else if ($byte <= "\xDF") {
      $seq_len = 2;
    } else if ($byte <= "\xEF") {
      $seq_len = 3;
    } else if ($byte <= "\xF7") {
      $seq_len = 4;
    } else if ($byte <= "\xFB") {
      $seq_len = 5;
    } else if ($byte <= "\xFD") {
      $seq_len = 6;
    } else {
      throw new Exception("Invalid UTF-8 string passed to phutil_utf8v().");
    }

    if ($ii + $seq_len > $len) {
      throw new Exception("Invalid UTF-8 string passed to phutil_utf8v().");
    }
    for ($jj = 1; $jj < $seq_len; ++$jj) {
      if ($string[$ii + $jj] >= "\xC0") {
        throw new Exception("Invalid UTF-8 string passed to phutil_utf8v().");
      }
    }
    $res[] = substr($string, $ii, $seq_len);
    $ii += $seq_len;
  }
  return $res;
}

/**
 * Split a UTF-8 string into an array of codepoints (as integers).
 *
 * @param   string  A valid UTF-8 string.
 * @return  list    A list of codepoints, as integers.
 * @group   utf8
 */
function phutil_utf8v_codepoints($string) {
  $str_v = phutil_utf8v($string);

  foreach ($str_v as $key => $char) {
    $c = ord($char[0]);
    $v = 0;

    if (($c & 0x80) == 0) {
      $v = $c;
    } else if (($c & 0xE0) == 0xC0) {
      $v = (($c & 0x1F) << 6)
         + ((ord($char[1]) & 0x3F));
    } else if (($c & 0xF0) == 0xE0) {
      $v = (($c & 0x0F) << 12)
         + ((ord($char[1]) & 0x3f) << 6)
         + ((ord($char[2]) & 0x3f));
    } else if (($c & 0xF8) == 0xF0) {
      $v = (($c & 0x07) << 18)
         + ((ord($char[1]) & 0x3F) << 12)
         + ((ord($char[2]) & 0x3F) << 6)
         + ((ord($char[3]) & 0x3f));
    } else if (($c & 0xFC) == 0xF8) {
      $v = (($c & 0x03) << 24)
         + ((ord($char[1]) & 0x3F) << 18)
         + ((ord($char[2]) & 0x3F) << 12)
         + ((ord($char[3]) & 0x3f) << 6)
         + ((ord($char[4]) & 0x3f));
    } else if (($c & 0xFE) == 0xFC) {
      $v = (($c & 0x01) << 30)
         + ((ord($char[1]) & 0x3F) << 24)
         + ((ord($char[2]) & 0x3F) << 18)
         + ((ord($char[3]) & 0x3f) << 12)
         + ((ord($char[4]) & 0x3f) << 6)
         + ((ord($char[5]) & 0x3f));
    }

    $str_v[$key] = $v;
  }

  return $str_v;
}

/**
 * Shorten a string to provide a summary, respecting UTF-8 characters. This
 * function attempts to truncate strings at word boundaries.
 *
 * NOTE: This function makes a best effort to apply some reasonable rules but
 * will not work well for the full range of unicode languages.
 *
 * @param   string  UTF-8 string to shorten.
 * @param   int     Maximum length of the result.
 * @param   string  If the string is shortened, add this at the end. Defaults to
 *                  horizontal ellipsis.
 * @return  string  A string with no more than the specified character length.
 *
 * @group utf8
 */
function phutil_utf8_shorten($string, $length, $terminal = "\xE2\x80\xA6") {
  // If the string has fewer bytes than the minimum length, we can return
  // it unmodified without doing any heavy lifting.
  if (strlen($string) <= $length) {
    return $string;
  }

  $string_v = phutil_utf8v_combined($string);
  $string_len = count($string_v);

  if ($string_len <= $length) {
    // If the string is already shorter than the requested length, simply return
    // it unmodified.
    return $string;
  }

  // NOTE: This is not complete, and there are many other word boundary
  // characters and reasonable places to break words in the UTF-8 character
  // space. For now, this gives us reasonable behavior for latin langauges. We
  // don't necessarily have access to PCRE+Unicode so there isn't a great way
  // for us to look up character attributes.

  // If we encounter these, prefer to break on them instead of cutting the
  // string off in the middle of a word.
  static $break_characters = array(
    ' '   => true,
    "\n"  => true,
    ';'   => true,
    ':'   => true,
    '['   => true,
    '('   => true,
    ','   => true,
    '-'   => true,
  );

  // If we encounter these, shorten to this character exactly without appending
  // the terminal.
  static $stop_characters = array(
    '.'   => true,
    '!'   => true,
    '?'   => true,
  );

  // Search backward in the string, looking for reasonable places to break it.
  $word_boundary = null;
  $stop_boundary = null;

  $terminal_len = phutil_utf8_strlen($terminal);

  // If we do a word break with a terminal, we have to look beyond at least the
  // number of characters in the terminal. If the terminal is longer than the
  // required length, we'll skip this whole block and return it on its own
  $terminal_area = $length - min($length, $terminal_len);
  for ($ii = $length; $ii >= 0; $ii--) {
    $c = $string_v[$ii];

    if (isset($break_characters[$c]) && ($ii <= $terminal_area)) {
      $word_boundary = $ii;
    } else if (isset($stop_characters[$c]) && ($ii < $length)) {
      $stop_boundary = $ii + 1;
      break;
    } else {
      if ($word_boundary !== null) {
        break;
      }
    }
  }

  if ($stop_boundary !== null) {
    // We found a character like ".". Cut the string there, without appending
    // the terminal.
    $string_part = array_slice($string_v, 0, $stop_boundary);
    return implode('', $string_part);
  }

  // If we didn't find any boundary characters or we found ONLY boundary
  // characters, just break at the maximum character length.
  if ($word_boundary === null || $word_boundary === 0) {
    $word_boundary = $terminal_area;
  }

  $string_part = array_slice($string_v, 0, $word_boundary);
  $string_part = implode('', $string_part);
  return $string_part.$terminal;
}

/**
 * Hard-wrap a block of UTF-8 text with embedded HTML tags and entities.
 *
 * @param   string An HTML string with tags and entities.
 * @return  list   List of hard-wrapped lines.
 * @group utf8
 */
function phutil_utf8_hard_wrap_html($string, $width) {
  $break_here = array();

  // Convert the UTF-8 string into a list of UTF-8 characters.
  $vector = phutil_utf8v($string);
  $len = count($vector);
  $char_pos = 0;
  for ($ii = 0; $ii < $len; ++$ii) {
    // An ampersand indicates an HTML entity; consume the whole thing (until
    // ";") but treat it all as one character.
    if ($vector[$ii] == '&') {
      do {
        ++$ii;
      } while ($vector[$ii] != ';');
      ++$char_pos;
    // An "<" indicates an HTML tag, consume the whole thing but don't treat
    // it as a character.
    } else if ($vector[$ii] == '<') {
      do {
        ++$ii;
      } while ($vector[$ii] != '>');
    } else {
      ++$char_pos;
    }

    // Keep track of where we need to break the string later.
    if ($char_pos == $width) {
      $break_here[$ii] = true;
      $char_pos = 0;
    }
  }

  $result = array();
  $string = '';
  foreach ($vector as $ii => $char) {
    $string .= $char;
    if (isset($break_here[$ii])) {
      $result[] = $string;
      $string = '';
    }
  }

  if (strlen($string)) {
    $result[] = $string;
  }

  return $result;
}

/**
  * Hard-wrap a block of UTF-8 text with no embedded HTML tags and entitites
  *
  * @param string A non HTML string
  * @param int Width of the hard-wrapped lines
  * @return list List of hard-wrapped lines.
  * @group utf8
  */
function phutil_utf8_hard_wrap($string, $width) {
  $result = array();

  $lines = phutil_split_lines($string, $retain_endings = false);
  foreach ($lines as $line) {

    // Convert the UTF-8 string into a list of UTF-8 characters.
    $vector = phutil_utf8v($line);

    $len = count($vector);
    $buffer = '';

    for ($ii = 1; $ii <= $len; ++$ii) {
      $buffer .= $vector[$ii - 1];
      if (($ii % $width) === 0) {
        $result[] = $buffer;
        $buffer = '';
      }
    }

    if (strlen($buffer)) {
      $result[] = $buffer;
    }
  }

  return $result;
}

/**
 * Convert a string from one encoding (like ISO-8859-1) to another encoding
 * (like UTF-8).
 *
 * This is primarily a thin wrapper around `mb_convert_encoding()` which checks
 * you have the extension installed, since we try to require the extension
 * only if you actually need it (i.e., you want to work with encodings other
 * than UTF-8).
 *
 * NOTE: This function assumes that the input is in the given source encoding.
 * If it is not, it may not output in the specified target encoding. If you
 * need to perform a hard conversion to UTF-8, use this function in conjunction
 * with @{function:phutil_utf8ize}. We can detect failures caused by invalid
 * encoding names, but `mb_convert_encoding()` fails silently if the
 * encoding name identifies a real encoding but the string is not actually
 * encoded with that encoding.
 *
 * @param string String to re-encode.
 * @param string Target encoding name, like "UTF-8".
 * @param string Source endocing name, like "ISO-8859-1".
 * @return string Input string, with converted character encoding.
 *
 * @group utf8
 *
 * @phutil-external-symbol function mb_convert_encoding
 */
function phutil_utf8_convert($string, $to_encoding, $from_encoding) {
  if (!$from_encoding) {
    throw new InvalidArgumentException(
      "Attempting to convert a string encoding, but no source encoding ".
      "was provided. Explicitly provide the source encoding.");
  }
  if (!$to_encoding) {
    throw new InvalidArgumentException(
      "Attempting to convert a string encoding, but no target encoding ".
      "was provided. Explicitly provide the target encoding.");
  }

  // Normalize encoding names so we can no-op the very common case of UTF8
  // to UTF8 (or any other conversion where both encodings are identical).
  $to_upper = strtoupper(str_replace('-', '', $to_encoding));
  $from_upper = strtoupper(str_replace('-', '', $from_encoding));
  if ($from_upper == $to_upper) {
    return $string;
  }

  if (!function_exists('mb_convert_encoding')) {
    throw new Exception(
      "Attempting to convert a string encoding from '{$from_encoding}' ".
      "to '{$to_encoding}', but the 'mbstring' PHP extension is not ".
      "available. Install mbstring to work with encodings other than ".
      "UTF-8.");
  }

  $result = @mb_convert_encoding($string, $to_encoding, $from_encoding);

  if ($result === false) {
    $message = error_get_last();
    if ($message) {
      $message = idx($message, 'message', 'Unknown error.');
    }
    throw new Exception(
      "String conversion from encoding '{$from_encoding}' to encoding ".
      "'{$to_encoding}' failed: {$message}");
  }

  return $result;
}

/**
 * Convert a string to title case in a UTF8-aware way. This function doesn't
 * necessarily do a great job, but the builtin implementation of ucwords() can
 * completely destroy inputs, so it just has to be better than that. Similar to
 * @{function:ucwords}.
 *
 * @param   string  UTF-8 input string.
 * @return  string  Input, in some semblance of title case.
 *
 * @group utf8
 */
function phutil_utf8_ucwords($str) {
  // NOTE: mb_convert_case() discards uppercase letters in words when converting
  // to title case. For example, it will convert "AAA" into "Aaa", which is
  // undesirable.

  $v = phutil_utf8v($str);
  $result = '';
  $last = null;

  $ord_a = ord('a');
  $ord_z = ord('z');
  foreach ($v as $c) {
    $convert = false;
    if ($last === null || $last === ' ') {
      $o = ord($c[0]);
      if ($o >= $ord_a && $o <= $ord_z) {
        $convert = true;
      }
    }

    if ($convert) {
      $result .= phutil_utf8_strtoupper($c);
    } else {
      $result .= $c;
    }

    $last = $c;
  }

  return $result;
}

/**
 * Convert a string to lower case in a UTF8-aware way. Similar to
 * @{function:strtolower}.
 *
 * @param   string  UTF-8 input string.
 * @return  string  Input, in some semblance of lower case.
 *
 * @group utf8
 *
 * @phutil-external-symbol function mb_convert_case
 */
function phutil_utf8_strtolower($str) {
  if (function_exists('mb_convert_case')) {
    return mb_convert_case($str, MB_CASE_LOWER, 'UTF-8');
  }

  static $map;
  if ($map === null) {
    $map = array_combine(
      range('A', 'Z'),
      range('a', 'z'));
  }

  return phutil_utf8_strtr($str, $map);
}

/**
 * Convert a string to upper case in a UTF8-aware way. Similar to
 * @{function:strtoupper}.
 *
 * @param   string  UTF-8 input string.
 * @return  string  Input, in some semblance of upper case.
 *
 * @group utf8
 *
 * @phutil-external-symbol function mb_convert_case
 */
function phutil_utf8_strtoupper($str) {
  if (function_exists('mb_convert_case')) {
    return mb_convert_case($str, MB_CASE_UPPER, 'UTF-8');
  }

  static $map;
  if ($map === null) {
    $map = array_combine(
      range('a', 'z'),
      range('A', 'Z'));
  }

  return phutil_utf8_strtr($str, $map);
}

/**
 * Replace characters in a string in a UTF-aware way. Similar to
 * @{function:strtr}.
 *
 * @param   string              UTF-8 input string.
 * @param   map<string, string> Map of characters to replace.
 * @return  string              Input with translated characters.
 *
 * @group utf8
 */
function phutil_utf8_strtr($str, array $map) {
  $v = phutil_utf8v($str);
  $result = '';
  foreach ($v as $c) {
    if (isset($map[$c])) {
      $result .= $map[$c];
    } else {
      $result .= $c;
    }
  }

  return $result;
}

/**
 * Determine if a given unicode character is a combining character or not.
 *
 * @param   string              A single unicode character.
 * @return  boolean             True or false.
 *
 * @group utf8
 */

function phutil_utf8_is_combining_character($character) {
  $components = phutil_utf8v_codepoints($character);

  // Combining Diacritical Marks (0300 - 036F).
  // Combining Diacritical Marks Supplement (1DC0 - 1DFF).
  // Combining Diacritical Marks for Symbols (20D0 - 20FF).
  // Combining Half Marks (FE20 - FE2F).

  foreach ($components as $codepoint) {
    if ($codepoint >= 0x0300 && $codepoint <= 0x036F ||
         $codepoint >= 0x1DC0 && $codepoint <= 0x1DFF ||
         $codepoint >= 0x20D0 && $codepoint <= 0x20FF ||
         $codepoint >= 0xFE20 && $codepoint <= 0xFE2F) {
      return true;
    }
  }

  return false;
}

/**
 * Split a UTF-8 string into an array of characters. Combining characters
 * are not split.
 *
 * @param string A valid utf-8 string.
 * @return list  A list of characters in the string.
 *
 * @group utf8
 */

function phutil_utf8v_combined($string) {
  $components = phutil_utf8v($string);
  $array_length = count($components);

  // If the first character in the string is a combining character,
  // prepend a space to the string.
  if (
    $array_length > 0 &&
    phutil_utf8_is_combining_character($components[0])) {
    $string = " ".$string;
    $components = phutil_utf8v($string);
    $array_length++;
  }

  for ($index = 1; $index < $array_length; $index++) {
    if (phutil_utf8_is_combining_character($components[$index])) {
      $components[$index - 1] =
        $components[$index - 1].$components[$index];

      unset($components[$index]);
      $components = array_values($components);

      $index --;
      $array_length = count($components);
    }
  }

  return $components;
}

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>String Template Resources</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="Smarty 3 Manual">
<link rel="up" href="resources.html" title="Chapter 16. Resources">
<link rel="prev" href="resources.html" title="Chapter 16. Resources">
<link rel="next" href="resources.streams.html" title="Stream Template Resources">

String Template Resources

Prev
Chapter 16. Resources
 Next

String Template Resources

  Smarty can render templates from a string by using the string: or eval: resource.

    The string: resource behaves much the same as a template file.
    The template source is compiled from a string and stores the compiled template code for later reuse.
    Each unique template string will create a new compiled template file.
    If your template strings are accessed frequently, this is a good choice.
    If you have frequently changing template strings (or strings with low reuse value),
    the eval: resource may be a better choice, as it doesn't save compiled templates to disk.

    The eval: resource evaluates the template source every time a page is rendered. This is a good choice
    for strings with low reuse value. If the same string is accessed frequently, the string: resource may
    be a better choice.

Note

   With a string: resource type, each unique string generates a compiled file. Smarty cannot detect a string that has changed,
   and therefore will generate a new compiled file for each unique string. It is important to choose the correct resource so that you do not
   fill your disk space with wasted compiled strings.

Example 16.5. Using templates from strings

<?php
$smarty->assign('foo','value');
$template_string = 'display {$foo} here';
$smarty->display('string:'.$template_string); // compiles for later reuse
$smarty->display('eval:'.$template_string); // compiles every time
?>

From within a Smarty template

{include file="string:$template_string"} {* compiles for later reuse *}
{include file="eval:$template_string"} {* compiles every time *}

     Both string: and eval: resources may be encoded with
     urlencode() or
     base64_encode(). This is
     not necessary for the usual use of string: and eval:,
     but is required when using either of them in conjunction with
     Extends Template Resource

Example 16.6. Using templates from encoded strings

 <?php
 $smarty->assign('foo','value');
 $template_string_urlencode = urlencode('display {$foo} here');
 $template_string_base64 = base64_encode('display {$foo} here');
 $smarty->display('eval:urlencode:'.$template_string_urlencode); // will decode string using urldecode()
 $smarty->display('eval:base64:'.$template_string_base64); // will decode string using base64_decode()
 ?>

From within a Smarty template

 {include file="string:urlencode:$template_string_urlencode"} {* will decode string using urldecode() *}
 {include file="eval:base64:$template_string_base64"} {* will decode string using base64_decode() *}

Prev
Up
 Next

Chapter 16. Resources
Home
 Stream Template Resources


text:
from Acspy.Clients.SimpleClient import PySimpleClient
from sys                        import argv
from sys                        import exit
from TMCDB                      import MonitorCollector
from TMCDB                      import propertySerailNumber
from omniORB                    import any
import MonitorErrImpl
import MonitorErr
import time

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

try:
    tc =   simpleClient.getComponent('MC_TEST_COMPONENT')
    psns =[propertySerailNumber('doubleSeqProp', ['12124']),propertySerailNumber('doubleProp', ['3432535'])]
    mc.registerMonitoredDeviceWithMultipleSerial('MC_TEST_COMPONENT', psns)
    tc.reset();
    mc.startMonitoring('MC_TEST_COMPONENT')
    time.sleep(10)
    #Change archiving interval to 2 seconds instead of 1
    mc.set_archiving_interval('MC_TEST_COMPONENT','doubleProp',20000000)
    mc.set_archiving_interval('MC_TEST_COMPONENT','doubleSeqProp',20000000)
    time.sleep(10)
    mc.stopMonitoring('MC_TEST_COMPONENT')
except MonitorErr.RegisteringDeviceProblemEx, _ex:
    ex = MonitorErrImpl.RegisteringDeviceProblemExImpl(exception=_ex)
    ex.Print();

data = mc.getMonitorData()
print "Number of Devices:", len(data);
for d in data:
    print d.componentName, d.deviceSerialNumber
    for blob in d.monitorBlobs:
        print "\t", blob.propertyName, blob.propertySerialNumber
        for blobData in any.from_any(blob.blobDataSeq):
            print "\t\t", blobData

mc.deregisterMonitoredDevice('MC_TEST_COMPONENT')

#cleanly disconnect
simpleClient.releaseComponent(argv[1])
simpleClient.disconnect()