text:
package com.facebook.flipper.plugins.inspector;

import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;

/**
 * A singleton instance of a overlay drawable used for highlighting node bounds. See {@link
 * NodeDescriptor#setHighlighted(Object, boolean)}.
 */
public class HighlightedOverlay {
  private static final boolean VIEW_OVERLAY_SUPPORT =
      Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;

  /**
   * Highlights a particular view with its content bounds, padding and margin dimensions
   *
   * @param targetView The view to apply the highlight on
   * @param margin A {@link Rect} containing the margin values
   * @param padding A {@link Rect} containing the padding values
   * @param contentBounds The {@link Rect} bounds of the content, which includes padding
   */
  public static void setHighlighted(
      View targetView, Rect margin, Rect padding, Rect contentBounds, boolean isAlignmentMode) {
    if (!VIEW_OVERLAY_SUPPORT) {
      return;
    }

    contentBounds.set(
        contentBounds.left + padding.left,
        contentBounds.top + padding.top,
        contentBounds.right - padding.right,
        contentBounds.bottom - padding.bottom);

    padding = enclose(padding, contentBounds);
    margin = enclose(margin, padding);

    final float density = targetView.getContext().getResources().getDisplayMetrics().density;
    final Drawable overlay =
        BoundsDrawable.getInstance(targetView, density, margin, padding, contentBounds);

    targetView.getOverlay().add(overlay);

    if (isAlignmentMode) {
      int[] coords = new int[2];
      targetView.getLocationOnScreen(coords);
      Rect lineContentBounds =
          new Rect(
              coords[0] + contentBounds.left,
              coords[1] + contentBounds.top,
              coords[0] + contentBounds.right,
              coords[1] + contentBounds.bottom);

      final Drawable lineOverlay =
          LinesDrawable.getInstance(targetView, density, margin, padding, lineContentBounds);

      targetView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

      targetView.getRootView().getOverlay().add(lineOverlay);
    }
  }

  public static void removeHighlight(View targetView) {
    if (!VIEW_OVERLAY_SUPPORT) {
      return;
    }

    final float density = targetView.getContext().getResources().getDisplayMetrics().density;
    final Drawable overlay = BoundsDrawable.getInstance(targetView, density);
    final Drawable overlay2 = LinesDrawable.getInstance(targetView, density);
    targetView.getRootView().getOverlay().remove(overlay2);

    targetView.getOverlay().remove(overlay);
  }

  private static Rect enclose(Rect parent, Rect child) {
    return new Rect(
        child.left - parent.left,
        child.top - parent.top,
        child.right + parent.right,
        child.bottom + parent.bottom);
  }
}


text:
class Spacewar : public Game
{
private:
    // game items
    TextureManager backgroundTexture;	// nebula texture
	TextureManager shipTextures;
	TextureManager asteroidTextures;
	TextureManager gunTexture;
	TextureManager bulletTexture;
	TextureManager enemyBulletTexture;
	TextureManager powerTexture;

	Ship    ship;           		// spaceship
	Image	background;					// backdrop image
	Bullet  bullets[MAX_BULLETS];	// array of bullets
	EnemyBullet enemyBullets[MAX_ENEMY_BULLETS];
	Asteroid asteroids[MAX_ASTEROIDS];	// array of bullets
	Gun		guns[MAX_GUNS];
	Power	power;

	// text fonts
	TextDX *dxFontGameOver;
	TextDX *dxFontScore;

	int asteroidCounter;
	int asterGroupSize;
	float asteroidSpawnTime;

	// flags
	bool shoot;
	float shootTime;
	bool gameOver;
	int score;
	bool powerupActive;
	float powerupTime;
	float timeSincePowerupSpawn;

public:
    // Constructor
    Spacewar();

    // Destructor
    virtual ~Spacewar();

    // Initialize the game
    void initialize(HWND hwnd);
    void update();      // must override pure virtual from Game
    void ai();          // "
    void collisions();  // "
    void render();      // "

	void spawnBullet(VECTOR2 pos, VECTOR2 vel);
	void spawnEnemyBullet(VECTOR2 pos, VECTOR2 vel);
	void spawnAsteroid(VECTOR2 pos, VECTOR2 vel);
	void spawnPowerup(VECTOR2 pos, VECTOR2 vel);

	void releaseAll();
    void resetAll();
};

#endif

redpajama_set_name: RedPajamaGithub


text:
package liquibase.exception;

public class LiquibaseParseException extends LiquibaseException {

    public LiquibaseParseException() {
    }

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

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

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


text:
layout: post
unique_id: exploring_philly
title: Exploring Philly
categories: []
locations:
---

YESTERDAY:
* landed safely in Philly
* took a Lyft to apartment
* got keys
  * apartment is pretty well furnished!
  * just missing a plunger and a desk chair
* early morning target run
* took a nap from 10 am to noon
* worked until 6 pm
  * wifi wasn't set up
  * went to "business/conference area"
  * wifi there was crap
  * used up most of my high speed 2 gb hotspot
* took a break for lunch at a ramen place across the street
  * reasonable prices for bay area ...
  * super expensive for philly
  * tasty chicken katsu though!
* went for a walk to U of Penn with Jackie in the evening
  * sat on a bench while she figured out on-campus wifi connection
  * got bit by an ... ant?
  * bug bite spread pretty large
  * picked up a corticol steroid from CVS
* checked out the gym at U of Penn
  * nice climbing wall
  * decent ping-pong table too
* dropped by trader joe's on the way back
  * realized we didn't have any utensils
* turkey hoagie for dinner (with more fries)
* went to gym after a quick nap to work it off
* gym isn't bad
  * only two pieces of equipment had slight safety issues

TODAY:
* technician from Verizon came to install internet!
* shrimp bowl from Trader Joe's for lunch
  * also an egg!
  * Jackie cooked it with a plastic knife
* met up with Jackie's friend
* headed to Nan Zhou hand-pulled noodle restaurant
  * pretty decent lai mein!
  * only slightly sketchy walking there

LEARNINGS:
* get the internets asap!


text:
	<title>Mary Kenny's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Mary Kenny's panel show appearances

Mary Kenny (born 1944-04-04[ref]) has appeared in 6 episodes between 1969-1990.  Mary Kenny on Wikipedia.

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1990-03-08 / Question Time

1987-10-29 / Question Time

1983-03-24 / Question Time

1980-03-06 / Question Time

1969-02-18 / Petticoat Line

1969-01-21 / Petticoat Line


text:
// Copyright 2015 Ivan Popivanov
//
// 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 net.tradelib.ratio;

import java.util.List;

import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

public class SortinoRatio {
   /**
    * @brief Computes the Sortino ratio for a list of returns.
    *
    * @param returns The returns
    * @param rf The risk free average return
    * @param multiplier Mainly used to compute the Sortino ratio
    *                   for the opposite returns, i.e. short strategy.
    *
    * @return The Sortino ratio. Double.MAX_VALUE is returned if there
    *         are no negative returns after applying the multiplier (i.e.
    *         the divisor is 0).
    */
   public static double value(List<Double> returns, double rf, double multiplier) {
      SummaryStatistics fullStats = new SummaryStatistics();
      SummaryStatistics downStats = new SummaryStatistics();
      for(int ii = 0; ii < returns.size(); ++ii) {
         double dd = (returns.get(ii) - rf) * multiplier;
         fullStats.addValue(dd);
         if(dd < rf) downStats.addValue(dd);
         else downStats.addValue(0);
      }

      if(downStats.getN() == 0) return Double.MAX_VALUE;

      return fullStats.getMean() / downStats.getStandardDeviation();
   }

   public static double value(List<Double> returns) {
      return value(returns, 0, 1);
   }

   public static double value(List<Double> returns, double rf) {
      return value(returns, rf, 1);
   }

   /**
    * @brief Computes the Sortino ratio for the short strategy.
    *
    * @param returns The returns
    *
    * @return The Sortino ratio. Double.MAX_VALUE is returned if there
    *         are no negative returns after applying the multiplier (i.e.
    *         the divisor is 0).
    */
   public static double reverseValue(List<Double> returns) {
      return value(returns, 0, -1);
   }

   /**
    * @brief Computes the Sortino ratio for the short strategy.
    *
    * @param returns The returns
    * @param rf The risk free average return
    *
    * @return The Sortino ratio. Double.MAX_VALUE is returned if there
    *         are no negative returns after applying the multiplier (i.e.
    *         the divisor is 0).
    */
   public static double reverseValue(List<Double> returns, double rf) {
      return value(returns, rf, -1);
   }
}


text:
QUnit CLIB helps extend QUnit's CLI support to many common CLI environments.

## Screenshot

![QUnit CLIB brings QUnit to your favorite shell.](http://i.imgur.com/jpu9l.png)

## Support

QUnit CLIB has been tested in at least Node.js 0.4.8-0.8.20, Narwhal 0.3.2, PhantomJS 1.8.1, RingoJS 0.9, and Rhino 1.7RC5.

## Usage

```js
;(function(window) {
  'use strict';

  // use a single "load" function
  var load = typeof require == 'function' ? require : window.load;

  // load QUnit and CLIB if needed
  var QUnit = (function() {
    var noop = Function.prototype;
    return  window.QUnit || (
      window.addEventListener || (window.addEventListener = noop),
      window.setTimeout || (window.setTimeout = noop),
      window.QUnit = load('../vendor/qunit/qunit/qunit.js') || window.QUnit,
      (load('../vendor/qunit-clib/qunit-clib.js') || { 'runInContext': noop }).runInContext(window),
      addEventListener === noop && delete window.addEventListener,
      window.QUnit
    );
  }());

  // explicitly call `QUnit.module()` instead of `module()`
  // in case we are in a CLI environment
  QUnit.module('A Test Module');

  test('A Test', function() {
    // ...
  });

  // call `QUnit.start()` for Narwhal, Node.js, PhantomJS, Rhino, and RingoJS
  if (!window.document || window.phantom) {
    QUnit.start();
  }
}(typeof global == 'object' && global || this));
```

## Footnotes

  1. QUnit v1.3.0 does not work with Narwhal or Ringo < v0.8.0
  2. Rhino v1.7RC4 does not support timeout fallbacks `clearTimeout` and `setTimeout`

## Author

* [John-David Dalton](http://allyoucanleet.com/)
  [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter")


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;

namespace Azure.Monitor.OpenTelemetry.Exporter.Internals
{
    internal readonly struct AzMonList : IEnumerable
    {
        private static int s_allocationSize = 8;

        private readonly KeyValuePair<string, object>[] data;

        private AzMonList(KeyValuePair<string, object>[] data, int length)
        {
            this.data = data;
            this.Length = length;
        }

        public int Length { get; }

        public ref KeyValuePair<string, object> this[int index]
        {
            get => ref this.data[index];
        }

        public static AzMonList Initialize()
        {
            return new AzMonList(ArrayPool<KeyValuePair<string, object>>.Shared.Rent(s_allocationSize), 0);
        }

        public static void Add(ref AzMonList list, KeyValuePair<string, object> keyValuePair)
        {
            var data = list.data;

            if (data == null)
            {
                throw new InvalidOperationException("AzMonList instance is not initialized.");
            }

            if (list.Length >= data.Length)
            {
                s_allocationSize = data.Length * 2;
                var previousData = data;

                data = ArrayPool<KeyValuePair<string, object>>.Shared.Rent(s_allocationSize);

                var span = previousData.AsSpan();
                span.CopyTo(data);
                ArrayPool<KeyValuePair<string, object>>.Shared.Return(previousData);
            }

            data[list.Length] = keyValuePair;
            list = new AzMonList(data, list.Length + 1);
        }

        public static void Clear(ref AzMonList list)
        {
            list = new AzMonList(list.data, 0);
        }

        public static object GetTagValue(ref AzMonList list, string tagName)
        {
            int length = list.Length;

            for (int i = 0; i < length; i++)
            {
                if (ReferenceEquals(list[i].Key, tagName))
                {
                    return list[i].Value;
                }
            }

            return null;
        }

        internal static object[] GetTagValues(ref AzMonList list, params string[] tagNames)
        {
            int lengthTagNames = tagNames.Length;
            int lengthList = list.Length;
            object[] values = new object[lengthTagNames];

            for (int i = 0; i < lengthList; i++)
            {
                var index = Array.IndexOf(tagNames, list[i].Key);
                if (index >= 0)
                {
                    values[index] = list[i].Value;
                    lengthTagNames--;

                    if (lengthTagNames == 0)
                    {
                        break;
                    }
                }
            }

            return values;
        }

        public void Return()
        {
            var data = this.data;
            if (data != null)
            {
                ArrayPool<KeyValuePair<string, object>>.Shared.Return(data);
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new Enumerator(in this);
        }

        public struct Enumerator : IEnumerator
        {
            private readonly KeyValuePair<string, object>[] data;
            private readonly int length;
            private int index;
            private KeyValuePair<string, object> current;

            public Enumerator(in AzMonList list)
            {
                this.data = list.data;
                this.length = list.Length;
                this.index = 0;
                this.current = default;
            }

            public object Current { get => this.current; }

            public bool MoveNext()
            {
                if (this.index < this.length)
                {
                    this.current = this.data[this.index++];
                    return true;
                }

                this.index = this.length + 1;
                this.current = default;
                return false;
            }

            void IEnumerator.Reset()
            {
                this.index = 0;
                this.current = default;
            }
        }
    }
}


text:
require 'spec_helper'

describe DebitNote do
  include SupportingSpecHelpers

  before :all do
    @debit_note = eval_support_script("serialization/debit_note_sample")
    @xml = Nokogiri::XML(@debit_note.to_xml)
  end

  it "should include the discrepancy response data" do
    expect(@xml.xpath("//cac:DiscrepancyResponse/cbc:ReferenceID").text).to eq @debit_note.discrepancy_response.reference_id
    expect(@xml.xpath("//cac:DiscrepancyResponse/cbc:ResponseCode").text).to eq @debit_note.discrepancy_response.response_code
    expect(@xml.xpath("//cac:DiscrepancyResponse/cbc:Description").text).to eq @debit_note.discrepancy_response.description
  end

  it "should include the billing reference data" do
    expect(@xml.xpath("//cac:BillingReference/cac:InvoiceDocumentReference/cbc:ID").text).to eq @debit_note.billing_reference.invoice_document_reference.id
    expect(@xml.xpath("//cac:BillingReference/cac:InvoiceDocumentReference/cbc:DocumentTypeCode").text).to eq @debit_note.billing_reference.invoice_document_reference.document_type_code
  end

  it "should include the debit note lines data" do
    expect(@xml.xpath("//cac:DebitNoteLine/cbc:ID").text).to eq @debit_note.lines.first.id
  end
end


text:
require 'spec_helper'

RSpec.describe Gitlab::Ci::Build::Artifacts::Path do
  describe '#valid?' do
    context 'when path contains a zero character' do
      it 'is not valid' do
        expect(described_class.new("something/\255")).not_to be_valid
      end
    end

    context 'when path is not utf8 string' do
      it 'is not valid' do
        expect(described_class.new("something/\0")).not_to be_valid
      end
    end

    context 'when path is valid' do
      it 'is valid' do
        expect(described_class.new("some/file/path")).to be_valid
      end
    end
  end

  describe '#directory?' do
    context 'when path ends with a directory indicator' do
      it 'is a directory' do
        expect(described_class.new("some/file/dir/")).to be_directory
      end
    end

    context 'when path does not end with a directory indicator' do
      it 'is not a directory' do
        expect(described_class.new("some/file")).not_to be_directory
      end
    end
  end

  describe '#name' do
    it 'returns a base name' do
      expect(described_class.new("some/file").name).to eq 'file'
    end
  end

  describe '#nodes' do
    it 'returns number of path nodes' do
      expect(described_class.new("some/dir/file").nodes).to eq 2
    end
  end

  describe '#to_s' do
    context 'when path is valid' do
      it 'returns a string representation of a path' do
        expect(described_class.new('some/path').to_s).to eq 'some/path'
      end
    end

    context 'when path is invalid' do
      it 'raises an error' do
        expect { described_class.new("invalid/\0").to_s }
          .to raise_error ArgumentError
      end
    end
  end
end


text:
  TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"), name, \
               arg1_name, arg1_val, arg2_name, arg2_val);
#endif

namespace cc {

// (Pure) Interface for observing BeginFrame messages from BeginFrameSource
// objects.
class CC_EXPORT BeginFrameObserver {
 public:
  virtual ~BeginFrameObserver() {}

  // The |args| given to OnBeginFrame is guaranteed to have
  // |args|.IsValid()==true and have |args|.frame_time
  // field be strictly greater than the previous call.
  //
  // Side effects: This function can (and most of the time *will*) change the
  // return value of the LastUsedBeginFrameArgs method. See the documentation
  // on that method for more information.
  virtual void OnBeginFrame(const BeginFrameArgs& args) = 0;

  // Returns the last BeginFrameArgs used by the observer. This method's return
  // value is affected by the OnBeginFrame method!
  //
  //  - Before the first call of OnBeginFrame, this method should return a
  //    BeginFrameArgs on which IsValid() returns false.
  //
  //  - If the |args| passed to OnBeginFrame is (or *will be*) used, then
  //    LastUsedBeginFrameArgs return value should become the |args| given to
  //    OnBeginFrame.
  //
  //  - If the |args| passed to OnBeginFrame is dropped, then
  //    LastUsedBeginFrameArgs return value should *not* change.
  //
  // These requirements are designed to allow chaining and nesting of
  // BeginFrameObservers which filter the incoming BeginFrame messages while
  // preventing "double dropping" and other bad side effects.
  virtual const BeginFrameArgs LastUsedBeginFrameArgs() const = 0;

  virtual void OnBeginFrameSourcePausedChanged(bool paused) = 0;

  // Tracing support
  virtual void AsValueInto(base::trace_event::TracedValue* dict) const = 0;
};

// Simple base class which implements a BeginFrameObserver which checks the
// incoming values meet the BeginFrameObserver requirements and implements the
// required LastUsedBeginFrameArgs behaviour.
//
// Users of this class should;
//  - Implement the OnBeginFrameDerivedImpl function.
//  - Recommended (but not required) to call
//    BeginFrameObserverBase::OnValueInto in their overridden OnValueInto
//    function.
class CC_EXPORT BeginFrameObserverBase : public BeginFrameObserver {
 public:
  BeginFrameObserverBase();

  // BeginFrameObserver

  // Traces |args| and DCHECK |args| satisfies pre-conditions then calls
  // OnBeginFrameDerivedImpl and updates the last_begin_frame_args_ value on
  // true.
  void OnBeginFrame(const BeginFrameArgs& args) override;
  const BeginFrameArgs LastUsedBeginFrameArgs() const override;

  // Outputs last_begin_frame_args_
  void AsValueInto(base::trace_event::TracedValue* dict) const override;

 protected:
  // Subclasses should override this method!
  // Return true if the given argument is (or will be) used.
  virtual bool OnBeginFrameDerivedImpl(const BeginFrameArgs& args) = 0;

  BeginFrameArgs last_begin_frame_args_;
  int64_t dropped_begin_frame_args_;

 private:
  DISALLOW_COPY_AND_ASSIGN(BeginFrameObserverBase);
};

// Interface for a class which produces BeginFrame calls to a
// BeginFrameObserver.
//
// BeginFrame calls *normally* occur just after a vsync interrupt when input
// processing has been finished and provide information about the time values
// of the vsync times. *However*, these values can be heavily modified or even
// plain made up (when no vsync signal is available or vsync throttling is
// turned off). See the BeginFrameObserver for information about the guarantees
// all BeginFrameSources *must* provide.
class CC_EXPORT BeginFrameSource {
 public:
  virtual ~BeginFrameSource() {}

  // SetNeedsBeginFrames is the on/off "switch" for the BeginFrameSource. When
  // set to false no more BeginFrame messages should be sent to observer.
  virtual bool NeedsBeginFrames() const = 0;
  virtual void SetNeedsBeginFrames(bool needs_begin_frames) = 0;

  // DidFinishFrame provides back pressure to a frame source about frame
  // processing (rather than toggling SetNeedsBeginFrames every frame). It is
  // used by systems like the BackToBackFrameSource to make sure only one frame
  // is pending at a time.
  virtual void DidFinishFrame(size_t remaining_frames) = 0;

  // Add/Remove an observer from the source.
  // *At the moment* only a single observer can be added to the source, however
  // in the future this may be extended to allow multiple observers.
  // If making this change, please use base::ObserverList to do so.
  virtual void AddObserver(BeginFrameObserver* obs) = 0;
  virtual void RemoveObserver(BeginFrameObserver* obs) = 0;

  // Tells the Source that client is ready to handle BeginFrames messages.
  virtual void SetClientReady() = 0;

  // Tracing support - Recommend (but not required) to call this implementation
  // in any override.
  virtual void AsValueInto(base::trace_event::TracedValue* dict) const = 0;
};

// Simple base class which implements a BeginFrameSource.
// Implementation classes should:
//  - Implement the pure virtual (Set)NeedsBeginFrames methods from
//    BeginFrameSource.
//  - Use the CallOnBeginFrame method to call to the observer(s).
//  - Recommended (but not required) to call BeginFrameSourceBase::AsValueInto
//    in their own AsValueInto implementation.
class CC_EXPORT BeginFrameSourceBase : public BeginFrameSource {
 public:
  ~BeginFrameSourceBase() override {}

  // BeginFrameSource
  bool NeedsBeginFrames() const final;
  void SetNeedsBeginFrames(bool needs_begin_frames) final;
  void DidFinishFrame(size_t remaining_frames) override {}
  void AddObserver(BeginFrameObserver* obs) final;
  void RemoveObserver(BeginFrameObserver* obs) final;
  void SetClientReady() override {}

  // Tracing support - Recommend (but not required) to call this implementation
  // in any override.
  void AsValueInto(base::trace_event::TracedValue* dict) const override;

 protected:
  BeginFrameSourceBase();

  // These methods should be used by subclasses to make the call to the
  // observers.
  void CallOnBeginFrame(const BeginFrameArgs& args);
  void SetBeginFrameSourcePaused(bool paused);

  // This method should be overridden if you want to change some behaviour on
  // needs_begin_frames change.
  virtual void OnNeedsBeginFramesChange(bool needs_begin_frames) {}

  BeginFrameObserver* observer_;
  bool needs_begin_frames_;
  bool paused_;

 private:
  bool inside_as_value_into_;

  DISALLOW_COPY_AND_ASSIGN(BeginFrameSourceBase);
};

// A frame source which calls BeginFrame (at the next possible time) as soon as
// remaining frames reaches zero.
class CC_EXPORT BackToBackBeginFrameSource : public BeginFrameSourceBase {
 public:
  static scoped_ptr<BackToBackBeginFrameSource> Create(
      base::SingleThreadTaskRunner* task_runner);
  ~BackToBackBeginFrameSource() override;

  // BeginFrameSource
  void DidFinishFrame(size_t remaining_frames) override;

  // Tracing
  void AsValueInto(base::trace_event::TracedValue* dict) const override;

 protected:
  explicit BackToBackBeginFrameSource(
      base::SingleThreadTaskRunner* task_runner);
  virtual base::TimeTicks Now();  // Now overridable for testing

  base::SingleThreadTaskRunner* task_runner_;

  bool send_begin_frame_posted_;

  // BeginFrameSourceBase
  void OnNeedsBeginFramesChange(bool needs_begin_frames) override;

  void BeginFrame();

 private:
  base::WeakPtrFactory<BackToBackBeginFrameSource> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(BackToBackBeginFrameSource);
};

// A frame source which is locked to an external parameters provides from a
// vsync source and generates BeginFrameArgs for it.
class CC_EXPORT SyntheticBeginFrameSource : public BeginFrameSourceBase,
                                            public DelayBasedTimeSourceClient {
 public:
  static scoped_ptr<SyntheticBeginFrameSource> Create(
      base::SingleThreadTaskRunner* task_runner,
      base::TimeDelta initial_vsync_interval);
  ~SyntheticBeginFrameSource() override;

  void OnUpdateVSyncParameters(base::TimeTicks new_vsync_timebase,
                               base::TimeDelta new_vsync_interval);

  // Tracing
  void AsValueInto(base::trace_event::TracedValue* dict) const override;

  // DelayBasedTimeSourceClient
  void OnTimerTick() override;

 protected:
  explicit SyntheticBeginFrameSource(
      scoped_ptr<DelayBasedTimeSource> time_source);

  BeginFrameArgs CreateBeginFrameArgs(base::TimeTicks frame_time,
                                      BeginFrameArgs::BeginFrameArgsType type);

  // BeginFrameSourceBase
  void OnNeedsBeginFramesChange(bool needs_begin_frames) override;

  scoped_ptr<DelayBasedTimeSource> time_source_;

 private:
  DISALLOW_COPY_AND_ASSIGN(SyntheticBeginFrameSource);
};

// A "virtual" frame source which lets you switch between multiple other frame
// sources while making sure the BeginFrameArgs stays increasing (possibly
// enforcing minimum boundry between BeginFrameArgs messages).
class CC_EXPORT BeginFrameSourceMultiplexer : public BeginFrameSourceBase,
                                              public BeginFrameObserver {
 public:
  static scoped_ptr<BeginFrameSourceMultiplexer> Create();
  ~BeginFrameSourceMultiplexer() override;

  void SetMinimumInterval(base::TimeDelta new_minimum_interval);

  void AddSource(BeginFrameSource* new_source);
  void RemoveSource(BeginFrameSource* existing_source);
  void SetActiveSource(BeginFrameSource* new_source);
  const BeginFrameSource* ActiveSource();

  // BeginFrameObserver
  // The mux is an BeginFrameObserver as it needs to proxy the OnBeginFrame
  // calls to preserve the monotonicity of the BeginFrameArgs when switching
  // sources.
  void OnBeginFrame(const BeginFrameArgs& args) override;
  const BeginFrameArgs LastUsedBeginFrameArgs() const override;
  void OnBeginFrameSourcePausedChanged(bool paused) override;

  // BeginFrameSource
  void DidFinishFrame(size_t remaining_frames) override;

  // BeginFrameSourceBase
  void OnNeedsBeginFramesChange(bool needs_begin_frames) override;

  // Tracing
  void AsValueInto(base::trace_event::TracedValue* dict) const override;

 protected:
  BeginFrameSourceMultiplexer();
  explicit BeginFrameSourceMultiplexer(base::TimeDelta minimum_interval);

  bool HasSource(BeginFrameSource* source);
  bool IsIncreasing(const BeginFrameArgs& args);

  base::TimeDelta minimum_interval_;

  BeginFrameSource* active_source_;
  std::set<BeginFrameSource*> source_list_;

 private:
  DISALLOW_COPY_AND_ASSIGN(BeginFrameSourceMultiplexer);
};

}  // namespace cc

#endif  // CC_SCHEDULER_BEGIN_FRAME_SOURCE_H_


text:
"""
Beacon to emit adb device state changes for Android devices

.. versionadded:: 2016.3.0
"""
import logging

import salt.utils.beacons
import salt.utils.path

log = logging.getLogger(__name__)

__virtualname__ = "adb"

last_state = {}
last_state_extra = {"value": False, "no_devices": False}

def __virtual__():
    which_result = salt.utils.path.which("adb")
    if which_result is None:
        err_msg = "adb is missing."
        log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
        return False, err_msg
    else:
        return __virtualname__

def validate(config):
    """
    Validate the beacon configuration
    """
    # Configuration for adb beacon should be a dictionary with states array
    if not isinstance(config, list):
        log.info("Configuration for adb beacon must be a list.")
        return False, "Configuration for adb beacon must be a list."

    config = salt.utils.beacons.list_to_dict(config)

    if "states" not in config:
        log.info("Configuration for adb beacon must include a states array.")
        return False, "Configuration for adb beacon must include a states array."
    else:
        if not isinstance(config["states"], list):
            log.info("Configuration for adb beacon must include a states array.")
            return False, "Configuration for adb beacon must include a states array."
        else:
            states = [
                "offline",
                "bootloader",
                "device",
                "host",
                "recovery",
                "no permissions",
                "sideload",
                "unauthorized",
                "unknown",
                "missing",
            ]
            if any(s not in states for s in config["states"]):
                log.info(
                    "Need a one of the following adb states: %s", ", ".join(states)
                )
                return (
                    False,
                    "Need a one of the following adb states: {}".format(
                        ", ".join(states)
                    ),
                )
    return True, "Valid beacon configuration"

def beacon(config):
    """
    Emit the status of all devices returned by adb

    Specify the device states that should emit an event,
    there will be an event for each device with the
    event type and device specified.

    .. code-block:: yaml

        beacons:
          adb:
            - states:
                - offline
                - unauthorized
                - missing
            - no_devices_event: True
            - battery_low: 25

    """

    log.trace("adb beacon starting")
    ret = []

    config = salt.utils.beacons.list_to_dict(config)

    out = __salt__["cmd.run"]("adb devices", runas=config.get("user", None))

    lines = out.split("\n")[1:]
    last_state_devices = list(last_state.keys())
    found_devices = []

    for line in lines:
        try:
            device, state = line.split("\t")
            found_devices.append(device)
            if device not in last_state_devices or (
                "state" in last_state[device] and last_state[device]["state"] != state
            ):
                if state in config["states"]:
                    ret.append({"device": device, "state": state, "tag": state})
                    last_state[device] = {"state": state}

            if "battery_low" in config:
                val = last_state.get(device, {})
                cmd = "adb -s {} shell cat /sys/class/power_supply/*/capacity".format(
                    device
                )
                battery_levels = __salt__["cmd.run"](
                    cmd, runas=config.get("user", None)
                ).split("\n")

                for l in battery_levels:
                    battery_level = int(l)
                    if 0 < battery_level < 100:
                        if "battery" not in val or battery_level != val["battery"]:
                            if (
                                "battery" not in val
                                or val["battery"] > config["battery_low"]
                            ) and battery_level <= config["battery_low"]:
                                ret.append(
                                    {
                                        "device": device,
                                        "battery_level": battery_level,
                                        "tag": "battery_low",
                                    }
                                )

                        if device not in last_state:
                            last_state[device] = {}

                        last_state[device].update({"battery": battery_level})

        except ValueError:
            continue

    # Find missing devices and remove them / send an event
    for device in last_state_devices:
        if device not in found_devices:
            if "missing" in config["states"]:
                ret.append({"device": device, "state": "missing", "tag": "missing"})

            del last_state[device]

    # Maybe send an event if we don't have any devices
    if "no_devices_event" in config and config["no_devices_event"] is True:
        if not found_devices and not last_state_extra["no_devices"]:
            ret.append({"tag": "no_devices"})

    # Did we have no devices listed this time around?
    last_state_extra["no_devices"] = not found_devices

    return ret


text:
template <class T>
void test_is_trivially_default_constructible()
{
    static_assert( std::is_trivially_default_constructible<T>::value, "");
    static_assert( std::is_trivially_default_constructible<const T>::value, "");
    static_assert( std::is_trivially_default_constructible<volatile T>::value, "");
    static_assert( std::is_trivially_default_constructible<const volatile T>::value, "");
#if TEST_STD_VER > 14
    static_assert( std::is_trivially_default_constructible_v<T>, "");
    static_assert( std::is_trivially_default_constructible_v<const T>, "");
    static_assert( std::is_trivially_default_constructible_v<volatile T>, "");
    static_assert( std::is_trivially_default_constructible_v<const volatile T>, "");
#endif
}

template <class T>
void test_has_not_trivial_default_constructor()
{
    static_assert(!std::is_trivially_default_constructible<T>::value, "");
    static_assert(!std::is_trivially_default_constructible<const T>::value, "");
    static_assert(!std::is_trivially_default_constructible<volatile T>::value, "");
    static_assert(!std::is_trivially_default_constructible<const volatile T>::value, "");
#if TEST_STD_VER > 14
    static_assert(!std::is_trivially_default_constructible_v<T>, "");
    static_assert(!std::is_trivially_default_constructible_v<const T>, "");
    static_assert(!std::is_trivially_default_constructible_v<volatile T>, "");
    static_assert(!std::is_trivially_default_constructible_v<const volatile T>, "");
#endif
}

class Empty
{
};

class NotEmpty
{
    virtual ~NotEmpty();
};

union Union {};

struct bit_zero
{
    int :  0;
};

class Abstract
{
    virtual ~Abstract() = 0;
};

struct A
{
    A();
};

int main()
{
    test_has_not_trivial_default_constructor<void>();
    test_has_not_trivial_default_constructor<int&>();
    test_has_not_trivial_default_constructor<A>();
    test_has_not_trivial_default_constructor<Abstract>();
    test_has_not_trivial_default_constructor<NotEmpty>();

    test_is_trivially_default_constructible<Union>();
    test_is_trivially_default_constructible<Empty>();
    test_is_trivially_default_constructible<int>();
    test_is_trivially_default_constructible<double>();
    test_is_trivially_default_constructible<int*>();
    test_is_trivially_default_constructible<const int*>();
    test_is_trivially_default_constructible<char[3]>();
    test_is_trivially_default_constructible<bit_zero>();
}


text:
var Ext = require("Ext4").Ext;
var WNPRC = require("wnprc_ehr/WNPRC").WNPRC;
var moment = require("dbutils/lib/moment");

// noinspection JSUnresolvedVariable
exports.registerTriggers = function (EHR, registerGenericHandler, Events) {
    var registerHandler = function (event, callback) {
        registerGenericHandler(event, "study", "necropsy", callback);
    };

    registerHandler(Events.BEFORE_UPSERT, function (helper, scriptErrors, row) {
        var validator = WNPRC.Validator.new(EHR, row, scriptErrors);

        var pdRegex = /^pd/i;
        if (row.Id && pdRegex.test(row.Id) && !row.is_prenatal_necropsy) {
            EHR.Server.Utils.addError(scriptErrors, 'Id', "Animal ID looks like a prenatal death.  'Fetal Necropsy' should be checked?", "WARN");
        }

        if (row.is_prenatal_necropsy && !row.dam) {
            EHR.Server.Utils.addError(scriptErrors, 'dam', "Dam is required for pre-natal necropsies.  If dam is not known, you may enter a descriptive placeholder here, such as 'rUNKOWN' for an as of yet unspecified rhesus animal.", "ERROR");
        }

        if ('dam' in row && row.dam) {
            validator.checkAnimalInCol("dam", {
                exists: WNPRC.Validator.Severity.WARN,
                isAlive: WNPRC.Validator.Severity.WARN,
                isFemale: WNPRC.Validator.Severity.ERROR
            });
        }

        // Warn if the pathologist is not a pathologist and throw an error if they are not a user.
        if (Ext.isDefined(row.performedby)) {
            // Only check that the user exists for records after 2013, because there are some older records
            // that need to reference users that don't exist.
            if (row.date && moment(row.date.getTime()).isAfter(moment('2013-01-01'))) {
                validator.ensureUserExists("performedby", undefined, WNPRC.Validator.Severity.ERROR, true);
            }
            validator.ensureUserIsPathologist("performedby", undefined, WNPRC.Validator.Severity.WARN, true);
        }

        // For each assistant (comma-delimited), warn if they are not a pathlogist and throw an error
        // if they are not a user.
        if (row.assistant) {
            Ext.each(row.assistant.split(","), function (user) {
                // Only check that the user exists for records after 2013, because there are some older records
                // that need to reference users that don't exist.
                if (row.date && moment(row.date.getTime()).isAfter(moment('2013-01-01'))) {
                    validator.ensureUserExists("assistant", user, WNPRC.Validator.Severity.ERROR, true);
                }
                validator.ensureUserIsPathologist("assistant", user, WNPRC.Validator.Severity.WARN, true);
            });
        }

        // Enforce on the Server Side that requests should not be <10 days out.
        if (row.date && EHR.Server.Security.getQCStateByLabel(row.QCStateLabel).isRequest) {
            var requestedTime = moment(row.date.getTime());
            var today = moment();

            if (requestedTime.isBefore(today.add(10, 'days'), 'day')) {
                EHR.Server.Utils.addError(scriptErrors, "date", "Please contact pathology directly if you need to schedule a necropsy in less than 10 days", 'ERROR');
            }
        }
    });

};


text:
Deprecated as this is now natively available in all modern browsers and Node.js versions.

---

# math-sinh

> ES2015 [`Math.sinh()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sinh) [ponyfill](https://ponyfill.com)

## Install

```
$ npm install --save math-sinh
```

## Usage

```js
var mathSinh = require('math-sinh');

mathSinh(1);
//=> 1.1752011936438014
```

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)


text:
package org.jboss.hal.client.configuration.subsystem.mail;

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

import javax.inject.Inject;

import org.jboss.hal.core.finder.ColumnActionFactory;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderColumn;
import org.jboss.hal.core.finder.ItemAction;
import org.jboss.hal.core.finder.ItemActionFactory;
import org.jboss.hal.core.finder.ItemDisplay;
import org.jboss.hal.core.mbui.dialog.AddResourceDialog;
import org.jboss.hal.core.mvp.Places;
import org.jboss.hal.dmr.Operation;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.dmr.dispatch.Dispatcher;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.MetadataRegistry;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.token.NameTokens;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.AsyncColumn;
import org.jboss.hal.spi.Message;
import org.jboss.hal.spi.MessageEvent;
import org.jboss.hal.spi.Requires;

import com.google.common.base.Joiner;
import com.google.web.bindery.event.shared.EventBus;

import elemental2.dom.HTMLElement;
import elemental2.promise.Promise;

import static java.util.stream.Collectors.toList;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_ADDRESS;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_SESSION_ADDRESS;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_SESSION_TEMPLATE;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_TEMPLATE;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.SERVER_ADDRESS;
import static org.jboss.hal.dmr.ModelDescriptionConstants.ADD;
import static org.jboss.hal.dmr.ModelDescriptionConstants.FROM;
import static org.jboss.hal.dmr.ModelDescriptionConstants.JNDI_NAME;
import static org.jboss.hal.dmr.ModelDescriptionConstants.MAIL_SESSION;
import static org.jboss.hal.dmr.ModelDescriptionConstants.NAME;
import static org.jboss.hal.dmr.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.hal.dmr.ModelDescriptionConstants.RECURSIVE;

@AsyncColumn(Ids.MAIL_SESSION)
@Requires({ MAIL_ADDRESS, MAIL_SESSION_ADDRESS, SERVER_ADDRESS })
public class MailSessionColumn extends FinderColumn<MailSession> {

    @Inject
    protected MailSessionColumn(Finder finder,
            ColumnActionFactory columnActionFactory,
            ItemActionFactory itemActionFactory,
            EventBus eventBus,
            Dispatcher dispatcher,
            StatementContext statementContext,
            MetadataRegistry metadataRegistry,
            Places places,
            Resources resources) {

        super(new Builder<MailSession>(finder, Ids.MAIL_SESSION, Names.MAIL_SESSION)
                .withFilter()
                .filterDescription(resources.messages().mailColumnFilterDescription())
                .useFirstActionAsBreadcrumbHandler());

        setItemsProvider(context -> {
            ResourceAddress mailAddress = MAIL_TEMPLATE.resolve(statementContext);
            Operation op = new Operation.Builder(mailAddress, READ_RESOURCE_OPERATION)
                    .param(RECURSIVE, true).build();

            return dispatcher.execute(op)
                    .then(result -> Promise.resolve(result.get(MAIL_SESSION).asPropertyList().stream()
                            .map(MailSession::new).collect(toList())));
        });

        addColumnAction(columnActionFactory.add(Ids.MAIL_SESSION_ADD, Names.MAIL_SESSION, MAIL_SESSION_TEMPLATE,
                column -> {
                    Metadata metadata = metadataRegistry.lookup(AddressTemplates.MAIL_SESSION_TEMPLATE);
                    AddResourceDialog dialog = new AddResourceDialog(Ids.MAIL_SESSION_DIALOG,
                            resources.messages().addResourceTitle(Names.MAIL_SESSION), metadata,
                            Arrays.asList(JNDI_NAME, FROM, "debug"), // NON-NLS
                            (name, modelNode) -> {
                                if (modelNode != null) {
                                    ResourceAddress address = AddressTemplates.MAIL_SESSION_TEMPLATE
                                            .resolve(statementContext, name);
                                    Operation operation = new Operation.Builder(address, ADD)
                                            .param(MAIL_SESSION, name)
                                            .payload(modelNode)
                                            .build();
                                    dispatcher.execute(operation, result -> {
                                        MessageEvent.fire(eventBus,
                                                Message.success(resources.messages()
                                                        .addResourceSuccess(Names.MAIL_SESSION, name)));
                                        column.refresh(Ids.mailSession(name));
                                    });
                                }
                            });
                    dialog.getForm().<String> getFormItem(NAME).addValidationHandler(createUniqueValidation());
                    dialog.show();
                }));
        addColumnAction(columnActionFactory.refresh(Ids.MAIL_SESSION_REFRESH));

        setItemRenderer(mailSession -> new ItemDisplay<MailSession>() {
            @Override
            public String getId() {
                return Ids.mailSession(mailSession.getName());
            }

            @Override
            public String getTitle() {
                return mailSession.getName();
            }

            @Override
            public HTMLElement element() {
                if (!mailSession.getServers().isEmpty()) {
                    return ItemDisplay
                            .withSubtitle(mailSession.getName(), Joiner.on(", ").join(mailSession.getServers()));
                }
                return null;
            }

            @Override
            public String getFilterData() {
                List<String> data = new ArrayList<>();
                data.add(mailSession.getName());
                data.addAll(mailSession.getServers());
                return String.join(" ", data);
            }

            @Override
            public List<ItemAction<MailSession>> actions() {
                List<ItemAction<MailSession>> actions = new ArrayList<>();
                actions.add(itemActionFactory.view(places.selectedProfile(NameTokens.MAIL_SESSION)
                        .with(NAME, mailSession.getName()).build()));
                actions.add(itemActionFactory.remove(Names.MAIL_SESSION, mailSession.getName(),
                        AddressTemplates.MAIL_SESSION_TEMPLATE, MailSessionColumn.this));
                return actions;
            }
        });

        setPreviewCallback(mailSession -> new MailSessionPreview(mailSession, resources));
    }
}


text:
namespace llvm {

class AnalysisUsage;
class BasicBlock;
class Constant;
class Function;
class Instruction;
class Module;
class Value;

/// ForwardControlFlowIntegrity uses the information from JumpInstrTableInfo to
/// prepend checks to indirect calls to make sure that these calls target valid
/// locations.
class ForwardControlFlowIntegrity : public ModulePass {
public:
  static char ID;

  ForwardControlFlowIntegrity();
  ForwardControlFlowIntegrity(JumpTable::JumpTableType JTT,
                              CFIntegrity CFIType,
                              bool CFIEnforcing, std::string CFIFuncName);
  ~ForwardControlFlowIntegrity() override;

  /// Runs the CFI pass on a given module. This works best if the module in
  /// question is the result of link-time optimization (see lib/LTO).
  bool runOnModule(Module &M) override;
  const char *getPassName() const override {
    return "Forward Control-Flow Integrity";
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override;

private:
  typedef SmallVector<Instruction *, 64> CallSet;

  /// A structure that is used to keep track of constant table information.
  struct CFIConstants {
    Constant *StartValue;
    Constant *MaskValue;
    Constant *Size;
  };

  /// A map from function type to the base of the table for this type and a mask
  /// for the table
  typedef DenseMap<FunctionType *, CFIConstants> CFITables;

  CallSet IndirectCalls;

  /// The type of jumptable implementation.
  JumpTable::JumpTableType JTType;

  /// The type of CFI check to add before each indirect call.
  CFIntegrity CFIType;

  /// A value that controls whether or not CFI violations cause a halt.
  bool CFIEnforcing;

  /// The name of the function to call in case of a CFI violation when
  /// CFIEnforcing is false. There is a default function that ignores
  /// violations.
  std::string CFIFuncName;

  /// The alignment of each entry in the table, from JumpInstrTableInfo. The
  /// JumpInstrTableInfo class always makes this a power of two.
  uint64_t ByteAlignment;

  /// The base-2 logarithm of ByteAlignment, needed for some of the transforms
  /// (like CFIntegrity::Ror)
  unsigned LogByteAlignment;

  /// Adds checks to each indirect call site to make sure that it is calling a
  /// function in our jump table.
  void updateIndirectCalls(Module &M, CFITables &CFIT);

  /// Walks the instructions to find all the indirect calls.
  void getIndirectCalls(Module &M);

  /// Adds a function that handles violations in non-enforcing mode
  /// (!CFIEnforcing). The default warning function simply returns, since the
  /// exact details of how to handle CFI violations depend on the application.
  void addWarningFunction(Module &M);

  /// Rewrites a function pointer in a call/invoke instruction to force it into
  /// a table.
  void rewriteFunctionPointer(Module &M, Instruction *I, Value *FunPtr,
                              Constant *JumpTableStart, Constant *JumpTableMask,
                              Constant *JumpTableSize);

  /// Inserts a check and a call to a warning function at a given instruction
  /// that must be an indirect call.
  void insertWarning(Module &M, BasicBlock *Block, Instruction *I,
                     Value *FunPtr);
};

ModulePass *
createForwardControlFlowIntegrityPass(JumpTable::JumpTableType JTT,
                                      CFIntegrity CFIType,
                                      bool CFIEnforcing, StringRef CFIFuncName);
}

#endif // LLVM_CODEGEN_FORWARDCONTROLFLOWINTEGRITY_H


text:
Отзывы

    <?php foreach( $items as $item_num => $item ) : ?>

<?php echo $item['text']; ?>

            <?php echo $item['author']; ?> <?php echo $item['date']; ?>

    <?php endforeach; ?>


text:
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
/**
 * 外部数据源缓存
 */
function dbsource_cache() {
	$db = pc_base::load_model('dbsource_model');
	$list = $db->select();
	$data = array();
	if ($list) {
		foreach ($list as $val) {
			$data[$val['name']] = array('hostname'=>$val['host'].':'.$val['port'], 'database' =>$val['dbname'] , 'db_tablepre'=>$val['dbtablepre'], 'username' =>$val['username'],'password' => $val['password'],'charset'=>$val['charset'],'debug'=>0,'pconnect'=>0,'autoconnect'=>0);
		}
	} else {
		return false;
	}
	return setcache('dbsource', $data, 'commons');
}

/**
 * 获取模型PC标签配置相信
 * @param $module 模型名
 */
function pc_tag_class ($module) {
	$filepath = PC_PATH.'modules'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.$module.'_tag.class.php';
	if (file_exists($filepath)) {
		$pc_tag = pc_base::load_app_class($module.'_tag', $module);
		if (!method_exists($pc_tag, 'pc_tag')) {
			showmessage(L('the_module_will_not_support_the_operation'));
		}
		$html  = $pc_tag->pc_tag();
	} else {
		showmessage(L('the_module_will_not_support_the_operation'), HTTP_REFERER);
	}
	return $html;
}

/**
 * 返回模板地址。
 * @param $id 数据源调用ID
 */
function template_url($id) {
	$filepath = CACHE_PATH.'caches_template'.DIRECTORY_SEPARATOR.'dbsource'.DIRECTORY_SEPARATOR.$id.'.php';
	if (!file_exists($filepath)) {
		$datacall = pc_base::load_model('datacall_model');
		$str = $datacall->get_one(array('id'=>$id), 'template');
		$dir = dirname($filepath);
		if(!is_dir($dir)) {
			mkdir($dir, 0777, true);
	    }
	    $tpl = pc_base::load_sys_class('template_cache');
		$str = $tpl->template_parse($str['template']);
		@file_put_contents($filepath, $str);
	}
	return $filepath;
}
?>


text:
'use strict';
const common = require('../common');

if (!common.hasCrypto) {
  common.skip('missing crypto');
  return;
}

const assert = require('assert');
const tls = require('tls');
const fs = require('fs');

const options = {
  key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
  cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
};

const server = tls.createServer(options, function(s) {
  s.end('hello');
}).listen(0, function() {
  const opts = {
    port: this.address().port,
    rejectUnauthorized: false
  };

  server.on('connection', common.mustCall(function(socket) {
    assert.strictEqual(socket.server, server);
    server.close();
  }));

  const client = tls.connect(opts, function() {
    client.end();
  });
});


text:
package org.kaazing.gateway.transport.nio.internal;

import static java.lang.String.format;
import static java.util.Collections.singleton;
import static org.kaazing.gateway.resource.address.ResourceAddress.ALTERNATE;
import static org.kaazing.gateway.resource.address.ResourceAddress.NEXT_PROTOCOL;
import static org.kaazing.gateway.resource.address.ResourceAddress.TRANSPORT;
import static org.kaazing.gateway.resource.address.ResourceAddress.TRANSPORTED_URI;
import static org.kaazing.gateway.transport.BridgeSession.LOCAL_ADDRESS;
import static org.kaazing.gateway.transport.BridgeSession.NEXT_PROTOCOL_KEY;
import static org.kaazing.gateway.transport.BridgeSession.REMOTE_ADDRESS;
import static org.kaazing.gateway.transport.nio.NioSystemProperty.TCP_IDLE_TIMEOUT;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Resource;

import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.DefaultIoSessionDataStructureFactory;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionInitializer;
import org.apache.mina.core.write.WriteRequest;
import org.kaazing.gateway.resource.address.Comparators;
import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.resource.address.ResourceAddressFactory;
import org.kaazing.gateway.resource.address.ResourceOptions;
import org.kaazing.gateway.resource.address.uri.URIUtils;
import org.kaazing.gateway.transport.Bindings;
import org.kaazing.gateway.transport.Bindings.Binding;
import org.kaazing.gateway.transport.BridgeAcceptHandler;
import org.kaazing.gateway.transport.BridgeAcceptor;
import org.kaazing.gateway.transport.BridgeServiceFactory;
import org.kaazing.gateway.transport.BridgeSessionInitializer;
import org.kaazing.gateway.transport.IoHandlerAdapter;
import org.kaazing.gateway.transport.IoSessionAdapterEx;
import org.kaazing.gateway.transport.LoggingFilter;
import org.kaazing.gateway.transport.NextProtocolBindings;
import org.kaazing.gateway.transport.NextProtocolBindings.NextProtocolBinding;
import org.kaazing.gateway.transport.NextProtocolFilter;
import org.kaazing.gateway.transport.NioBindException;
import org.kaazing.gateway.transport.dispatch.ProtocolDispatcher;
import org.kaazing.gateway.util.scheduler.SchedulerProvider;
import org.kaazing.mina.core.buffer.IoBufferEx;
import org.kaazing.mina.core.future.BindFuture;
import org.kaazing.mina.core.future.DefaultUnbindFuture;
import org.kaazing.mina.core.future.UnbindFuture;
import org.kaazing.mina.core.service.IoAcceptorEx;
import org.kaazing.mina.core.service.IoProcessorEx;
import org.kaazing.mina.core.session.IoSessionConfigEx.ChangeListener;
import org.kaazing.mina.core.session.IoSessionEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractNioAcceptor implements BridgeAcceptor {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractNioAcceptor.class);

    private static final String NEXT_PROTOCOL_FILTER = "nio#next-protocol";

    private final AtomicBoolean started;
    private final NextProtocolBindings bindings;
    private final SortedSet<ResourceAddress> boundAuthorities;

    private IoAcceptorEx acceptor;
    private ScheduledExecutorService unbindScheduler;
    private boolean skipIPv6Addresses = false;

    protected ResourceAddressFactory resourceAddressFactory;
    protected BridgeServiceFactory bridgeServiceFactory;

    protected final Properties configuration;
    protected final Logger logger;

    private final Integer idleTimeout;

    public AbstractNioAcceptor(Properties configuration, Logger logger) {
        if (configuration == null) {
            throw new NullPointerException("configuration");
        }
        if (logger == null) {
            throw new NullPointerException("logger");
        }
        this.configuration = configuration;
        this.logger = logger;
        started = new AtomicBoolean(false);
        bindings = new NextProtocolBindings();
        boundAuthorities = new ConcurrentSkipListSet<>(Comparators.compareResourceOrigin());

        String preferIPv4NetworkStack = System.getProperty("java.net.preferIPv4Stack");
        if ("true".equalsIgnoreCase(preferIPv4NetworkStack)) {
            skipIPv6Addresses = true;
        }

        idleTimeout = TCP_IDLE_TIMEOUT.getIntProperty(configuration);
    }

    @Resource(name = "bridgeServiceFactory")
    public void setBridgeServiceFactory(BridgeServiceFactory bridgeServiceFactory) {
        this.bridgeServiceFactory = bridgeServiceFactory;
    }

    @Resource(name = "resourceAddressFactory")
    public void setResourceAddressFactory(ResourceAddressFactory factory) {
        this.resourceAddressFactory = factory;
    }

    /* for testing observability */
    Bindings<?> getBindings() {
        return bindings;
    }

    public boolean emptyBindings() {
        return bindings.isEmpty();
    }

    private final BridgeAcceptHandler tcpHandler = new BridgeAcceptHandler(this) {
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            LoggingFilter.addIfNeeded(logger, session, getTransportName());

            ResourceAddress localAddress = asResourceAddress(session.getLocalAddress());
            NextProtocolBinding nioBinding = bindings.getBinding0(localAddress);
            if (nioBinding == null) {
                // Not currently bound (A concurrent unbind may have removed the binding)
                session.close(true);
                return;
            }

            if (idleTimeout != null && idleTimeout > 0) {
                session.getFilterChain().addLast("idle", new NioIdleFilter(logger, idleTimeout, session));
            }

            // note: defer sessionCreated until sessionOpened to support (optional) protocol dispatch
            SortedSet<String> nextProtocolNames = nioBinding.getNextProtocolNames();
            if (nextProtocolNames == null || nextProtocolNames.isEmpty()) {
                NEXT_PROTOCOL_KEY.set(session, null);
                sessionCreated0(session);
            }
            else if (nextProtocolNames.size() == 1) {
                NEXT_PROTOCOL_KEY.set(session, nextProtocolNames.first());
                sessionCreated0(session);
            }
            else {
                Collection<ProtocolDispatcher> dispatchers = bridgeServiceFactory.getTransportFactory().getProtocolDispatchers().values();

                // sessionCreated will be sent down pipeline again when next-protocol has been determined
                NextProtocolFilter nextProtocol = new NextProtocolFilter(dispatchers) {
                    @Override
                    protected void flushInboundEvents(NextFilter nextFilter, IoSession session) throws Exception {
                        // defer sessionCreated until next-protocol determined
                        sessionCreated0(session);
                        // flush other events after sessionCreated
                        super.flushInboundEvents(nextFilter, session);
                    }
                };
                IoFilterChain filterChain = session.getFilterChain();
                filterChain.addLast(NEXT_PROTOCOL_FILTER, nextProtocol);
            }

        }

        private void sessionCreated0(IoSession session) throws Exception {
            SocketAddress boundAddress0 = session.getLocalAddress();
            ResourceAddress boundAddress = asResourceAddress(boundAddress0);
            String candidateURI = boundAddress.getExternalURI();

            ResourceOptions candidateOptions = ResourceOptions.FACTORY.newResourceOptions(boundAddress);
            String nextProtocol = NEXT_PROTOCOL_KEY.get(session);
            candidateOptions.setOption(NEXT_PROTOCOL, nextProtocol);
            candidateOptions.setOption(TRANSPORT, LOCAL_ADDRESS.get(session));
            ResourceAddress candidateAddress = resourceAddressFactory.newResourceAddress(candidateURI, candidateOptions);

            Binding binding = bindings.getBinding(candidateAddress);
            if (binding == null) {
                // next-protocol not currently bound for this address
                session.close(true);
                return;
            }

            IoHandler handler = binding.handler();
            DELEGATE_KEY.set(session, handler);

            // This is added to store the associated resource address
            // with the nio socket session.  An NioSocketSession localAddress
            // is still an InetSocketAddress, but we can count on this
            // attribute to give us the bound resource address.
            ResourceAddress localAddress = binding.bindAddress();
            LOCAL_ADDRESS.set(session, localAddress);

            SocketAddress remoteSocketAddress = session.getRemoteAddress();
            String remoteExternalURI = asResourceURI((InetSocketAddress) remoteSocketAddress);
            ResourceAddress remoteAddress = resourceAddressFactory.newResourceAddress(remoteExternalURI, nextProtocol);
            REMOTE_ADDRESS.set(session, remoteAddress);

            BridgeSessionInitializer<? extends IoFuture> initializer = binding.initializer();
            if (initializer != null) {
                initializer.initializeSession(session, null);
            }

            // next-protocol has been determined
            super.sessionCreated(session);
        }

        @Override
        public void sessionClosed(IoSession session) throws Exception {
            NEXT_PROTOCOL_KEY.remove(session);
            LOCAL_ADDRESS.remove(session);
            REMOTE_ADDRESS.remove(session);

            super.sessionClosed(session);
        }

        private ResourceAddress asResourceAddress(SocketAddress socketAddress) {
            if (socketAddress instanceof InetSocketAddress) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                return createResourceAddress(inetSocketAddress);
            }

            return (ResourceAddress) socketAddress;
        }

    };

    private ResourceAddress createResourceAddress(InetSocketAddress inetSocketAddress) {
        String transport = asResourceURI(inetSocketAddress);
        return resourceAddressFactory.newResourceAddress(transport);
    }

    private String asResourceURI(InetSocketAddress inetSocketAddress) {
        String transportName = getTransportName();
        InetAddress inetAddress = inetSocketAddress.getAddress();
        String hostAddress = inetAddress.getHostAddress();
        String addressFormat = (inetAddress instanceof Inet6Address) ? "%s://[%s]:%s" : "%s://%s:%s";
        int port = inetSocketAddress.getPort();
        return format(addressFormat, transportName, hostAddress, port);
    }

    protected final void init() {
        acceptor = initAcceptor(null);

        acceptor.setSessionDataStructureFactory(new DefaultIoSessionDataStructureFactory());
        acceptor.setHandler(tcpHandler);
    }

    @Resource(name = "schedulerProvider")
    public final void setSchedulerProvider(SchedulerProvider provider) {
        unbindScheduler = provider.getScheduler(this + "_unbind", true);
    }

    @Override
    public IoHandler getHandler(ResourceAddress address) {
        Binding binding = bindings.getBinding(address);
        return (binding != null) ? binding.handler() : null;
    }

    @Override
    public void bind(final ResourceAddress address,
                     IoHandler handler,
                     BridgeSessionInitializer<? extends IoFuture> initializer) throws NioBindException {

        initIfNecessary();

        ResourceAddress failedAddress = null;
        ResourceAddress currentAddress = address;
        while (currentAddress != null) {
            ResourceAddress transport = currentAddress.getTransport();
            if (transport != null) {

                Binding newBinding = new Binding(currentAddress, handler, initializer);
                Binding binding = bindings.addBinding(newBinding);
                if (binding != null) {
                    failedAddress = currentAddress;
                }

                ResourceAddress transportAddress = currentAddress.getTransport();

                BridgeAcceptor acceptor = bridgeServiceFactory.newBridgeAcceptor(transportAddress);

                acceptor.bind(transportAddress, tcpBridgeHandler, null);
            }
            else {
                // note: [Tcp,Udp]ResourceAddressFactorySpi resolves bind option (then network context) already
                URI resource = currentAddress.getResource();
                InetSocketAddress socketAddress = asSocketAddress(currentAddress);

                if (!(skipIPv6Addresses && (socketAddress.getAddress() instanceof Inet6Address))) {
                    if (socketAddress.isUnresolved()) {
                        failedAddress = currentAddress;
                        throw new NioBindException("Unable to resolve address " + resource.getHost() + ":" + resource.getPort(), singleton(failedAddress));
                    }

                    boolean needsAcceptorBind = !boundAuthorities.contains(currentAddress);

                    Binding newBinding = new Binding(currentAddress, handler, initializer);
                    Binding binding = bindings.addBinding(newBinding);
                    if (binding != null) {
                        failedAddress = currentAddress;
                    }

                    if (needsAcceptorBind) {
                        // Asynchronous bind is needed to avoid a Netty error if bind is called from an IO worker thread.
                        // This can happens from connect in SocksConnector in reverse mode (see KG-7179 for details).
                        BindFuture bound = acceptor.bindAsync(socketAddress);
                        bound.awaitUninterruptibly();
                        Throwable e = bound.getException();
                        if (e != null) {
                            boolean preferIPv6Stack = "true".equalsIgnoreCase(System.getProperty("java.net.preferIPv6Stack"));
                            if (!preferIPv6Stack && (e instanceof SocketException) && (socketAddress.getAddress() instanceof Inet6Address)) {
                                skipIPv6Addresses = true;
                            } else {
                                String error = "Unable to bind resource: " + resource + " cause: " + e.getMessage();
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug(error, e);
                                } else {
                                    LOG.error(error + " "+ e.getMessage());
                                }
                                throw new RuntimeException(error);
                            }
                        } else {
                            boundAuthorities.add(currentAddress);
                            LOG.info("Bound to resource: " + resource);
                        }
                    }
                }
            }

            // bind alternates as well
            currentAddress = currentAddress.getOption(ALTERNATE);
        }

        if (failedAddress != null) {
            throw new NioBindException("Address already bound to different handlers, error in the configuration: " + failedAddress + " address: " + address,
                                       Collections.singletonList(failedAddress));
        }
    }

    @Override
    public UnbindFuture unbind(final ResourceAddress address) {
        // KG-3458: do the unbind asynchronously to avoid blocking the IoProcessor thread in cases where a session close
        // future listener does the unbind (e.g. to unbind a dynamic bind done for SSO revalidate). This was causing
        // a hang when there's a race with Gateway.destroy().
        if (!unbindScheduler.isShutdown()) {
            final UnbindFuture future = new DefaultUnbindFuture();
            unbindScheduler.submit(new FutureTask<>(new Runnable() {
                @Override
                public void run() {
                    try {
                        unbindInternal(address);
                        future.setUnbound();
                    } catch (ThreadDeath td) {
                        throw td;
                    } catch (Throwable t) {
                        LOG.error("Exception during unbinding:\n"+address, t);
                        //System.out.println("Exception during unbinding:\n"+address+"\n");
                        //t.printStackTrace(System.out);
                        future.setException(t);
                        throw new RuntimeException(t);
                    }
                }
            }, Boolean.TRUE));
            return future;
        }
        else {
            return DefaultUnbindFuture.succeededFuture();
        }
    }

    protected final void initIfNecessary() {
        if (!started.get()) {
            synchronized (started) {
                if (!started.get()) {
                    init();
                    started.set(true);
                }
            }
        }
    }

    private void unbindInternal(ResourceAddress address) {

        while (address != null) {

            ResourceAddress transport = address.getTransport();
            if (transport != null) {

                Binding nioBinding = bindings.getBinding(address);
                if (nioBinding != null) {
                    bindings.removeBinding(address, nioBinding);
                }

                BridgeAcceptor bridgeAcceptor = bridgeServiceFactory.newBridgeAcceptor(transport);
                bridgeAcceptor.unbind(address.getTransport());
            }
            else {
                try {
                    // note: [Tcp,Udp]ResourceAddressFactorySpi resolves bind option (then network context) already

                    // ref count this binding so we don't unbind until every acceptor is unbound
                    Binding nioBinding = bindings.getBinding(address);
                    if (nioBinding != null) {
                        boolean removed = bindings.removeBinding(address, nioBinding);
                        if (removed) {
                            ResourceAddress bindAddress = nioBinding.bindAddress();
                            InetSocketAddress socketAddress = asSocketAddress(bindAddress);
                            acceptor.unbind(socketAddress);
                            boundAuthorities.remove(bindAddress);
                        }
                    }
                } catch (RuntimeException e) {
                    LOG.error("Error while unbinding " + address, e);
                }
            }

            address = address.getOption(ALTERNATE);
        }
    }

    @Override
    public void dispose() {
        if (acceptor != null) {
            acceptor.dispose();
        }
    }

    protected abstract IoAcceptorEx initAcceptor(final IoSessionInitializer<? extends IoFuture> initializer);

    protected abstract String getTransportName();

    private static InetSocketAddress asSocketAddress(ResourceAddress address) {
        URI location = address.getResource();
        return new InetSocketAddress(location.getHost(), location.getPort());
    }

    //
    // Tcp as a "virtual" bridge session when we specify tcp.transport option in a resource address.
    //

    public static final String TCP_SESSION_KEY = "tcp.bridgeSession.key"; // holds tcp session acting as a bridge
    public static final String PARENT_KEY = "tcp.parentKey.key"; // holds parent of tcp bridge session

    private final IoProcessorEx<IoSessionAdapterEx> tcpBridgeProcessor = new IoProcessorEx<IoSessionAdapterEx>() {
        @Override
        public void add(IoSessionAdapterEx session) {
            // Do nothing
        }

        @Override
        public void flush(IoSessionAdapterEx session) {
            IoSession parent = (IoSession) session.getAttribute(PARENT_KEY);
            WriteRequest req = session.getWriteRequestQueue().poll(session);

            // Check that the request is not null. If the session has been closed,
            // we may not have any pending requests.
            if (req != null) {
                final WriteFuture tcpBridgeWriteFuture = req.getFuture();
                Object m = req.getMessage();
                if (m instanceof IoBufferEx && ((IoBufferEx) m).remaining() == 0) {
                    session.setCurrentWriteRequest(null);
                    tcpBridgeWriteFuture.setWritten();
                } else {
                    WriteFuture parentWriteFuture = parent.write(m);
                    parentWriteFuture.addListener(new IoFutureListener<WriteFuture>() {
                        @Override
                        public void operationComplete(WriteFuture future) {
                            if (future.isWritten()) {
                                tcpBridgeWriteFuture.setWritten();
                            }
                            else {
                                tcpBridgeWriteFuture.setException(future.getException());
                            }
                        }
                    });
                }
            }
        }

        @Override
        public void remove(IoSessionAdapterEx session) {
            LOG.debug("AbstractNioAcceptor Fake Processor remove session "+session);
            IoSession parent = (IoSession) session.getAttribute(PARENT_KEY);
            parent.close(false);
            acceptor.getListeners().fireSessionDestroyed(session);
        }

        @Override
        public void updateTrafficControl(IoSessionAdapterEx session) {
            // Do nothing
        }

        @Override
        public void dispose() {
            // Do nothing
        }

        @Override
        public boolean isDisposed() {
            return false;
        }

        @Override
        public boolean isDisposing() {
            return false;
        }

    };

    private final IoHandlerAdapter<IoSessionEx> tcpBridgeHandler =
            new IoHandlerAdapter<IoSessionEx>() {

                @Override
                public void doSessionClosed(IoSessionEx session) throws Exception {
                    LOG.debug("AbstractNioAcceptor.doSessionClosed for session "+session);
                    NEXT_PROTOCOL_KEY.remove(session);
                    LOCAL_ADDRESS.remove(session);
                    REMOTE_ADDRESS.remove(session);
                    IoSession tcpBridgeSession = getTcpBridgeSession(session);
                    if ( tcpBridgeSession != null ) {
                        tcpBridgeSession.getFilterChain().fireSessionClosed();
                    }
                }

                @Override
                protected void doSessionCreated(IoSessionEx session) throws Exception {
                    LoggingFilter.addIfNeeded(logger, session, getTransportName());

                    ResourceAddress candidateAddress = getCandidateResourceAddress(session);
                    NextProtocolBinding nextBinding = bindings.getBinding0(candidateAddress);
                    if (nextBinding == null) {
                        // next-protocol not currently bound for this address
                        session.close(true);
                        return;
                    }
                    SortedSet<String> nextProtocolNames = nextBinding.getNextProtocolNames();
                    if (nextProtocolNames == null || nextProtocolNames.isEmpty()) {
                        NEXT_PROTOCOL_KEY.set(session, null);
                    }
                    else if (nextProtocolNames.size() == 1) {
                        NEXT_PROTOCOL_KEY.set(session, nextProtocolNames.first());
                    }
                    else {
                        Collection<ProtocolDispatcher> dispatchers = bridgeServiceFactory.getTransportFactory().getProtocolDispatchers().values();

                        // sessionCreated will be sent down pipeline again when next-protocol has been determined
                        NextProtocolFilter nextProtocol = new NextProtocolFilter(dispatchers);
                        IoFilterChain filterChain = session.getFilterChain();
                        filterChain.addLast(NEXT_PROTOCOL_FILTER, nextProtocol);
                    }

                }

                @Override
                protected void doSessionOpened(final IoSessionEx session) throws Exception {
                    ResourceAddress candidateAddress = getCandidateResourceAddress(session);
                    final Binding binding = bindings.getBinding(candidateAddress);
                    if (binding == null) {
                        // next-protocol not currently bound for this address
                        session.close(true);
                        return;
                    }

                    IoSessionAdapterEx newTcpBridgeSession = new IoSessionAdapterEx(session.getIoThread(),
                                                                                session.getIoExecutor(),
                                                                                acceptor,
                                                                                tcpBridgeProcessor,
                                                                                acceptor.getSessionDataStructureFactory());
                    newTcpBridgeSession.setLocalAddress(binding.bindAddress());
                    newTcpBridgeSession.setRemoteAddress(resourceAddressFactory.newResourceAddress(binding.bindAddress(),
                                                                                REMOTE_ADDRESS.get(session)));

                    newTcpBridgeSession.setHandler(binding.handler());

                    newTcpBridgeSession.setTransportMetadata(acceptor.getTransportMetadata());

                    newTcpBridgeSession.setAttribute(PARENT_KEY, session);
                    newTcpBridgeSession.setTransportMetadata(acceptor.getTransportMetadata());

                    // Propagate changes to idle time to the parent session
                    newTcpBridgeSession.getConfig().setChangeListener(new ChangeListener() {
                        @Override
                        public void idleTimeInMillisChanged(IdleStatus status, long idleTime) {
                            session.getConfig().setIdleTimeInMillis(status, idleTime);
                        }
                    });

                    session.setAttribute(TCP_SESSION_KEY, newTcpBridgeSession);

                    if ( binding.initializer() != null ) {
                        binding.initializer().initializeSession(newTcpBridgeSession, null);
                    }

                    acceptor.getListeners().fireSessionCreated(newTcpBridgeSession);
                }

                private ResourceAddress getCandidateResourceAddress(IoSessionEx session) {
                    // Build candidate address from session
                    final ResourceAddress candidateTransportAddress = REMOTE_ADDRESS.get(session);
                    URI candidateURI = candidateTransportAddress.getOption(TRANSPORTED_URI);

                    ResourceOptions candidateOptions = ResourceOptions.FACTORY.newResourceOptions();

                    candidateOptions.setOption(NEXT_PROTOCOL, NEXT_PROTOCOL_KEY.get(session));
                    candidateOptions.setOption(TRANSPORT, candidateTransportAddress);
                    return resourceAddressFactory.newResourceAddress(URIUtils.uriToString(candidateURI), candidateOptions);
                }

                private IoSession getTcpBridgeSession(IoSession session) {
                    return (IoSession) session.getAttribute(TCP_SESSION_KEY);
                }

                @Override
                protected void doExceptionCaught(IoSessionEx session, Throwable cause) throws Exception {
                    //TODO: consider tcpBridgeSession.reset as an alternate impl.
                    LOG.debug("NioSocketAcceptor exception caught", cause);

                    if (!session.isClosing()) {
                        IoSession tcpBridgeSession = getTcpBridgeSession(session);
                        if (tcpBridgeSession != null) {
                            tcpBridgeSession.getFilterChain().fireExceptionCaught(cause);
                        }
                    } else {
                        LOG.debug("Unexpected exception while session is closing", cause);
                    }
                }

                @Override
                public void doSessionIdle(IoSessionEx session, IdleStatus status) throws Exception {
                    IoSession tcpBridgeSession = getTcpBridgeSession(session);
                    tcpBridgeSession.getFilterChain().fireSessionIdle(status);
                }

                @Override
                protected void doMessageReceived(IoSessionEx session, Object message) throws Exception {
                    IoSession tcpBridgeSession = getTcpBridgeSession(session);
                    tcpBridgeSession.getFilterChain().fireMessageReceived(message);
                }

            };
}


text:
/***********************************
 * $Id$
 ***********************************
 *
 ***************************************
 * Simple drivers common header
 ***************************************
 */

#ifndef __SIMPLE_H
#define __SIMPLE_H

/* #include "quicc.h" */

#define GLB_SCC_0   0
#define GLB_SCC_1   1
#define GLB_SCC_2   2
#define GLB_SCC_3   3

typedef void (int_routine)(unsigned short interrupt_event);
typedef int_routine *int_routine_ptr;
typedef void *(alloc_routine)(int length);
typedef void (free_routine)(int scc_num, int channel_num, void *buf);
typedef void (store_rx_buffer_routine)(int scc_num, int channel_num, void *buff, int length);
typedef int  (handle_tx_error_routine)(int scc_num, int channel_num, QUICC_BD *tbd);
typedef void (handle_rx_error_routine)(int scc_num, int channel_num, QUICC_BD *rbd);
typedef void (handle_lost_error_routine)(int scc_num, int channel_num);

/* user defined functions for global errors */
typedef void (handle_glob_overrun_routine)(int scc_number);
typedef void (handle_glob_underrun_routine)(int scc_number);
typedef void (glob_intr_q_overflow_routine)(int scc_number);

/*
 * General initialization and command routines
 */
void quicc_issue_cmd (unsigned short cmd, int scc_num);
void quicc_init(void);
void quicc_scc_init(int scc_number, int number_of_rx_buf, int number_of_tx_buf);
void quicc_smc_init(int smc_number, int number_of_rx_buf, int number_of_tx_buf);
void quicc_scc_start(int scc_num);
void quicc_scc_loopback(int scc_num);

/* Interrupt enable/disable routines for critical pieces of code*/
unsigned short  IntrDis(void);
void            IntrEna(unsigned short old_sr);

/* For debugging */
void print_rbd(int scc_num);
void print_tbd(int scc_num);

#endif


text:
package mdgithub

import (
	"bytes"
	"html"

	"gopkg.in/akavel/vfmd.v1/md"
	"gopkg.in/akavel/vfmd.v1/mdblock"
	"gopkg.in/akavel/vfmd.v1/x/mdhtml"
)

type FencedCodeBlock struct {
	// TODO(akavel): Language string
	md.Prose
	md.Raw
}

func (FencedCodeBlock) Detect(first, second mdblock.Line, detectors mdblock.Detectors) mdblock.Handler {
	if !bytes.HasPrefix(first.Bytes, []byte("```")) {
		return nil
	}

	block := FencedCodeBlock{}
	done := false
	return mdblock.HandlerFunc(func(next mdblock.Line, ctx mdblock.Context) (bool, error) {
		if done {
			return false, nil
		}
		if next.EOF() {
			ctx.Emit(block)
			ctx.Emit(md.End{})
			return false, nil
		}
		if len(block.Raw) > 0 {
			// Three backticks, on second on later line - means end of block.
			if bytes.HasPrefix(next.Bytes, []byte("```")) {
				done = true
				ctx.Emit(block)
				ctx.Emit(md.End{})
			} else {
				// Collect all stuff between first and last fenced line into Prose.
				block.Prose = append(block.Prose, md.Run(next))
			}
		}
		block.Raw = append(block.Raw, md.Run(next))
		return true, nil
	})
}

func (b FencedCodeBlock) HTMLBlock(ctx mdhtml.Context, opt mdhtml.Opt) ([]md.Tag, error) {
	ctx.Printf("
")
	for _, r := range b.Prose {
		ctx.Printf("%s", html.EscapeString(string(r.Bytes)))
	}
	ctx.Printf("
\n")
	// Skip self and subsequent md.End{}
	return ctx.Tags[2:], ctx.Err
}