text:
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif

#import "Clustering/GMUClusterManager+Testing.h"

#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>

@interface GMUClusterManagerTest : XCTestCase
@end

static const CLLocationCoordinate2D kCameraPosition = {-35, 151};
static const double kCameraZoom = 10.0;

@implementation GMUClusterManagerTest {
  // Object under test.
  GMUClusterManager *_clusterManager;
  id _mapView;
  id _algorithm;
  id _renderer;
  id _delegate;
  id _mapDelegate;
  GMSCameraPosition *_camera;
}

- (void)setUp {
  [super setUp];

  _mapView = OCMClassMock([GMSMapView class]);
  _camera = [GMSCameraPosition cameraWithTarget:kCameraPosition zoom:kCameraZoom];
  [[[_mapView stub] andDo:^(NSInvocation *invocation) {
    [invocation setReturnValue:&_camera];
  }] camera];

  _algorithm = OCMProtocolMock(@protocol(GMUClusterAlgorithm));
  _renderer = OCMProtocolMock(@protocol(GMUClusterRenderer));

  _clusterManager =
      [[GMUClusterManager alloc] initWithMap:_mapView algorithm:_algorithm renderer:_renderer];

  _delegate = OCMProtocolMock(@protocol(GMUClusterManagerDelegate));
  _mapDelegate = OCMProtocolMock(@protocol(GMSMapViewDelegate));
  [_clusterManager setDelegate:_delegate mapDelegate:_mapDelegate];
}

- (void)tearDown {
  [super tearDown];

  OCMVerifyAll(_algorithm);
  OCMVerifyAll(_renderer);
  OCMVerifyAll(_delegate);
  OCMVerifyAll(_mapDelegate);
}

// Tests that clusterManager does not set mapView.delegate to itself on init.
- (void)testInitMapDelegateNotHookedByDefault {
  [[_mapView reject] setDelegate:OCMOCK_ANY];
  _clusterManager =
      [[GMUClusterManager alloc] initWithMap:_mapView algorithm:_algorithm renderer:_renderer];
  OCMVerifyAll(_mapView);
}

- (void)testInit {
  XCTAssertEqual(_clusterManager.algorithm, _algorithm);
  XCTAssertEqual(_clusterManager.delegate, _delegate);
  XCTAssertEqual(_clusterManager.mapDelegate, _mapDelegate);
}

- (void)testAddItem {
  // Arrange.
  id item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  [[_algorithm expect] addItems:@[ item1 ]];

  // Act.
  [_clusterManager addItem:item1];
}

- (void)testAddItems {
  // Arrange.
  id item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  id item2 = OCMProtocolMock(@protocol(GMUClusterItem));
  [[_algorithm expect] addItems:@[ item1, item2 ]];

  // Act.
  [_clusterManager addItems:@[ item1, item2 ]];
}

- (void)testRemoveItem {
  // Arrange.
  id item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  [[_algorithm expect] removeItem:item1];
  [_clusterManager addItem:item1];

  // Act.
  [_clusterManager removeItem:item1];
}

- (void)testClearItems {
  // Arrange.
  id item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  id item2 = OCMProtocolMock(@protocol(GMUClusterItem));
  [[_algorithm expect] clearItems];
  [_clusterManager addItems:@[ item1, item2 ]];

  // Act.
  NSUInteger requestCount = [_clusterManager clusterRequestCount];
  [_clusterManager clearItems];
  XCTAssertEqual([_clusterManager clusterRequestCount], requestCount + 1);
}

- (void)testCluster {
  NSArray<id<GMUCluster>> *clusters = @[ OCMProtocolMock(@protocol(GMUCluster)) ];
  [[[_algorithm expect] andReturn:clusters] clustersAtZoom:kCameraZoom];
  [[_renderer expect] renderClusters:clusters];

  [_clusterManager cluster];
}

- (void)testCameraChangedReclusterRequested {
  // Arrange.
  NSArray<id<GMUCluster>> *clusters = @[ OCMProtocolMock(@protocol(GMUCluster)) ];
  [[[_algorithm expect] andReturn:clusters] clustersAtZoom:kCameraZoom];
  [[_renderer expect] renderClusters:clusters];
  // Intial cluster.
  [_clusterManager cluster];

  // Act.
  _camera = [GMSCameraPosition cameraWithTarget:kCameraPosition zoom:kCameraZoom + 2];
  [_clusterManager observeValueForKeyPath:@"camera" ofObject:_mapView change:nil context:nil];
  XCTAssertEqual([_clusterManager clusterRequestCount], 1);
}

// Small camera change should not trigger re-clustering.
- (void)testCameraChangedALittleReclusterNotRequested {
  // Arrange.
  NSArray<id<GMUCluster>> *clusters = @[ OCMProtocolMock(@protocol(GMUCluster)) ];
  [[[_algorithm expect] andReturn:clusters] clustersAtZoom:kCameraZoom];
  [[_renderer expect] renderClusters:clusters];
  // Intial cluster.
  [_clusterManager cluster];

  // Act.
  _camera = [GMSCameraPosition cameraWithTarget:kCameraPosition zoom:kCameraZoom + 0.3];
  [_clusterManager observeValueForKeyPath:@"camera" ofObject:_mapView change:nil context:nil];
  XCTAssertEqual([_clusterManager clusterRequestCount], 0);
}

- (void)testTapOnClusterMarkerEventRaised {
  id<GMUCluster> cluster1 = OCMProtocolMock(@protocol(GMUCluster));
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.map = _mapView;
  marker.userData = cluster1;

  // Expect and reject.
  [[_delegate expect] clusterManager:_clusterManager didTapCluster:cluster1];
  [[_delegate reject] clusterManager:_clusterManager didTapClusterItem:OCMOCK_ANY];

  // Act.
  [_clusterManager mapView:_mapView didTapMarker:marker];
}

- (void)testTapOnClusterItemMarkerEventRaised {
  id<GMUClusterItem> item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.map = _mapView;
  marker.userData = item1;

  // Expect and reject.
  [[_delegate reject] clusterManager:_clusterManager didTapCluster:OCMOCK_ANY];
  [[_delegate expect] clusterManager:_clusterManager didTapClusterItem:item1];

  // Act.
  [_clusterManager mapView:_mapView didTapMarker:marker];
}

- (void)testTapOnClusterItemMarkerNoDelegateEventRaisedOnMapDelegate {
  id<GMUClusterItem> item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.map = _mapView;
  marker.userData = item1;
  [_clusterManager setDelegate:nil mapDelegate:_mapDelegate];

  // Expect and reject.
  [[_delegate reject] clusterManager:_clusterManager didTapCluster:OCMOCK_ANY];
  [[_delegate reject] clusterManager:_clusterManager didTapClusterItem:item1];
  [[_mapDelegate expect] mapView:_mapView didTapMarker:marker];

  // Act.
  [_clusterManager mapView:_mapView didTapMarker:marker];
}

- (void)testTapOnClusterItemMarkerDelegateRetusnNOEventRaisedOnMapDelegate {
  id<GMUClusterItem> item1 = OCMProtocolMock(@protocol(GMUClusterItem));
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.map = _mapView;
  marker.userData = item1;
  [_clusterManager setDelegate:_delegate mapDelegate:_mapDelegate];

  // Expect and reject.
  [[_delegate reject] clusterManager:_clusterManager didTapCluster:OCMOCK_ANY];

  // Set _delegate to not handle the event.
  [[[_delegate stub] andReturnValue:OCMOCK_VALUE(NO)] clusterManager:_clusterManager
                                                   didTapClusterItem:item1];
  [[_mapDelegate expect] mapView:_mapView didTapMarker:marker];

  // Act.
  [_clusterManager mapView:_mapView didTapMarker:marker];
}

- (void)testTapOnClusterMarkerDelegateRetusnNOEventRaisedOnMapDelegate {
  id<GMUCluster> cluster1 = OCMProtocolMock(@protocol(GMUCluster));
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.map = _mapView;
  marker.userData = cluster1;

  // Expect and reject.
  // Set _delegate to not handle the event.
  [[[_delegate stub] andReturnValue:OCMOCK_VALUE(NO)] clusterManager:_clusterManager
                                                       didTapCluster:cluster1];
  [[_delegate reject] clusterManager:_clusterManager didTapClusterItem:OCMOCK_ANY];
  [[_mapDelegate expect] mapView:_mapView didTapMarker:marker];

  // Act.
  [_clusterManager mapView:_mapView didTapMarker:marker];
}

- (void)testTapOnNormalMarkerEventRaisedOnMapDelegate {
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.map = _mapView;

  // Expect and reject.
  [[_delegate reject] clusterManager:_clusterManager didTapCluster:OCMOCK_ANY];
  [[_delegate reject] clusterManager:_clusterManager didTapClusterItem:OCMOCK_ANY];
  [[_mapDelegate expect] mapView:_mapView didTapMarker:marker];

  // Act.
  [_clusterManager mapView:_mapView didTapMarker:marker];
}

- (void)testMapEventsForwardedToMapDelegate {
  GMSMarker *marker = [[GMSMarker alloc] init];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:kCameraPosition zoom:kCameraZoom];

  // Expect and reject.
  [[_mapDelegate expect] mapView:_mapView willMove:YES];
  [[_mapDelegate expect] mapView:_mapView didChangeCameraPosition:camera];
  [[_mapDelegate expect] mapView:_mapView idleAtCameraPosition:camera];
  [[_mapDelegate expect] mapView:_mapView didTapAtCoordinate:kCameraPosition];
  [[_mapDelegate expect] mapView:_mapView didLongPressAtCoordinate:kCameraPosition];
  [[_mapDelegate expect] mapView:_mapView didTapInfoWindowOfMarker:marker];
  [[_mapDelegate expect] mapView:_mapView didLongPressInfoWindowOfMarker:marker];
  [[_mapDelegate expect] mapView:_mapView didTapOverlay:marker];
  [[_mapDelegate expect] mapView:_mapView markerInfoWindow:marker];
  [[_mapDelegate expect] mapView:_mapView markerInfoContents:marker];
  [[_mapDelegate expect] mapView:_mapView didCloseInfoWindowOfMarker:marker];
  [[_mapDelegate expect] mapView:_mapView didBeginDraggingMarker:marker];
  [[_mapDelegate expect] mapView:_mapView didEndDraggingMarker:marker];
  [[_mapDelegate expect] didTapMyLocationButtonForMapView:_mapView];
  [[_mapDelegate expect] mapViewDidStartTileRendering:_mapView];
  [[_mapDelegate expect] mapViewDidFinishTileRendering:_mapView];

  // Act.
  [_clusterManager mapView:_mapView willMove:YES];
  [_clusterManager mapView:_mapView didChangeCameraPosition:camera];
  [_clusterManager mapView:_mapView idleAtCameraPosition:camera];
  [_clusterManager mapView:_mapView didTapAtCoordinate:kCameraPosition];
  [_clusterManager mapView:_mapView didLongPressAtCoordinate:kCameraPosition];
  [_clusterManager mapView:_mapView didTapInfoWindowOfMarker:marker];
  [_clusterManager mapView:_mapView didLongPressInfoWindowOfMarker:marker];
  [_clusterManager mapView:_mapView didTapOverlay:marker];
  [_clusterManager mapView:_mapView markerInfoWindow:marker];
  [_clusterManager mapView:_mapView markerInfoContents:marker];
  [_clusterManager mapView:_mapView didCloseInfoWindowOfMarker:marker];
  [_clusterManager mapView:_mapView didBeginDraggingMarker:marker];
  [_clusterManager mapView:_mapView didEndDraggingMarker:marker];
  [_clusterManager didTapMyLocationButtonForMapView:_mapView];
  [_clusterManager mapViewDidStartTileRendering:_mapView];
  [_clusterManager mapViewDidFinishTileRendering:_mapView];
}

@end


text:
<?php

require_once 'Bootstrap.php';
use \PDO;

class ConnectTest extends PHPUnit_Framework_TestCase
{
	public function testCreateOptions()
	{
		//we explicitely remove the options not compatible with sqlite.
		$dsn = 'sqlite::memory:';
		$db = new Connect($dsn, null, null);
		$this->assertEquals(true,$db->getAttribute(PDO::ATTR_ERRMODE));
		$this->assertEquals(PDO::FETCH_ASSOC,$db->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE));
	}
}

redpajama_set_name: RedPajamaGithub


text:
//Copyright (c) 2016 Kai Clavier [kaiclavier.com] Do Not Distribute
using UnityEngine;
using System.Collections.Generic;

[System.Serializable]
public class ShakeData {
	[Tooltip("The name that will call this.")]
	public string name;
	[Tooltip("The strength of the shake, on individual axises, in localPosition.")]
	public Vector3 strength = Vector2.one; //Vector2.one can be used to get a nice 2d screenshake
	[Range(0.0001f, 10f)]
	[Tooltip("How long the screenshake will last for.")]
	public float time = 0.5f;
	[Tooltip("Intensity over time.")]
	public AnimationCurve curve = new AnimationCurve(new Keyframe(0,1,-1,-1), new Keyframe(1,0,-1,-1));
	[Tooltip("What decimal play the random values should be rounded to. 7 means disabled. Still not perfect because floats.")]
	[Range(0,7)]
	public int roundDecimals = 7;
}
[System.Serializable]
public class KickbackData {
	[Tooltip("The name that will call this.")]
	public string name;
	[Tooltip("The strength of the kickback, in localPosition.")]
	public float strength = 1f;
	[Range(0.0001f, 10f)]
	[Tooltip("How long the kickback will last for.")]
	public float time = 0.5f;
	[Tooltip("Distance over time.")]
	public AnimationCurve curve = new AnimationCurve(new Keyframe(0,1,-1,-1), new Keyframe(1,0,-1,-1));
	[Tooltip("What decimal play the random values should be rounded to. 7 means disabled. Still not perfect because floats.")]
	[Range(0,7)]
	public int roundDecimals = 7;
}
[CreateAssetMenu(fileName = "New Screenshake Data", menuName = "Clavian/Screenshake Data", order = 1)]
public class ScreenshakeData : ScriptableObject {
	[Header("Shakes")]
	public List<ShakeData> shakes = new List<ShakeData>(); //a list, so you can use Find()
	[Header("Kickbacks")]
	public List<KickbackData> kicks = new List<KickbackData>();
}


text:
require 'waw'
require 'test/unit'
module Waw
  class RackExtensionTest < Test::Unit::TestCase

    class AnApp
      include Rack::Delegator
      def initialize(name)
        @name = name
      end
      def to_s
        "#{self.class}('#{@name}')"
      end
    end

    # Creates a typical rack application under @app
    def setup
      @app1 = AnApp.new('/')
      @app2 = AnApp.new('/webserv/event')
      @app3 = AnApp.new('/webserv/people')
      @urlmap2 = ::Rack::URLMap.new(
        '/event' => @app2,
        '/people' => @app3
      )
      @json = ::Waw::JSONController.new(@urlmap2)
      @urlmap1 = ::Rack::URLMap.new(
        '/' => @app1,
        '/webserv' => @json
      )
      @session = ::Rack::Session::Pool.new(@urlmap1, :domain => "www.waw.org", :expire_after => 65)
      @logger = ::Rack::CommonLogger.new(@session, STDOUT)
      @restart = ::Waw::Restart.new(@logger)
      @app = ::Waw::Kern::App.new
      @app.app = @restart
    end

    def test_find_rack_app
      app = @app
      assert_equal @app1, app.find_rack_app('/')
      assert_equal @app1, app.find_rack_app('/'){|theapp| AnApp===theapp}
      assert ::Waw::JSONController===app.find_rack_app('/webserv')
      assert_equal @app2, app.find_rack_app('/webserv/event'){|theapp| AnApp===theapp}
      assert_equal @app2, app.find_rack_app('/webserv/event/and_an_action_name'){|theapp| AnApp===theapp}
      assert_equal @app3, app.find_rack_app('/webserv/people'){|theapp| AnApp===theapp}
      assert_equal @app3, app.find_rack_app('/webserv/people/and_an_action_name'){|theapp| AnApp===theapp}
      assert_equal @logger, app.find_rack_app{|theapp| ::Rack::CommonLogger===theapp}
      assert_equal @json, app.find_rack_app{|theapp| ::Waw::JSONController===theapp}
    end

    def test_find_url_of
      assert_equal '/', @app.find_url_of(@app)
      [@logger, @session, @urlmap1, @app1].each {|app| assert_equal '/', @app.find_url_of(app)}
      [@json, @urlmap2].each{|app| assert_equal '/webserv', @app.find_url_of(app)}
      [@app2].each{|app| assert_equal '/webserv/event', @app.find_url_of(app)}
      [@app3].each{|app| assert_equal '/webserv/people', @app.find_url_of(app)}
      assert_equal nil, @app.find_url_of(self)
    end

    def test_visit
      paths = Hash.new{|h,k| h[k] = []}
      @app.visit{|path, app|
        paths[path] << app
      }
      expected = {
        '/' => [@app, @restart, @logger, @session, @urlmap1, @app1],
        '/webserv' => [@json, @urlmap2],
        '/webserv/event' => [@app2],
        '/webserv/people' => [@app3]
      }
      assert_equal expected, paths
    end

  end
end


text:
import {
  calculateFontSize_,
  updateOverflow_,
} from '../amp-fit-text';

describes.realWin('amp-fit-text component', {
  amp: {
    extensions: ['amp-fit-text'],
  },
}, env => {
  let win, doc;

  beforeEach(() => {
    win = env.win;
    doc = win.document;
  });

  function getFitText(text, opt_responsive) {
    const ft = doc.createElement('amp-fit-text');
    ft.setAttribute('width', '111');
    ft.setAttribute('height', '222');
    ft.style.fontFamily = 'Arial';
    ft.style.fontSize = '17px';
    ft.style.lineHeight = '17px';
    ft.style.overflow = 'hidden';
    ft.style.width = '111px';
    ft.style.height = '222px';
    ft.style.position = 'relative';
    if (opt_responsive) {
      ft.setAttribute('layout', 'responsive');
    }
    ft.textContent = text;
    doc.body.appendChild(ft);
    return ft.build().then(() => ft.layoutCallback()).then(() => ft);
  }

  it('renders', () => {
    const text = 'Lorem ipsum';
    return getFitText(text).then(ft => {
      const content = ft.querySelector('.i-amphtml-fit-text-content');
      expect(content).to.not.equal(null);
      expect(content.textContent).to.equal(text);
    });
  });
});

describes.realWin('amp-fit-text calculateFontSize', {}, env => {
  let win, doc;
  let element;

  beforeEach(() => {
    win = env.win;
    doc = win.document;
    element = doc.createElement('div');
    element.style.fontFamily = 'Arial';
    element.style.lineHeight = '1em';
    element.style.position = 'absolute';
    element.style.left = 0;
    element.style.top = 0;
    element.style.visibility = 'hidden';
    doc.body.appendChild(element);
  });

  it('should always fit on one line w/ enough width', () => {
    element./*OK*/innerHTML = 'A';
    expect(calculateFontSize_(element, 20, 200, 6, 72)).to.equal(20);
    expect(calculateFontSize_(element, 10, 200, 6, 72)).to.equal(10);
    expect(calculateFontSize_(element, 40, 200, 6, 72)).to.equal(40);
  });

  it('should always fit the width w/ enough height', () => {
    element./*OK*/innerHTML = 'A';
    expect(calculateFontSize_(element, 200, 10, 6, 72)).to.equal(15);
    expect(calculateFontSize_(element, 200, 20, 6, 72)).to.equal(30);
    expect(calculateFontSize_(element, 200, 40, 6, 72)).to.equal(60);
  });

  it('should hit min w/ small height and enough width', () => {
    element./*OK*/innerHTML = 'A';
    expect(calculateFontSize_(element, 6, 200, 6, 72)).to.equal(6);
    expect(calculateFontSize_(element, 3, 200, 6, 72)).to.equal(6);
  });

  it('should hit min w/ small width and enough height', () => {
    element./*OK*/innerHTML = 'A';
    expect(calculateFontSize_(element, 200, 2, 6, 72)).to.equal(6);
    expect(calculateFontSize_(element, 200, 4, 6, 72)).to.equal(6);
  });

  it('should hit max w/ enough width', () => {
    element./*OK*/innerHTML = 'A';
    expect(calculateFontSize_(element, 72, 200, 6, 72)).to.equal(72);
    expect(calculateFontSize_(element, 80, 200, 6, 72)).to.equal(72);
  });

  it('should hit max w/ enough height', () => {
    element./*OK*/innerHTML = 'A';
    expect(calculateFontSize_(element, 200, 48, 6,72)).to.equal(72);
    expect(calculateFontSize_(element, 200, 60, 6, 72)).to.equal(72);
  });

  it('should always fit on two lines w/ enough width', () => {
    element./*OK*/innerHTML = 'A
B';
    expect(calculateFontSize_(element, 20, 200, 6, 72)).to.equal(10);
  });
});

describes.realWin('amp-fit-text updateOverflow', {}, env => {
  let win, doc;
  let content;
  let classToggles;
  let measurer;

  beforeEach(() => {
    win = env.win;
    doc = win.document;
    classToggles = {};
    content = {
      style: {},
      classList: {
        toggle: (className, on) => {
          classToggles[className] = on;
        },
      },
    };

    measurer = doc.createElement('div');
    measurer.style.fontFamily = 'Arial';
    measurer.style.lineHeight = '1.15em';
    measurer.style.position = 'absolute';
    measurer.style.width = '300px';
    doc.body.appendChild(measurer);
  });

  function getLineClamp() {
    for (const k in content.style) {
      if (k == 'lineClamp' || k.match(/.*LineClamp/)) {
        return content.style[k];
      }
    }
    return null;
  }

  it('should always fit on one line', () => {
    measurer./*OK*/innerHTML = 'A';
    updateOverflow_(content, measurer, 24, 20);
    expect(classToggles['i-amphtml-fit-text-content-overflown']).to.be.false;
    expect(getLineClamp()).to.equal('');
    expect(content.style.maxHeight).to.equal('');
  });

  it('should always fit on two lines', () => {
    measurer./*OK*/innerHTML = 'A
B';
    updateOverflow_(content, measurer, 24, 20);
    expect(classToggles['i-amphtml-fit-text-content-overflown']).to.equal(true);
    expect(getLineClamp()).to.equal(1);
    expect(content.style.maxHeight).to.equal(23 + 'px'); // 23 = 20 * 1.15
  });
});


text:
/**
 *    @file
 *      This file defines a class for managing and manipulating a Host
 *      Port List, a compact, binary-encoded collection of host and port
 *      identifier tuples associated with the Weave Service Directory.
 *
 */

#ifndef HOSTPORTLIST_H_
#define HOSTPORTLIST_H_

#include <stdint.h>

#include <Weave/Core/WeaveError.h>

namespace nl {
namespace Weave {

/**
 *  @class HostPortList
 *
 *  @brief
 *    For managing and manipulating a Host Port List, a compact,
 *    binary-encoded collection of host and port identifier tuples
 *    associated with the Weave Service Directory.
 *
 */
class HostPortList
{
 public:
    HostPortList(void) = default;
    inline HostPortList(const uint8_t *hostPortList, uint8_t hostPortCount, const uint8_t *suffixList, const uint8_t suffixCount)
    {
        mElements    = hostPortList;
        mCount       = hostPortCount;
        mSuffixTable = suffixList;
        mSuffixCount = suffixCount;
    }

    WEAVE_ERROR Get(uint8_t index, char *hostBuf, uint32_t hostBufSize, uint16_t& port) const;
    WEAVE_ERROR Pop(char *hostBuf, uint32_t hostBufSize, uint16_t& port);

    void Clear(void);

    inline bool IsEmpty(void) const { return (mCount == 0); }

private:
    enum
    {
        kHostPortControl_TypeMask       = 0x03,  ///< Mask for the type of entry flags.
        kHostPortControl_HasSuffixIndex = 0x04,  ///< Flag indicating whether the host port tuple has an associated suffix index.
        kHostPortControl_HasPort        = 0x08,  ///< Flag indicating whether the host port tuple has a port number.

        kHostPortType_FullyQualified    = 0x00,  ///< Flag indicating whether the host name is fully-qualified.
        kHostPortType_Indexed           = 0x01,  ///< Flag indicating whether the host name is index (i.e. has a suffix).
    };

    WEAVE_ERROR Get(const uint8_t *& elem, char *hostBuf, uint32_t hostBufSize, uint16_t& port) const;
    WEAVE_ERROR Skip(const uint8_t *& elem) const;
    WEAVE_ERROR GetSuffix(uint8_t index, char *buf, uint32_t bufSize, uint8_t& suffixLen) const;

 private:
    const uint8_t  *mElements;     ///< A read-only pointer to the host and port tuples list.
    const uint8_t  *mSuffixTable;  ///< A read-only pointer to the host suffix list.
    uint8_t         mCount;        ///< The number of host and port tuples in the list.
    uint8_t         mSuffixCount;  ///< The number of host suffixes in the list.
};

} /* namespace Weave */
} /* namespace nl */

#endif /* HOSTPORTLIST_H_ */


text:
blog
====

Nathan's writings


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Controller — Leap Motion JavaScript SDK v3.1 documentation</title>

    <link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1471552333.css" type="text/css" />

    <link rel="top" title="Leap Motion JavaScript SDK v3.1 documentation" href="../index.html" />
    <link rel="up" title="API Reference" href="Leap_Classes.html" />
    <link rel="next" title="Finger" href="Leap.Finger.html" />
    <link rel="prev" title="Bone" href="Leap.Bone.html" />

<link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

            Developer Portal

      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

      </button>

What's new

Getting Started

Documentation

 Examples

 Blog

 Community

      JavaScript

      Unity

      C#

      C++

      Java

      Python

      Objective-C

      Unreal

<form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()">

  <input type="search" results="5" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Controller¶

Attributes:

<tt class="xref js js-attr docutils literal">frameEventName</tt>

Functions:

<tt class="xref js js-func docutils literal">connect()</tt>

<tt class="xref js js-func docutils literal">connected()</tt>

<tt class="xref js js-func docutils literal">disconnect()</tt>

<tt class="xref js js-func docutils literal">frame()</tt>

<tt class="xref js js-func docutils literal">on()</tt>

<tt class="xref js js-func docutils literal">setBackground()</tt>

<tt class="xref js js-func docutils literal">setOptimizeHMD()</tt>

<tt class="xref js js-func docutils literal">streaming()</tt>

Events:

<tt class="xref js js-attr docutils literal">blur</tt>

<tt class="xref js js-attr docutils literal">connect</tt>

<tt class="xref js js-attr docutils literal">deviceAttached</tt>

<tt class="xref js js-attr docutils literal">deviceConnected</tt>

<tt class="xref js js-attr docutils literal">deviceDisconnected</tt>

<tt class="xref js js-attr docutils literal">deviceRemoved</tt>

<tt class="xref js js-attr docutils literal">deviceStopped</tt>

<tt class="xref js js-attr docutils literal">deviceStreaming</tt>

<tt class="xref js js-attr docutils literal">disconnect</tt>

<tt class="xref js js-attr docutils literal">focus</tt>

<tt class="xref js js-attr docutils literal">frame</tt>

<tt class="xref js js-attr docutils literal">gesture</tt>

<tt class="xref js js-attr docutils literal">frameEnd</tt>

<tt class="xref js js-attr docutils literal">protocol</tt>

<tt class="xref js js-attr docutils literal">streamingStarted</tt>

<tt class="xref js js-attr docutils literal">streamingStopped</tt>

Plugins:

<tt class="xref js js-func docutils literal">plugin()</tt>

<tt class="xref js js-func docutils literal">use()</tt>

<tt class="xref js js-func docutils literal">stopUsing()</tt>

class <tt class="descname">Controller</tt><big>(</big><big>)</big>¶

The Controller class is your main interface to the Leap Motion
Controller.

Create an instance of this Controller class to access frames of tracking
data and configuration information. Frame data can be polled at any time
using the <tt class="xref js js-func docutils literal">frame()</tt>
function. Call frame() or frame(0) to get the most recent frame. Set the
history parameter to a positive integer to access previous frames. A
controller stores up to 60 frames in its frame history.

When creating a Controller object, you may optionally pass in an options object
to set various controller properties.

var controller = new Leap.Controller({
  host: '127.0.0.1',
  port: 6437,
  frameEventName: 'animationFrame',
  useAllPlugins: true
});

The Leap Motion Controller class extends the Node.js EventEmitter <http://nodejs.org/api/events.html> class.

<col class="field-name" />
<col class="field-body" />

Arguments:

options (Object) –
An object containing the option values for this Controller:

<tt class="docutils literal">host</tt> — The host name or IP address of the WebSocket server providing
Leap Motion tracking data. Usually, this is the local host address: <tt class="docutils literal">127.0.0.1</tt>.

<tt class="docutils literal">port</tt> — The port on which the WebSocket server is listening. By default, this is
port <tt class="docutils literal">6437</tt>.

<tt class="docutils literal">enableGestures</tt> — Set to <tt class="docutils literal">true</tt> to enable gesture recognition. Omit or
set to <tt class="docutils literal">false</tt> if your application does not use gestures.

<tt class="docutils literal">background</tt> — Set to <tt class="docutils literal">true</tt> to enable this application to receive frames when not the foreground application.

<tt class="docutils literal">optimizeHMD</tt> — Set to <tt class="docutils literal">true</tt> to when mounting the Leap Motion hardware to a head-mounted display.

<tt class="docutils literal">frameEventName</tt> — The type of update loop to use for processing frame data.

<tt class="docutils literal">animationFrame</tt> uses the browser animation loop (generally 60 fps).

<tt class="docutils literal">deviceFrame</tt> runs at the Leap Motion controller frame rate (20 to 200 fps depending on the user’s settings and available computing power).

<tt class="docutils literal">useAllPlugins</tt> - False by default.

Tells the controller to use all plugins included on the page. For more
information, see https://github.com/leapmotion/leapjs/wiki/plugins.

<tt class="docutils literal">loopWhileDisconnected</tt> — Defaults to <tt class="docutils literal">true</tt>, which means the animation frame loop runs at all times. If you set this to <tt class="docutils literal">false</tt>, the animation loop does only runs when the <tt class="xref js js-class docutils literal">Controller()</tt> object is connected to the Leap Motion service and only when a new frame of data is available. Setting <tt class="docutils literal">loopWhileDisconnected</tt> to <tt class="docutils literal">false</tt> can minimize your app’s use of computing resources, but may irregularly slow down or stop any animations driven by the frame loop. Added in LeapJS version 0.4.3.

<tt class="descclassname">Controller.</tt><tt class="descname">frameEventName</tt>¶

<col class="field-name" />
<col class="field-body" />

Type:	string – either <tt class="docutils literal">"animationFrame"</tt> or <tt class="docutils literal">"deviceFrame"</tt>

Reports the type of update loop requested when this Controller was created.
Changing this value for an existing Controller object has undefined behavior.
Set the type of frame loop to use in the Controller object constructor function.

var loopType = controller.frameEventName;

<tt class="descclassname">Controller.</tt><tt class="descname">connect</tt><big>(</big><big>)</big>¶

Connects this Controller object to the Leap Motion WebSocket server. If the
connection succeeds, the controller can begin supplying tracking data. Use
the <tt class="xref js js-func docutils literal">frame()</tt> or <tt class="xref js js-func docutils literal">on()</tt> functions to access tracking data.

You can register callbacks with the <tt class="xref js js-func docutils literal">on()</tt> function to receive notification
when the connection succeeds.

<div id="frameID"></div>

var controller = new Leap.Controller();
var frameDisplay = document.getElementById('frameID');

this.controller.on('connect', function(){
   setInterval(function(){
      var frame = controller.frame();
      frameDisplay.innerHTML = '<p>Frame: ' + frame.id + ' is ' + (frame.valid ? 'valid.</p>' : 'invalid.</p>');
   }, 500);
});

controller.connect();

<col class="field-name" />
<col class="field-body" />

Returns:	<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0 and LeapJS 0.3.0

<tt class="descclassname">Controller.</tt><tt class="descname">connected</tt><big>(</big><big>)</big>¶

Reports whether this Controller is currently connected to the Leap Motion service.

<col class="field-name" />
<col class="field-body" />

Returns:	true or false

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.</tt><tt class="descname">disconnect</tt><big>(</big><big>)</big>¶

Disconnects from the WebSocket server. Call <tt class="xref js js-func docutils literal">connect()</tt> to reconnect this
controller object.

controller.disconnect();

<col class="field-name" />
<col class="field-body" />

Returns:	<tt class="xref js js-class docutils literal">Controller()</tt>

<tt class="descclassname">Controller.</tt><tt class="descname">frame</tt><big>(</big>[history]<big>)</big>¶

Returns a frame of tracking data from the Leap.

Use the optional history parameter to specify which frame to retrieve.
Call frame() or frame(0) to access the most recent frame; call frame(1)
to access the previous frame, and so on. If you use a history value
greater than the number of stored frames, then the controller returns an
invalid frame. When using the <tt class="docutils literal">animationFrame</tt> loop, only one Frame object
is stored per loop iteration. Any device frames occuring between iterations
are discarded.

var controller = Leap.loop({enableGestures:true}, function(frame){
    var currentFrame = frame;
    var previousFrame = controller.frame(1);
    var tenFramesBack = controller.frame(10);
});

<col class="field-name" />
<col class="field-body" />

Arguments:

history (int) – The age of the frame to return, counting backwards from the most recent
frame (0) into the past and up to the maximum age. The number of frames stored in the
history buffer is an implementation detail that may change in the future. Do not rely on
the current value (200).

Returns:
<tt class="xref js js-class docutils literal">Frame()</tt> – The specified frame; or, if no history
parameter is specified, the newest frame. If a frame is not available at the
specified history position, an invalid Frame is returned.

Leap Motion 1.0 and LeapJS 0.3.0

<tt class="descclassname">Controller.</tt><tt class="descname">inBrowser</tt><big>(</big><big>)</big>¶

Reports whether the the code is executing an a browser context.

controller.inBrowser();

<col class="field-name" />
<col class="field-body" />

Returns:	True, if running in a browser; false, if running in the Node platform.

Leap Motion 1.0.8 and LeapJS 0.3.0

<tt class="descclassname">Controller.</tt><tt class="descname">on</tt><big>(</big>eventName, callback<big>)</big>¶

Adds a callback function for one of the events dispatched by this Controller object. Defined in the Node.js EventEmitter. See emitter.on <http://nodejs.org/api/events.html#events_emitter_on_event_listener> for additional information. You can use the other EventEmitter classes, as well, but they are not described here.

<col class="field-name" />
<col class="field-body" />

Arguments:

eventName (string) –
One of the following:

<tt class="xref js js-attr docutils literal">blur</tt>

<tt class="xref js js-attr docutils literal">connect</tt>

<tt class="xref js js-attr docutils literal">deviceConnected</tt>

<tt class="xref js js-attr docutils literal">deviceDisconnected</tt>

<tt class="xref js js-attr docutils literal">disconnect</tt>

<tt class="xref js js-attr docutils literal">focus</tt>

<tt class="xref js js-attr docutils literal">frame</tt>

<tt class="xref js js-attr docutils literal">gesture</tt>

<tt class="xref js js-attr docutils literal">protocol</tt>

callback (function) –
A function to be called whenever the named event occurs.
Callbacks for the protocol, frame, and gesture events take arguments, the others do not.

var controller = new Leap.Controller();
controller.connect();

controller.on('frame', onFrame);
function onFrame(frame)
{
    console.log("Frame event for frame " + frame.id);
}

Returns:
<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.</tt><tt class="descname">setBackground</tt><big>(</big>state<big>)</big>¶

Informs the Leap Motion WebSocket server that your application always wants to receive frames of tracking data when it is in the background and not being actively used. Note that setting this option to true could lead to unintended input to your application while the user interacts with other applications. Most applications should not receive frames in the background.

Note that your application does not receive frames if another
Leap-enabled application is in the foreground, even when the background
frames policy is in effect. The policy only matters when a non-Leap-enabled app
has the operating system input focus.

controller.setBackground(true); //enable
controller.setBackground(false); //disable

<col class="field-name" />
<col class="field-body" />

Arguments:

state (boolean) – True to receive frames at all times; otherwise, false (the default).

Returns:
<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.</tt><tt class="descname">setOptimizeHMD</tt><big>(</big>state<big>)</big>¶

Informs the Leap Motion WebSocket server that your application expects the controller to be attached to a head-mounted display.

In the optimize for HMD mode, the Leap Motion software expects to view hands from the top rather than the bottom. When ambiguity exists whether the palm of a hand is facing toward or away from the Leap Motion sensors, setting this mode makes it more likely that the software will initialize the hand model so that it is facing away from the sensors.

<col class="field-name" />
<col class="field-body" />

Arguments:

state (boolean) – True to enable the optimize for HMD mode; otherwise, false (the default).

Returns:
<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 2.1.5 and LeapJS 0.6.2

<tt class="descclassname">Controller.</tt><tt class="descname">streaming</tt><big>(</big><big>)</big>¶

Reports whether this Controller is currently recieving tracking data from the Leap Motion service.

<col class="field-name" />
<col class="field-body" />

Returns:	true or false

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">blur</tt>¶

Dispatched when the browser page loses focus. Typically, this occurs when the user
changes tabs in a single browser window, but not, for example, when the user switches
to a different browser window or another application.

var controller = new Leap.Controller();
controller.connect();

controller.on('blur', onBlur);
function onBlur()
{
    console.log("Blur event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">connect</tt>¶

Dispatched when this controller establishes a connection to the Leap Motion WebSocket server.
This event does not mean that tracking data is available as Leap Motion tracking may be
paused by the user, or the device itself unplugged.

var controller = new Leap.Controller();
controller.connect();

controller.on('connect', onConnect);
function onConnect()
{
    console.log("Connect event");
}

<col class="field-name" />
<col class="field-body" />

Returns:	<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">deviceAttached</tt>¶

Dispatched when the Leap Motion device is plugged in or turned on.

All <tt class="docutils literal">device</tt> events include a device info object with the following information:

<colgroup>
<col width="33%" />
<col width="33%" />
<col width="33%" />
</colgroup>

name
type
values

attached
boolean
true or false

streaming
boolean
true or false

id
string
the device hardware ID

type
string

One of:

peripheral

keyboard

laptop

unknown

unrecognized

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceAttached', onAttached);
function onAttached()
{
    console.log("Device attached event");
}

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">deviceConnected</tt>¶

Dispatched when the Leap Motion device is plugged in and when tracking is unpaused by the user.

Note that this event is not dispatched if the controller is already plugged in when your
application starts.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceConnected', onDeviceConnected);
function onDeviceConnected(evt)
{
    console.log("Device Connect event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">deviceDisconnected</tt>¶

Dispatched when the Leap Motion device is unplugged and when tracking is paused by the user.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceDisconnected', onDeviceDisconnect);
function onDeviceDisconnect()
{
    console.log("Device disconnect event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">deviceRemoved</tt>¶

Dispatched when the Leap Motion device is unplugged or turned off.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceRemoved', onRemoved);
function onRemoved()
{
    console.log("Device removed event");
}

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">deviceStopped</tt>¶

Dispatched when the Leap Motion device stops providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceStopped', onStopped);
function onStopped()
{
    console.log("Device stopped streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">deviceStreaming</tt>¶

Dispatched when the Leap Motion device starts providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('deviceStreaming', onStreaming);
function onStreaming()
{
    console.log("Device started streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">disconnect</tt>¶

Dispatched when this Controller object disconnects from the Leap Motion WebSocket server.

var controller = new Leap.Controller();
controller.connect();

controller.on('disconnect', onDisconnect);
function onDisconnect()
{
    console.log("Disconnect event");
}

<col class="field-name" />
<col class="field-body" />

Returns:	<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">focus</tt>¶

Dispatched when the browser tab gains focus.

var controller = new Leap.Controller();
controller.connect();

controller.on('focus', onFocus);
function onFocus()
{
    console.log("Focus event");
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">frame</tt>¶

Dispatched once per update cycle.

If the <tt class="xref js js-attr docutils literal">frameEventName</tt> is <tt class="docutils literal">animationFrame</tt>, then
the browser animation loop is in use and this event is dispatched typically 60 times
per second. Since the animation loop timing does not match that of the Leap Motion device,
you may get the same Leap.Frame object more than once or skip frames.

If the <tt class="xref js js-attr docutils literal">frameEventName</tt> is <tt class="docutils literal">deviceFrame</tt>, then this event is dispatched as
each frame of Leap Motion data is received. The device frame rate can vary quite a bit
depending on the user’s settings and the available computing power.

Set the type of frame loop to use in the Controller object constructor function.

The current <tt class="xref py py-class docutils literal">Frame</tt> object is passed to your callback function.

var controller = new Leap.Controller();
controller.connect();

controller.on('frame', onFrame);
function onFrame(frame)
{
    console.log("Frame event for frame " + frame.id);
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">gesture</tt>¶

Notice Gestures are deprecated in version 3.0 and may not behave the same
as they did in earlier versions.

Dispatched for each gesture update in a frame.

The associated <tt class="xref py py-class docutils literal">Gesture</tt> and the current <tt class="xref py py-class docutils literal">Frame</tt> objects are passed to your
callback function.

When the Controller is using the <tt class="docutils literal">animationFrame</tt> loop, which is the default``, any gestures generated in device frames produced between iterations of the <tt class="docutils literal">animationFrame</tt> loop are collected and dispatched at the next iteration. This means that the Frame object passed to your gesture listener function will not always be the frame in which the gesture was recorded.  The position and other physical attributes of the hands and fingers making the gesture may have changed slightly between frames. In some cases, a Hand or Pointable object with the same IDs as those referenced by the Gesture object may not be present at all in the current frame.

var controller = new Leap.Controller({enableGestures:true});
controller.connect();

controller.on('gesture', onGesture);
function onGesture(gesture,frame)
{
    console.log(gesture.type + " with ID " + gesture.id + " in frame " + frame.id);
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">frameEnd</tt>¶

Dispatched when the frame of data has been fully constructed.

Use this callback for code that should run after the frame is available.

LeapJS 0.6.4

<tt class="descclassname">Controller.Event.</tt><tt class="descname">protocol</tt>¶

Dispatched when the WebSocket server and client have negotiated a protocol.

A Protocol object is passed to your callback function. Use the <tt class="docutils literal">version</tt> or
<tt class="docutils literal">versionLong</tt> attributes of this object to determine which protocol is in use,
which may be lower than the requested protocol if the user is running an older
version of the Leap Motion software.

var controller = new Leap.Controller();
controller.connect();

controller.on('protocol', onProtocol);
function onProtocol(protocol)
{
    console.log("Protocol event: " + protocol.version);
}

Leap Motion 1.0.9 and LeapJS 0.3.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">streamingStarted</tt>¶

Dispatched when the Leap Motion service/daemon starts providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('streamingStarted', onServiceStreaming);
function onServiceStreaming()
{
    console.log("Service started streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.Event.</tt><tt class="descname">streamingStopped</tt>¶

Dispatched when the Leap Motion service/daemon stops providing data.

var controller = new Leap.Controller();
controller.connect();

controller.on('streamingStopped', onServiceStopped);
function onServiceStopped()
{
    console.log("Service stopped streaming event");
}

Leap Motion 1.2 and LeapJS 0.5.0

<tt class="descclassname">Controller.</tt><tt class="descname">plugin</tt><big>(</big>pluginName, factory<big>)</big>¶

Registers a plugin, making is accessible to <tt class="docutils literal">controller.use()</tt> later on.

Valid keys for the object returned by the factory include <tt class="docutils literal">frame</tt>, <tt class="docutils literal">hand</tt>, <tt class="docutils literal">finger</tt>, and <tt class="docutils literal">pointable</tt>.
The value of each key can be either a function or an object.  If given a function, that function
will be called once for every instance of the object, with that instance injected as an
argument.  This allows decoration of objects with additional data:

Leap.Controller.plugin('testPlugin', function(options){
 return {
   frame: function(frame){
     frame.foo = 'bar';
   }
 }
});

When <tt class="docutils literal">hand</tt> is used, the callback is called for every hand object in <tt class="docutils literal">frame.hands</tt>.  Note that
hand objects are recreated with every new frame; any data saved on a hand does not
persist across frames.

Leap.Controller.plugin('testPlugin', function(){
 return {
   hand: function(hand){
     console.log('testPlugin running on hand ' + hand.id);
   }
 }
});

A factory can return an object to add custom functionality to Frames, Hands, or Pointables.
The methods defined by this returned object are added directly to the prototype of the specified class.
The Finger and Tool classes cannot be used here, Pointable must be used instead.
Use this technique for calculations that may not be necessary on every frame.
Memoization is also encouraged, for cases where the method may be called many times per frame by the application.

// This plug-in allows hand.usefulData() to be called later.
Leap.Controller.plugin('testPlugin', function(){
 return {
   hand: {
     usefulData: function(){
       console.log('usefulData on hand', this.id);
       // memoize the results onto the hand, preventing repeat work:
       this.x || (this.x = someExpensiveCalculation());
       return this.x;
     }
   }
 }
});

Note that the factory pattern gives encapsulation for every plugin instance.

Leap.Controller.plugin('testPlugin', function(options){
 options || (options = {});
 options.center || (options.center = [0,0,0]);

 privatePrintingMethod = function(){
   console.log('privatePrintingMethod - options', options);
 }

 return {
   pointable: {
     publicPrintingMethod: function(){
       privatePrintingMethod();
     }
   }
 }
});

<col class="field-name" />
<col class="field-body" />

Arguments:

pluginName (string) – The name string identifying a plugin.

factory (function) – A factory method which will return an instance of a plugin.
The factory itself receives an optional hash of options, passed in via <tt class="docutils literal">controller.use()</tt>.

Leap Motion 1.0 and LeapJS 0.4.0

<tt class="descclassname">Controller.</tt><tt class="descname">use</tt><big>(</big>pluginNameOrFactory[, options]<big>)</big>¶

Begin using a registered plugin.  The plugin’s functionality will be added to all frames
returned by the Controller object and any other specified objects within the frame.

The order of plugin execution inside the loop matches the order in which <tt class="docutils literal">use</tt> is called by the application.

The plugin is run for <tt class="docutils literal">animationFrames</tt> only.

<script src="http://js.leapmotion.com/leap-plugins-0.1.4.js"></script>
<script>
var controller = new Leap.Controller();
controller.use('handEntry');
controller.connect();
</script>

<col class="field-name" />
<col class="field-body" />

Arguments:

pluginNameOrFactory (string) – The registered name string of the plugin.  A plugin factory is also accepted
directly, for use in node environments.

options (hash) – Options to be passed to the plugin’s factory.

Returns:
<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0 and LeapJS 0.4.0

<tt class="descclassname">Controller.</tt><tt class="descname">stopUsing</tt><big>(</big>pluginName<big>)</big>¶

Stop using a used plugin.  Removes any of the plugin’s pipeline methods (those called on every frame)
and removes any methods added to extend class prototypes.

controller.stopUsing('handEntry');

<col class="field-name" />
<col class="field-body" />

Arguments:

pluginName (string) – The registered name string of the plugin.

Returns:
<tt class="xref js js-class docutils literal">Controller()</tt>

Leap Motion 1.0 and LeapJS 0.4.0

JavaScript Docs (v3.1)

API Overview

Guidelines

Application Development

Using the Tracking API

LeapJS Plug-ins

API Reference

Leap namespace

Bone

Controller

Finger

Frame

Hand

InteractionBox

Pointable

Matrix

Vector

Appendices

        Copyright © 2012 - 2016, Leap Motion, Inc.


text:
function ServiceSettings() {
    this.saveSettings = function() {
        var _self = this;

        this.settings.forEach(function(option) {
            if(option.password) {
                _self.setPassword(option.key, option.value);
            } else {
                _self.setSetting(option.key, option.value);
            }
        });
    };

    this.getSettings = function() {
        return this.settings;
    }

    this.getSetting = function(key) {
        return this._settings.get(this._name+'_'+key);
    }

    this.setSetting = function(key, value) {
        return this._settings.set(this._name+'_'+key, value);
    }

    this.getPassword = function(key) {
        return this._settings.getPassword(this._name+'_'+key);
    }

    this.setPassword = function(key, password) {
        return this._settings.setPassword(this._name+'_'+key, password);
    }

    // Loads settings at service initialization
    this.loadSettings = function() {
        var _self = this;
        this.settings.forEach(function(option) {
            if(option.password) {
                option.value = _self.getPassword(option.key);
            } else {
                option.value = _self.getSetting(option.key) || option.default;
            }
        });
    }
}

module.exports = ServiceSettings;


text:
package com.raizlabs.android.dbflow.processor.handler;

import com.raizlabs.android.dbflow.processor.model.ProcessorManager;

import javax.annotation.processing.RoundEnvironment;

/**
 * Description: The main base-level handler for performing some action when the
 * {@link javax.annotation.processing.Processor#process(java.util.Set, javax.annotation.processing.RoundEnvironment)} is called.
 */
public interface Handler {

    /**
     * Called when the process of the {@link javax.annotation.processing.Processor} is called
     *
     * @param processorManager The manager that holds processing information
     * @param roundEnvironment The round environment
     */
    public void handle(ProcessorManager processorManager, RoundEnvironment roundEnvironment);
}


text:
Website experimental para a disciplina de banco de dados do curso de TADS no IFRN.

Acesse esse repositório pelo link: http://victorlimeira.github.io/banco_dados_web/


text:
namespace phi {

template <typename T, dnnl::algorithm BINARY_OP>
void ElementwiseKernel(const OneDNNContext& dev_ctx,
                       const DenseTensor& x,
                       const DenseTensor& y,
                       int axis,
                       DenseTensor* out) {
  const auto& onednn_engine = dev_ctx.GetEngine();

  float scale_x = dev_ctx.HasDnnAttr("Scale_x")
                      ? PADDLE_GET_CONST(float, dev_ctx.GetDnnAttr("Scale_x"))
                      : 1;
  float scale_y = dev_ctx.HasDnnAttr("Scale_y")
                      ? PADDLE_GET_CONST(float, dev_ctx.GetDnnAttr("Scale_y"))
                      : 1;
  float scale_out =
      dev_ctx.HasDnnAttr("Scale_out")
          ? PADDLE_GET_CONST(float, dev_ctx.GetDnnAttr("Scale_out"))
          : 1;

  dnnl::post_ops post_operations;
  funcs::AppendActivation(dev_ctx, post_operations);

  auto* non_const_x = &x;
  auto* non_const_y = &y;

  funcs::BinaryOneDNNHandler<T> handler(BINARY_OP,
                                        axis,
                                        onednn_engine,
                                        dev_ctx.GetPlace(),
                                        non_const_x,
                                        non_const_y,
                                        out,
                                        scale_x,
                                        scale_y,
                                        scale_out,
                                        true,
                                        post_operations);

  // oneDNN's binary is optimized for broadcasting y into x, so in other case
  // we have to swap tensors to achieve optimal performance
  if (x.numel() < y.numel()) {
    std::swap(non_const_x, non_const_y);
  }

  const auto src_x_memory = handler.AcquireSrcMemory(non_const_x);
  const auto src_y_memory = handler.AcquireSecondSrcMemory(non_const_y);
  // (jczaja) For Inplace src and dst should be the same memory object.
  // So x should share buffer with z. But UT mechanics is testing inplace
  // execution for this op not checking that x can be bradcasted to match in
  // shape y tensor.
  // This is wrong as when x is to be broadcasted then z(out) will match the
  // shape of y which is bigger than x. Hence if x is smaller in shape than z
  // and they share a buffer (of
  // shape x) then this buffer is not big enough to hold result of elementwise
  // operation.
  const bool reuse_x_memory = non_const_x->numel() == out->numel() &&
                              non_const_x->IsSharedBufferWith(*out);
  std::shared_ptr<dnnl::memory> dst_memory;

  if (reuse_x_memory) {
    dst_memory = src_x_memory;
    // NOTE(chenfeiyu): when the output reuses memory from other tensor rather
    // than allocate its own, it's still need to take care of its data type.
    // Unfortunately, paddle's operator only infers the output' shape, but not
    // the data type. Alloc<T> takes care of allocation and data type
    // normally, but if the memory is already allocated and there is no need
    // to re-allocate, it just set the data type. So this it added there to
    // get the right data type.
    dev_ctx.template Alloc<T>(out);
  } else {
    dst_memory = handler.AcquireDstMemory(out);
  }

  const auto binary_prim = handler.AcquireForwardPrimitive();

  auto& astream = OneDNNContext::tls().get_stream();

  const std::unordered_map<int, dnnl::memory> args = {
      {DNNL_ARG_SRC_0, *src_x_memory},
      {DNNL_ARG_SRC_1, *src_y_memory},
      {DNNL_ARG_DST, *dst_memory}};

  binary_prim->execute(astream, args);
  astream.wait();

  if (handler.use_broadcasting_hack == false) {
    out->set_mem_desc(dst_memory->get_desc());
  } else {
    auto dims = dst_memory->get_desc().dims();
    dims.insert(dims.begin(), non_const_x->dims()[0]);
    dims[1] /= dims[0];
    out->set_mem_desc(dst_memory->get_desc().reshape(dims));
  }
}

#define DEFINE_ONEDNN_ELEMENTWISE_KERNEL(name, algorithm)      \
  template <typename T, typename Context>                      \
  void name##RawKernel(const Context& dev_ctx,                 \
                       const DenseTensor& x,                   \
                       const DenseTensor& y,                   \
                       int axis,                               \
                       DenseTensor* out) {                     \
    ElementwiseKernel<T, algorithm>(dev_ctx, x, y, axis, out); \
  }

DEFINE_ONEDNN_ELEMENTWISE_KERNEL(Divide, dnnl::algorithm::binary_div)

}  // namespace phi

PD_REGISTER_KERNEL(divide_raw,
                   OneDNN,
                   ONEDNN,
                   phi::DivideRawKernel,
                   float,
                   phi::dtype::bfloat16) {}


text:
from PyQt5.QtCore import QThread, pyqtSignal
import os

class DownloaderThread(QThread):
    downloadProgress = pyqtSignal(float)
    postprocessorProgress = pyqtSignal(float)

    def __init__(self, downloader, thread_id=None, parent=None):
        super().__init__(parent)
        self.downloader = downloader
        self._thread_id = thread_id

    def __del__(self):
        self.wait()

    def run(self):
        self.downloader.downloadProgress.connect(self.download_progress_received)
        self.downloader.postprocessorProgress.connect(self.postprocessor_progress_received)
        self.downloader.download()

    def download_progress_received(self, progress):
        self.downloadProgress.emit(progress)

    def postprocessor_progress_received(self, progress):
        self.postprocessorProgress.emit(progress)

    def stop(self):
        self._remove_tmp_files(self.downloader.temp_files)
        self.terminate()

    def _remove_tmp_files(self, filelist):
        for file in filelist:
            try:
                os.remove(file)
            except OSError:
                pass


text:
layout: post
status: publish
published: true
title: Back To The Beginning
author: Leask

author_login: leask
author_email: i@leaskh.com
author_url: https://leaskh.com
wordpress_id: 2075
wordpress_url: https://leaskh.com/?p=2075
date: '2013-10-18 16:41:44 +0800'
date_gmt: '2013-10-18 08:41:44 +0800'
categories:

tags: []
comments: []
---

Lyrics of "The Call"

It started out as a feeling

Which then grew into a hope

Which then turned into a quiet thought

Which then turned into a quiet word

And then that word grew louder and louder

'Til it was a battle cry

I'll come back when you call me

No need to say goodbye

Just because everything's changing

Doesn't mean it's never been this way before

All you can do is try to know who your friends are

As you head off to the war

Pick a star on the dark horizon and follow the light

You'll come back when it's over

No need to say goodbye

You'll come back when it's over

No need to say goodbye

Now we're back to the beginning

It's just a feeling and no one knows yet

But just because they can't feel it too

Doesn't mean that you have to forget

Let your memories grow stronger and stronger

'Til they're before your eyes

You'll come back when they call you

No need to say goodbye

You'll come back when they call you

No need to say goodbye


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <link rel="apple-touch-icon" href="/img/touch-icon.png">
  <title>Claryfy</title>

  <link href="css/materialize.min.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/normalize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

        <form id="subSearch" style="display: none">

            <input id="search" type="text" style="padding-left: 30px;" placeholder="Search..." required>

        </form>

SomeAlias
NDHS

Home

Tags

Logout

            SomeAlias

          NDHS

Alias

SomeAlias

School

Beijing National Day High School

            Send Private Message

        Copyright © 2015 Claryfy.com


text:
package com.ftfl.icareapplication.fragment;

import com.ftfl.icareapplication.R;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("NewApi")
public class NutationInformation extends Fragment {

	/*@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fregment_nutationinfo,
				container, false);

		TextView tvVaccineInfoTitel=(TextView) rootView.findViewById(R.id.tvNutationHealthTitel);
		//String mVeccineInfo=tvVaccineInfo.getText().toString();
		tvVaccineInfoTitel.setText(R.string.tv_NutationInfo_titel);

		TextView tvVaccineInfo=(TextView) rootView.findViewById(R.id.tvNutationHealthinfo);
		//String mVeccineInfo=tvVaccineInfo.getText().toString();
		tvVaccineInfo.setText(R.string.tv_NutaionfregmentInfo);
		return rootView;
	}*/
}


text:
class ListingZombiesTest < ActionDispatch::IntegrationTest
	test 'returns zombies in JSON' do
		get '/zombies', {}, { 'Accept' => Mime::JSON }
		assert_equal 200, response.status
		assert_equal Mime::JSON, response.content_type
	end

	test 'returns zombies in XML' do
		get '/zombies', {}, { 'Accept' => Mime::XML }
		assert_equal 200, response.status
		assert_equal Mime::XML, response.content_type
	end
end

# => app/controllers/zombies_controller.rb
class ZombiesController < ApplicationController
	def index
		zombies = Zombie.all

		respond_to do |format|
			format.json { render json: zombies, status: 200 }
			fromat.xml { render json: zombies, status: 200 }
		end
	end
end


text:
package com.microsoft.azure.management.mediaservices.v2018_07_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The HLS configuration.
 */
public class Hls {
    /**
     * The amount of fragments per HTTP Live Streaming (HLS) segment.
     */
    @JsonProperty(value = "fragmentsPerTsSegment")
    private Integer fragmentsPerTsSegment;

    /**
     * Get the amount of fragments per HTTP Live Streaming (HLS) segment.
     *
     * @return the fragmentsPerTsSegment value
     */
    public Integer fragmentsPerTsSegment() {
        return this.fragmentsPerTsSegment;
    }

    /**
     * Set the amount of fragments per HTTP Live Streaming (HLS) segment.
     *
     * @param fragmentsPerTsSegment the fragmentsPerTsSegment value to set
     * @return the Hls object itself.
     */
    public Hls withFragmentsPerTsSegment(Integer fragmentsPerTsSegment) {
        this.fragmentsPerTsSegment = fragmentsPerTsSegment;
        return this;
    }

}


text:
require File.expand_path("../../test_helper", __FILE__)

module Unit
  class TestGemExt < MiniTest::Unit::TestCase

    describe "lib/motion-bundler/gem_ext.rb" do
      it "should required after having required MotionBundler" do
        assert_equal true, $LOADED_FEATURES.include?(motion_bundler_file "motion-bundler/gem_ext.rb")
      end

      it "should override Motion::Project::Config#files_dependencies in order to tackle absolute paths" do
        config = Motion::Project::Config.new
        config.instance_variable_set :@files, %w(/Users/paulengel/foo.rb /Users/paulengel/bar.rb /Users/paulengel/fubar.rb)
        config.instance_variable_set :@dependencies, Hash.new
        assert config.files_dependencies("/Users/paulengel/foo.rb" => %w(/Users/paulengel/bar.rb))
        assert_raises RuntimeError do
          config.files_dependencies "foo" => %w(bar.rb)
        end
      end
    end

  end
end


text:
Collection of some android develop tools class

* LogUtil
  * Facilitate management of the log in whole project
* DeviceUtils
  * validate the mobile phone number (china)


text:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

	/**
	* ONLY FOR THIS CLASS (self)
	*   parse_attr($attributes) -> Parse out the attributes
	*
	* @static
	* @access	private
	* @param	mixed - An array or string for parse the specified attributes
	* @return	string The parsed attribute (attribute="value")
	*/
	function parse_attr($attributes) {
		if (is_string($attributes)) {
			return (!empty($attributes)) ? ' ' . trim($attributes) : '';
		}

		if (is_array($attributes)) {
			$attr = '';

			foreach ($attributes as $key => $val) {
                            if($key=='checked' AND $val==''){
                                continue;
                            }
				$attr .= ' ' . $key . '="' . $val . '"';
			}

			return $attr;
		}
	}

	/**
	 * ONLY FOR THIS CLASS (self)
	 * HTML::parse_fields($fields) -> Parse the $fields array and transform into a valid HTML input
	 *
	 * @static
	 * @access private
	 * @param  array $fields An array with the following structure -> 'Type' => array($attributes)
	 * @return string The parsed input HTML
	 */
	function parse_fields($fields, $content = '') {
		if (is_array($fields)) {
			$field = '';$label='';
			foreach ($fields as $key => $val) {
                             	$attributes =   parse_attr($val);

                                if(strlen ( $key ) > 1){ $label = ''.$key.' '; }else{ $label = ''; }
                                if(!empty($content)){
        				$field .= '
'.$label.'<input ' . $attributes . ' />
' . PHP_EOL;
                                }else{
        				$field .= $label.'<input ' . $attributes . ' />' . PHP_EOL;
                                }
			}

			return $field;
		}
	}

	/**
	 * ONLY FOR THIS CLASS (self)
	 *   list_item($items) -> Returns a

 tag parsed with the value in the array ($items = array)
	 *
	 * @static
	 * @access private
	 * @param  array $items The array with a list to transform into a

 tag
	 * @param  string $class A class for the items
	 * @return string The complete

 tag
	 */
	function list_item($items, $class = null) {
		if (is_array($items)) {
			$class = (isset($class) && !empty($class)) ? ' class="' . $class . '"': null;
			$li = '';
			$i = 0;

			foreach ($items as $key => $val) {
				$i++;
				$li .= '
' . PHP_EOL . $val . PHP_EOL . '
' . PHP_EOL;
			}

			return $li;
		}
	}

	/**
	 * ONLY FOR THIS CLASS (self)
	 *   filter description
	 *
	 * @static
	 * @access 	private
	 * @param  	string $str The input string to filter
	 * @param  	string $mode The filter mode
	 * @return 	mixed May return the filtered string or may return null if the $mode variable isn't set
	 */
	function filter($str, $mode) {
		switch($mode) {
			case 'strip':
				/* HTML tags are stripped from the string
				before it is used. */
				return strip_tags($str);
			case 'escapeAll':
				/* HTML and special characters are escaped from the string
				before it is used. */
				return htmlentities($str, ENT_QUOTES, 'UTF-8');
			case 'escape':
				/* Only HTML tags are escaped from the string. Special characters
				is kept as is. */
				return htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8');
			case 'url':
				/* Encode a string according to RFC 3986 for use in a URL. */
				return rawurlencode($str);
			case 'filename':
				/* Escape a string so it's safe to be used as filename. */
				return str_replace('/', '-', $str);
			default:
				return null;
		}
	}

	/**
	 * Generates a HTML document type
	 *
	 * @static
	 * @access 	public
	 * @param 	string $type Type of the document
	 * @return 	string
	 */
	function Doctype($type = 'html5') {
		$doctypes = array(
			'html5'			=> '<!DOCTYPE html>',
			'xhtml11'		=> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
			'xhtml1-strict'	=> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
			'xhtml1-trans'	=> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
			'xhtml1-frame'	=> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
			'html4-strict'	=> '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
			'html4-trans'	=> '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
			'html4-frame'	=> '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
		);

		if (isset($doctypes[strtolower($type)])) {
			return $doctypes[$type] . "\n";
		}
		else {
			return '';
		}
	}

	/**
	 * Creates the  tag
	 *
	 * @static
	 * @access 	public
	 * @param 	string $src Where is the image?
	 * @param 	mixed $attributes Custom attributes (must be a valid attribute for the  tag)
	 * @return 	string The formated  tag
	 */
	function Image($src, $attributes = '') {
		if (isset($attributes) && !empty($attributes)) {
			$attributes =   parse_attr($attributes);
		}

		$border = (isset($attributes['border']) && !empty($attributes['border'])) ? $attributes['border'] . ' ' : 'border="0" ';
		$alt = (isset($attributes['alt']) && !empty($attributes['alt'])) ? $attributes['alt'] . ' ' : 'alt="" ';

		return '';
	}

	/**
	 * Creates a HTML Anchor link
	 *
	 * @static
	 * @access 	public
	 * @param 	string $url the URL
	 * @param 	string $label the link value
	 * @param 	mixed $attributes Custom attributes (must be a valid attribute for the  tag)
	 * @return 	string The formated  tag
	 */
	function Url($url, $label = null, $attributes = null) {
		$label = (!empty($label)) ? $label : $url;

		if (isset($attributes) && !empty($attributes)) {
			$attributes = parse_attr($attributes);
		}

		return '' . $label . '';
	}

	/**
	 * Generates a "mailto" link
	 *
	 * @static
	 * @access 	public
	 * @param 	$email
	 * @param 	string $label The anchor value.
	 * @param 	mixed $attributes Custom attributes (must be a valid attribute for the  tag)
	 * @return 	string The formated  tag with the 'href' attribute set for: mailto:$email
	 */
	function Email($email, $label = null, $attributes = null)	{
		$label = (!empty($label)) ? $label : $email;

		if (isset($attributes) && !empty($attributes)) {
			$attributes = parse_attr($attributes);
		}

		$html = '' . $label . '';
		return $html;
	}

	/**
	 * HTML
 tag
	 *
	 * @static
	 * @access 	public
	 * @param 	int $count How many line breaks?
	 * @return 	string
	 */
	function LineBreak($count = 1, $attributes = null) {
            	if (isset($attributes) && !empty($attributes)) {
                    $attributes =   parse_attr($attributes);
		}
		return str_repeat('
', $count) . PHP_EOL;
	}

         function lineBreak2($count = 1, $attributes = null) {
            	if (isset($attributes) && !empty($attributes)) {
                    $attributes =   parse_attr($attributes);
		}
		return str_repeat('
', $count) . PHP_EOL;
	}

	/**
	 * Returns non-breaking space entities
	 *
	 * @static
	 * @access 	public
	 * @param 	int $count How many spaces?
	 * @return 	string
	 */
	 function Space($count = 1) {
//		return str_repeat(' ', $count);
            $output = '';
            for ($index = 0; $index < $count; $index++) {
                $output .= ' ';
            }
            return $output;
	}

	/**
	 * HTML::Form() -> Creates the <form> tag with the specified variables.
	 *
	 * @static
	 * @access 	public
	 * @param 	string $action The action attribute value.
	 * @param 	array $fields What is the form fields?
	 * @param 	string $name The form name
	 * @param 	string $method The form method (post or get)
	 * @param 	string $enctype The form enctype
	 */
	 function Form($action, $fields, $content = '', $fields2='', $fields3='', $arrattributes = array() , $name = null, $method = 'post', $enctype = 'multipart/form-data') {
		$name = (isset($name) && !empty($name)) ? ' name="' . $name . '"' : null;
		$method = (isset($method)) ? ' method="' . $method . '"': null;
		$enctype = (isset($enctype)) ? ' enctype="' . $enctype . '"': null;

                $attributes =   parse_attr($arrattributes);

		$html = '<form action="' . $action . '"' . $name . $method . $enctype . $attributes . '>' . PHP_EOL;
                $html .= $fields2;
		$html .=   parse_fields($fields, $content);
		$html .= $fields3;
		$html .= '</form>' . PHP_EOL;

		return $html;
	}

	 function Form1($fields, $arrattributes = array() ,$method = 'post', $enctype = 'multipart/form-data') {
            $name = (isset($name) && !empty($name)) ? ' name="' . $name . '"' : null;
            $method = (isset($method)) ? ' method="' . $method . '"': null;
            $enctype = (isset($enctype)) ? ' enctype="' . $enctype . '"': null;
            $attributes =   parse_attr($arrattributes);
            $html = '<form '.$attributes. $method . $enctype . '>' . PHP_EOL;
            $html .=   parse_fields($fields);
            $html .= '</form>' . PHP_EOL;
            return $html;
        }

         function tablethead($arrData){
            $output = '

';
            foreach ($arrData as $th) {
                $output.=''.$th.'	';
            }
            $output.='

';
            return $output;
        }

	/**
	 * HTML::Open('tag') -> Opens a HTML tag
	 *
	 * @static
	 * @access 	private
	 * @param 	string $tag Which tag we're gonna open?
	 * @param 	mixed $attributes Custom attributes (must be a valid attribute for the specified tag)
	 * @param 	array $li_items Some array with items for
 or
 tags
	 * @return 	string Return the opened tag (<$tag>)
	 */
	 function Open($tag, $attributes = null, $li_items = array()) {
		  $tag = strtolower($tag);

		if (isset($attributes) && !empty($attributes)) {
			$attributes =   parse_attr($attributes);
		}

		if ($tag == 'ul' || $tag == 'ol') {
			if (!empty($attributes['li_class'])) {
				$list =   list_item($li_items, $attributes['li_class']);
				return '<' .   $tag . $attributes . '>' . PHP_EOL . $li_items;
			} else {
				$list =   list_item($li_items);
				return '<' .   $tag . $attributes . '>' . PHP_EOL . $li_items;
			}
		}

		return '<' .   $tag . $attributes . '>' ;
	}

	function tagcontent($tag, $content = '', $attributes = '') {
            $output = '';
		  $tag = strtolower($tag);

		if (isset($attributes) && !empty($attributes)) {
			$attributes =   parse_attr($attributes);
		}
		$output .= '<' .   $tag . $attributes . '>' ;
                    $output .= $content;
                $output .= '</' .   $tag . $attributes . '>' ;
                return $output;
	}

	/**
	 * HTML::Close() -> Close the current open tag
	 *
	 * @static
	 * @access 	public
	 */
	 function Close($tag) {
             $tag = strtolower($tag);
		return '</' .   $tag . '>' ;
	}

        /**
	 * HTML::Close() -> Close the current open tag
	 *
	 * @static
	 * @access 	public
	 */
	 function closeTag($ptag) {
              $tag = strtolower($ptag);
		return PHP_EOL . '</' .   $tag . '>' . PHP_EOL;
	}

         function csslink($srcarray){
            $output = '';
            foreach ($srcarray as $val) {
                $output .= '<link href="'.$val.'" rel="stylesheet">';
            }
            return $output;
        }

         function jsload($srcarray){
            $output = '';
            foreach ($srcarray as $val) { $output .= ''; }
            return $output;
        }

         function tabs($tabsarray, $attributes){
            $output = '';
		if (isset($attributes) && !empty($attributes)) {
			$attributes =   parse_attr($attributes);
		}
                $output.='
';
                    foreach ($tabsarray as $id => $label) {
                        $liattributes =   parse_attr($label);
                            $output.='
'.$label['label'].'
';
                    }
                $output.='
';
            return $output;
        }

        function inputGroup($checkbox, $attributes, $attrlabel = array('class'=>'btn btn-primary'), $attrdiv = array('class'=>'btn-group', 'data-toggle'=>'buttons')){
            $output = ''; $input = '';
		if (isset($attributes) && !empty($attributes)) { $attributes =   parse_attr($attributes); }

                $output .=   Open('div', $attrdiv);
                    foreach ($checkbox as $label) {
                        $input .= '<input '.$attributes.'> '.$label;
                            $output .=   tagcontent('label', $input, $attrlabel);
                    }
                $output .=   closeTag('div');
            return $output;
        }

         function input($attributes){
            $output = '';
		if (isset($attributes) && !empty($attributes)) { $attributes =   parse_attr($attributes); }
                    $output .= '<input '.$attributes.'/>';
            return $output;
        }

        function combobox( $data, $optattr = null, $comboattr = null, $elem1 = false, $selected = '' ){
        $combo_opt = '';
        $opt_label = $optattr['label'];
//        echo $opt_label;
        $opt_value = $optattr['value'];
        $cont = 0;
            foreach ($data as $g) {
                if( $elem1 AND $cont == 0 ){
                    $combo_opt .= tagcontent('option', 'Seleccionar -- ', array('value'=>'-1'));
                    $cont ++;
//                    continue;
                }

                if( $selected != '' AND $selected == $g->$opt_value ){
                    $combo_opt .= tagcontent('option', $g->$opt_label, array('value'=>$g->$opt_value,'selected'=>''));
                    $cont ++;
                    continue;
                }
                $combo_opt .= tagcontent('option', $g->$opt_label, array('value'=>$g->$opt_value));
                $cont ++;
            }
            $combobox = tagcontent('select', $combo_opt, $comboattr);

            return $combobox;
        }

        function combobox_array( $data, $comboattr = null, $elem1 = false, $selected = '' ){
        $combo_opt = '';
//        $opt_label = $optattr['label'];
//        echo $opt_label;
//        $opt_value = $optattr['value'];
        $cont = 0;
            foreach ($data as $g) {
                if( $elem1 AND $cont == 0 ){
                    $combo_opt .= tagcontent('option', 'Seleccionar -- ', array('value'=>'-1'));
                    $cont ++;
//                    continue;
                }

                if( $selected != '' AND $selected == $g ){
                    $combo_opt .= tagcontent('option', $g, array('value'=>$g,'selected'=>''));
                    $cont ++;
                    continue;
                }
                $combo_opt .= tagcontent('option', $g, array('value'=>$g));
                $cont ++;
            }
            $combobox = tagcontent('select', $combo_opt, $comboattr);

            return $combobox;
        }


text:
package com.ecwid.consul.v1.acl;

import java.util.List;

import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.acl.model.Acl;
import com.ecwid.consul.v1.acl.model.NewAcl;
import com.ecwid.consul.v1.acl.model.UpdateAcl;

/**
 * @author Vasily Vasilkov (vgv@ecwid.com)
 */
public interface AclClient {
	Response<String> aclCreate(NewAcl newAcl, String token);

	Response<Void> aclUpdate(UpdateAcl updateAcl, String token);

	Response<Void> aclDestroy(String aclId, String token);

	Response<Acl> getAcl(String id);

	Response<String> aclClone(String aclId, String token);

	Response<List<Acl>> getAclList(String token);
}


text:
'use strict';
var expressTask = require('web-ui/boot/express-task'),
    serverTask = require('web-ui/boot/server-task');

exports = module.exports = function() {
	var app = expressTask();
	serverTask(app);
};


text:
require 'rails_helper'

describe DiscussionProcessingJob do
  it "should process the job successfully" do
  	DiscussionProcessingJob.extend(Module.new { def award_teamplayer id ; end ; def award_proactive_comments id, qid; end; def increase_notification_pointer i; end})
  	@user = FactoryGirl.create(:user)
  	@a_user = FactoryGirl.create(:user)
  	@p_user = FactoryGirl.create(:user)
  	@d_user = FactoryGirl.create(:user)
  	@project = FactoryGirl.create(:project)
  	@p_user.projects.push @project
  	@discussion = FactoryGirl.create(:discussion, discussable_type: "Project", discussable_id: @project.id, user_id: @user.id)
  	$redis.sadd @discussion.followers_key, @d_user.id
    @activity = FactoryGirl.create(:activity, user_id: @a_user.id)
  	DiscussionProcessingJob.perform @activity.id, @discussion.id
  	expect(@user.notifications).to include @activity.id.to_s
  	expect(@p_user.feed).to include @activity.id.to_s
  	expect(@d_user.notifications).to include @activity.id.to_s
  end
end