text:
require 'rspec'
require 'arangodb.rb'

describe ArangoDB do

  context "dealing with the admin interface:" do

    before do
      # load the most current routing information
      cmd = "/_admin/routing/reload"
      ArangoDB.get(cmd)
    end

################################################################################
## load some routing
################################################################################

    context "dealing with the routing" do
      before do
        @id = nil
      end

      after do
        if @id != nil
          ArangoDB.delete("/_api/document/" + @id)
        end
      end

      it "checks a simple routing" do
        cmd = "/_api/document?collection=_routing"
        body = "{ \"url\" : { \"match\" : \"\/hello\/world\" }, \"content\" : { \"contentType\" : \"text\/html\", \"body\": \"moo!\" } }"
        doc = ArangoDB.log_post("api-routing-simple", cmd, :body => body)

        doc.code.should eq(202)
        @id = doc.parsed_response['_id']

        cmd = "/_admin/routing/reload"
        doc = ArangoDB.log_get("api-routing-simple", cmd)

        # we need this because reloading the routing is asynchronous
        sleep(3)

        cmd = "/hello/world"
        doc = ArangoDB.log_get("api-routing-simple", cmd, :format => :plain)

        # check response code
        doc.code.should eq(200)
        # check whether HTML result contains expected title
        doc.response.body.should include("moo!")
      end

    end

################################################################################
## /_admin/echo
################################################################################

    context "checks /_admin/echo" do

      prefix = "api-system"

      it "using GET" do
        cmd = "/_admin/echo"
        doc = ArangoDB.log_get("#{prefix}-echo", cmd)

        doc.code.should eq(200)
        doc.parsed_response['url'].should eq("/_admin/echo")
        doc.parsed_response['path'].should eq("/")
        doc.parsed_response['parameters'].should eq({})
        doc.parsed_response['requestType'].should eq("GET")
      end

      it "using GET, with query parameter" do
        cmd = "/_admin/echo?a=1"
        doc = ArangoDB.log_get("#{prefix}-echo", cmd)

        doc.code.should eq(200)
        doc.parsed_response['url'].should eq("/_admin/echo?a=1")
        doc.parsed_response['path'].should eq("/")
        doc.parsed_response['parameters'].should eq({ "a" => "1" })
        doc.parsed_response['requestType'].should eq("GET")
      end

      it "using POST, with query parameters" do
        cmd = "/_admin/echo?a=1&b=2&foo[]=bar&foo[]=baz"
        body = "{\"foo\": \"bar\", \"baz\": { \"bump\": true, \"moo\": [ ] } }"
        doc = ArangoDB.log_post("#{prefix}-echo", cmd, :body => body)

        doc.code.should eq(200)
        doc.parsed_response['url'].should eq("/_admin/echo?a=1&b=2&foo[]=bar&foo[]=baz")
        doc.parsed_response['path'].should eq("/")
        doc.parsed_response['parameters'].should eq( { "a"=>"1", "b"=>"2", "foo"=>["bar", "baz"] } )
        doc.parsed_response['requestType'].should eq("POST")
        doc.parsed_response['requestBody'].should eq("{\"foo\": \"bar\", \"baz\": { \"bump\": true, \"moo\": [ ] } }")
      end

      it "using PUT, with headers" do
        cmd = "/_admin/echo?"
        body = "{ }"
        headers = { "X-Foo" => "Bar", "x-meow" => "mOO" }
        doc = ArangoDB.log_put("#{prefix}-echo", cmd, :body => body, :headers => headers)

        doc.code.should eq(200)
        doc.parsed_response['url'].should eq("/_admin/echo?")
        doc.parsed_response['path'].should eq("/")
        doc.parsed_response['parameters'].should eq({ })
        doc.parsed_response['requestType'].should eq("PUT")
        doc.parsed_response['requestBody'].should eq("{ }")
      end

    end

################################################################################
## check whether admin interface is accessible
################################################################################

    context "dealing with the admin interface:" do

      it "checks whether the admin interface is available at /_admin/aardvark/index.html" do
        cmd = "/_admin/aardvark/index.html"
        begin
          ArangoDB.log_get("admin-interface-get", cmd, :format => :plain, :no_follow => true)
        rescue HTTParty::RedirectionTooDeep => e
          # check response code
          e.response.code.should eq("302")
        end
      end

      it "checks whether the admin interface is available at /" do
        cmd = "/"
        begin
          ArangoDB.log_get("admin-interface-get", cmd, :format => :plain, :no_follow => true)
        rescue HTTParty::RedirectionTooDeep => e
          # check response code
          e.response.code.should eq("301")
          e.response.header['location'].should =~ /^\/.*\/*_admin\/aardvark\/index.html$/
        end
      end

      it "checks whether the admin interface is available at /_admin/html" do
        cmd = "/_admin/html"
        begin
          ArangoDB.log_get("admin-interface-get", cmd, :format => :plain, :no_follow => true)
        rescue HTTParty::RedirectionTooDeep => e
          # check response code
          e.response.code.should eq("301")
          e.response.header['location'].should =~ /\/_admin\/aardvark\/index.html$/
        end
      end

      it "checks whether the admin interface is available at /_admin/html/" do
        cmd = "/_admin/html/"
        begin
          ArangoDB.log_get("admin-interface-get", cmd, :format => :plain, :no_follow => true)
        rescue HTTParty::RedirectionTooDeep => e
          # check response code
          e.response.code.should eq("301")
          e.response.header['location'].should =~ /\/_admin\/aardvark\/index.html$/
        end
      end

      it "checks whether the admin interface is available at /_admin/aardvark/" do
        cmd = "/_admin/aardvark/"
        begin
          ArangoDB.log_get("admin-interface-get", cmd, :format => :plain, :no_follow => true)
        rescue HTTParty::RedirectionTooDeep => e
          # check response code
          e.response.code.should eq("307")
          e.response.header['location'].should =~ /\/_admin\/aardvark\/index.html$/
        end
      end

    end

  end

end


text:
/*global describe, it, before, after */
var should = require('should');
var telldus = require('..');
var utils = require('./utils');

describe('sync methods', function(){

  before(function () {
    this.devices = telldus.getDevicesSync();
  });

  after(function(){
    utils.cleanUp(this.devices);
  });

  describe('config related', function(){

    var deviceId;

    before(function () {
      deviceId = telldus.addDeviceSync();
    });

    it('getDevicesSync', function () {
      var devices = telldus.getDevicesSync();

      //if devices is zero length then
      //telldusd is probably not running
      devices.length.should.be.above(0);

      //set the environment variable VERBOSE to something if
      //you want to output the devices
      if (typeof process.env.VERBOSE !== 'undefined') {
        console.log(devices);
      }

      var dev1 = devices[0];
      dev1.should.have.property('name');
      dev1.should.have.property('methods');
      dev1.should.have.property('model');
      dev1.should.have.property('type');
      dev1.should.have.property('status');
      //test status
      dev1.status.should.have.property('name');

      //test methods
      var methods = dev1.methods;
      methods.should.be.an.instanceOf(Array);
      methods.should.include('TURNON');
      methods.should.include('TURNOFF');
    });

    it('addDeviceSync', function () {
      var id = telldus.addDeviceSync();
      should.exist(id);
      id.should.be.above(0);
    });

    it('getNameSync', function () {
      var result = telldus.getNameSync(1);
      result.should.not.equal('');
      result.should.not.equal('UNKNOWN');
    });

    it('getNameSync with new device and return ""', function () {
      var name = telldus.getNameSync(deviceId);
      name.should.equal('');
    });

    it('getNameSync with bad device and return UNKNOWN', function () {
      var result = telldus.getNameSync(utils.NON_EXISTING_DEVICE);
      result.should.equal('UNKNOWN');
    });

    it('setNameSync', function () {
      var setResult = telldus.setNameSync(deviceId, 'Newly created');
      var name = telldus.getNameSync(deviceId);
      name.should.equal('Newly created');
      setResult.should.equal(true, 'set worked but did still return error');
    });

    it('setNameSync with bad device and return false', function () {
      var setResult = telldus.setNameSync(utils.NON_EXISTING_DEVICE, 'Bad ! ');
      setResult.should.equal(false);
    });

    it('getProtocolSync', function () {
      var p = telldus.getProtocolSync(1);
      p.should.not.equal('');
      p.should.not.equal('UNKNOWN');
      utils.VALID_PROTOCOLS.should.include(p);
    });

    it('getProtocolSync with bad device and return UNKNOWN', function () {
      var p = telldus.getProtocolSync(utils.NON_EXISTING_DEVICE);
      p.should.equal('UNKNOWN'); //newly created device does not have a name.
    });

    it('getProtocolSync with new device and return ""', function () {
      var p = telldus.getProtocolSync(deviceId);
      p.should.equal(''); //newly created device does not have a name.
    });

    it('setProtocolSync', function () {
      var result = telldus.setProtocolSync(deviceId, utils.VALID_PROTOCOLS[0]);
      result.should.be.equal(true);
      var p = telldus.getProtocolSync(deviceId); //now it should have
      p.should.equal(utils.VALID_PROTOCOLS[0]);
    });

    it('getModelSync', function () {
      var result = telldus.getModelSync(1);
      result.should.not.equal('UNKNOWN');
      result.should.not.equal('');
      utils.VALID_MODELS.should.include(result);
    });

    it('getModelSync with bad device and get UNKNOWN', function () {
      var result = telldus.getModelSync(utils.NON_EXISTING_DEVICE);
      result.should.equal('UNKNOWN');
    });

    it('getModelSync with new device and get ""', function () {
      var result = telldus.getModelSync(deviceId);
      result.should.equal('');
    });

    it('setModelSync', function () {
      var r = telldus.setModelSync(deviceId, utils.VALID_MODELS[0]);
      r.should.equal(true);
      r = telldus.getModelSync(deviceId);
      r.should.equal(utils.VALID_MODELS[0]);
    });

    it('getDeviceTypeSync', function () {
      var r = telldus.getDeviceTypeSync(1);
      r.should.be.within(1, 3);
    });

    it('getDeviceParameterSync', function() {
      var result = telldus.getDeviceParameterSync(deviceId, 'house', 'testdefault');
      result.should.equal('testdefault');
    });

    it('setDeviceParameterSync', function() {
      var result = telldus.setDeviceParameterSync(deviceId, 'house', '12345');
      result.should.equal(true);
    });

    it('getNumberOfDevicesSync', function () {
      var result = telldus.getNumberOfDevicesSync();
      result.should.be.within(this.devices.length, this.devices.length + 3);
    });

    it('getDeviceIdSync', function(){
      var result = telldus.getDeviceIdSync(0);
      result.should.equal(1);

      result = telldus.getDeviceIdSync(9999);
      result.should.equal(-1);
    });

    it('removeDeviceSync', function () {
      var r = telldus.removeDeviceSync(deviceId);
      r.should.be.equal(true);
    });

  });//config related

  describe('actions', function(){

    var dimmerId;

    before(function (){
      //create a dimmer device
      dimmerId = utils.addDimmerSync();
    });

    it('turnOffSync', function () {
      var device = this.devices[0];
      var returnValue = telldus.turnOffSync(device.id);
      returnValue.should.be.equal(0);
      //refresh
      device = telldus.getDevicesSync()[0];
      device.status.should.have.property('name', 'OFF');
    });

    it('turnOnSync', function () {
      var device = this.devices[0];
      var returnValue = telldus.turnOnSync(device.id);
      returnValue.should.be.equal(0);
      //refresh
      device = telldus.getDevicesSync()[0];
      device.status.should.have.property('name', 'ON');
    });

    it('dimSync should dim', function() {
      telldus.dimSync(dimmerId, 75);
      var devices = telldus.getDevicesSync();
      var found=false;
      for (var i=0; i<devices.length; i++){
        if (devices[i].id === dimmerId) {
          var d = devices[i];
          d.status.should.have.property('name', 'DIM');
          d.status.should.have.property('level', 75);
          found=true;
        }
      }
      found.should.be.equal(true);
    });

    it('learn should learn...', function(){
      var result = telldus.learnSync(dimmerId);
      result.should.equal(telldus.enums.status.TELLSTICK_SUCCESS);

    });

  });

  describe('support events', function () {

    it('deviceEventListener', function (done) {
      var seconds = 5; // for how many seconds should we wait for an aevent
      this.timeout(seconds * 1000 + 1000);
      var count = 0;

      //listen and wait for something
      var listener = telldus.addDeviceEventListener(function (deviceId, evt) {
        if (typeof process.env.VERBOSE !== 'undefined') {
          console.log('device:%s, event:%j', deviceId, evt);
        }
        deviceId.should.be.above(0);
        evt.should.have.property('name', 'ON');
        count++;
      });

      listener.should.be.above(0);

      //send a device event
      telldus.turnOn(1);

      setTimeout(function () {
        var returnValue = telldus.removeEventListenerSync(listener);
        var msg = telldus.getErrorStringSync(returnValue);
        returnValue.should.equal(0, 'removeEventListenerSync failed with "' + msg + '"');
        //we should have 1 event
        count.should.be.equal(1);
        done(); //consider the test done
      }, seconds * 1000);
    });//deviceEventListener
  });//describe events

});

redpajama_set_name: RedPajamaGithub


text:
"""Usage:
          pontoon snapshot list [--with-ids]
          pontoon snapshot show <name>
          pontoon snapshot destroy <name>
          pontoon snapshot transfer <name> <region>

Options:
    --with-ids      Include ids in output. Useful for other software that uses
                    Digital Ocean ids for input (like Packer).
    -h --help       Show this page.
"""

from .. import ui
from .. import Command
from .. import SnapshotException

class SnapshotCommand(Command):

    def list(self):
        available = self.pontoon.snapshot.list()
        ui.message("Available snapshots:")
        if len(set(s.name for s in available)) != len(available):
            ui.warning("Warning: multiple snapshots have the same name! "
                       "Actions on these snapshots will fail until this is "
                       "resolved in the web UI.")

        for s in available:
            if self.args['--with-ids']:
                ui.message(" - %-10s %s" % (str(s.id) + ':', s.name))
            else:
                ui.message(" - %s" % s.name)
        return 0

    def show(self):
        img = self.pontoon.snapshot.show(self.args['<name>'])
        for k, v in img.__dict__.items():
            ui.message("   %s: %s" % (k, v))

    def destroy(self):
        ui.message("Destroying %s..." % self.args['<name>'])
        self.pontoon.snapshot.destroy(self.args['<name>'])

    def transfer(self):
        ui.message("Transferring %s to %s..." % (
            self.args['<name>'],
            self.args['<region>']
        ))
        self.pontoon.snapshot.transfer(self.args['<name>'],
                                       self.args['<region>'])
        return 0

def main():
    try:
        cmd = SnapshotCommand(str(__doc__))
        exit(cmd.run())
    except SnapshotException as e:
        ui.message(str(e))
        exit(1)

    exit(0)

if __name__ == '__main__':
    main()


text:
import { TransformationType } from './enums';
/**
 * Storage all library metadata.
 */
var MetadataStorage = /** @class */ (function () {
    function MetadataStorage() {
        // -------------------------------------------------------------------------
        // Properties
        // -------------------------------------------------------------------------
        this._typeMetadatas = new Map();
        this._transformMetadatas = new Map();
        this._exposeMetadatas = new Map();
        this._excludeMetadatas = new Map();
        this._ancestorsMap = new Map();
    }
    // -------------------------------------------------------------------------
    // Adder Methods
    // -------------------------------------------------------------------------
    MetadataStorage.prototype.addTypeMetadata = function (metadata) {
        if (!this._typeMetadatas.has(metadata.target)) {
            this._typeMetadatas.set(metadata.target, new Map());
        }
        this._typeMetadatas.get(metadata.target).set(metadata.propertyName, metadata);
    };
    MetadataStorage.prototype.addTransformMetadata = function (metadata) {
        if (!this._transformMetadatas.has(metadata.target)) {
            this._transformMetadatas.set(metadata.target, new Map());
        }
        if (!this._transformMetadatas.get(metadata.target).has(metadata.propertyName)) {
            this._transformMetadatas.get(metadata.target).set(metadata.propertyName, []);
        }
        this._transformMetadatas.get(metadata.target).get(metadata.propertyName).push(metadata);
    };
    MetadataStorage.prototype.addExposeMetadata = function (metadata) {
        if (!this._exposeMetadatas.has(metadata.target)) {
            this._exposeMetadatas.set(metadata.target, new Map());
        }
        this._exposeMetadatas.get(metadata.target).set(metadata.propertyName, metadata);
    };
    MetadataStorage.prototype.addExcludeMetadata = function (metadata) {
        if (!this._excludeMetadatas.has(metadata.target)) {
            this._excludeMetadatas.set(metadata.target, new Map());
        }
        this._excludeMetadatas.get(metadata.target).set(metadata.propertyName, metadata);
    };
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    MetadataStorage.prototype.findTransformMetadatas = function (target, propertyName, transformationType) {
        return this.findMetadatas(this._transformMetadatas, target, propertyName).filter(function (metadata) {
            if (!metadata.options)
                return true;
            if (metadata.options.toClassOnly === true && metadata.options.toPlainOnly === true)
                return true;
            if (metadata.options.toClassOnly === true) {
                return (transformationType === TransformationType.CLASS_TO_CLASS ||
                    transformationType === TransformationType.PLAIN_TO_CLASS);
            }
            if (metadata.options.toPlainOnly === true) {
                return transformationType === TransformationType.CLASS_TO_PLAIN;
            }
            return true;
        });
    };
    MetadataStorage.prototype.findExcludeMetadata = function (target, propertyName) {
        return this.findMetadata(this._excludeMetadatas, target, propertyName);
    };
    MetadataStorage.prototype.findExposeMetadata = function (target, propertyName) {
        return this.findMetadata(this._exposeMetadatas, target, propertyName);
    };
    MetadataStorage.prototype.findExposeMetadataByCustomName = function (target, name) {
        return this.getExposedMetadatas(target).find(function (metadata) {
            return metadata.options && metadata.options.name === name;
        });
    };
    MetadataStorage.prototype.findTypeMetadata = function (target, propertyName) {
        return this.findMetadata(this._typeMetadatas, target, propertyName);
    };
    MetadataStorage.prototype.getStrategy = function (target) {
        var excludeMap = this._excludeMetadatas.get(target);
        var exclude = excludeMap && excludeMap.get(undefined);
        var exposeMap = this._exposeMetadatas.get(target);
        var expose = exposeMap && exposeMap.get(undefined);
        if ((exclude && expose) || (!exclude && !expose))
            return 'none';
        return exclude ? 'excludeAll' : 'exposeAll';
    };
    MetadataStorage.prototype.getExposedMetadatas = function (target) {
        return this.getMetadata(this._exposeMetadatas, target);
    };
    MetadataStorage.prototype.getExcludedMetadatas = function (target) {
        return this.getMetadata(this._excludeMetadatas, target);
    };
    MetadataStorage.prototype.getExposedProperties = function (target, transformationType) {
        return this.getExposedMetadatas(target)
            .filter(function (metadata) {
            if (!metadata.options)
                return true;
            if (metadata.options.toClassOnly === true && metadata.options.toPlainOnly === true)
                return true;
            if (metadata.options.toClassOnly === true) {
                return (transformationType === TransformationType.CLASS_TO_CLASS ||
                    transformationType === TransformationType.PLAIN_TO_CLASS);
            }
            if (metadata.options.toPlainOnly === true) {
                return transformationType === TransformationType.CLASS_TO_PLAIN;
            }
            return true;
        })
            .map(function (metadata) { return metadata.propertyName; });
    };
    MetadataStorage.prototype.getExcludedProperties = function (target, transformationType) {
        return this.getExcludedMetadatas(target)
            .filter(function (metadata) {
            if (!metadata.options)
                return true;
            if (metadata.options.toClassOnly === true && metadata.options.toPlainOnly === true)
                return true;
            if (metadata.options.toClassOnly === true) {
                return (transformationType === TransformationType.CLASS_TO_CLASS ||
                    transformationType === TransformationType.PLAIN_TO_CLASS);
            }
            if (metadata.options.toPlainOnly === true) {
                return transformationType === TransformationType.CLASS_TO_PLAIN;
            }
            return true;
        })
            .map(function (metadata) { return metadata.propertyName; });
    };
    MetadataStorage.prototype.clear = function () {
        this._typeMetadatas.clear();
        this._exposeMetadatas.clear();
        this._excludeMetadatas.clear();
        this._ancestorsMap.clear();
    };
    // -------------------------------------------------------------------------
    // Private Methods
    // -------------------------------------------------------------------------
    MetadataStorage.prototype.getMetadata = function (metadatas, target) {
        var metadataFromTargetMap = metadatas.get(target);
        var metadataFromTarget;
        if (metadataFromTargetMap) {
            metadataFromTarget = Array.from(metadataFromTargetMap.values()).filter(function (meta) { return meta.propertyName !== undefined; });
        }
        var metadataFromAncestors = [];
        for (var _i = 0, _a = this.getAncestors(target); _i < _a.length; _i++) {
            var ancestor = _a[_i];
            var ancestorMetadataMap = metadatas.get(ancestor);
            if (ancestorMetadataMap) {
                var metadataFromAncestor = Array.from(ancestorMetadataMap.values()).filter(function (meta) { return meta.propertyName !== undefined; });
                metadataFromAncestors.push.apply(metadataFromAncestors, metadataFromAncestor);
            }
        }
        return metadataFromAncestors.concat(metadataFromTarget || []);
    };
    MetadataStorage.prototype.findMetadata = function (metadatas, target, propertyName) {
        var metadataFromTargetMap = metadatas.get(target);
        if (metadataFromTargetMap) {
            var metadataFromTarget = metadataFromTargetMap.get(propertyName);
            if (metadataFromTarget) {
                return metadataFromTarget;
            }
        }
        for (var _i = 0, _a = this.getAncestors(target); _i < _a.length; _i++) {
            var ancestor = _a[_i];
            var ancestorMetadataMap = metadatas.get(ancestor);
            if (ancestorMetadataMap) {
                var ancestorResult = ancestorMetadataMap.get(propertyName);
                if (ancestorResult) {
                    return ancestorResult;
                }
            }
        }
        return undefined;
    };
    MetadataStorage.prototype.findMetadatas = function (metadatas, target, propertyName) {
        var metadataFromTargetMap = metadatas.get(target);
        var metadataFromTarget;
        if (metadataFromTargetMap) {
            metadataFromTarget = metadataFromTargetMap.get(propertyName);
        }
        var metadataFromAncestorsTarget = [];
        for (var _i = 0, _a = this.getAncestors(target); _i < _a.length; _i++) {
            var ancestor = _a[_i];
            var ancestorMetadataMap = metadatas.get(ancestor);
            if (ancestorMetadataMap) {
                if (ancestorMetadataMap.has(propertyName)) {
                    metadataFromAncestorsTarget.push.apply(metadataFromAncestorsTarget, ancestorMetadataMap.get(propertyName));
                }
            }
        }
        return metadataFromAncestorsTarget
            .slice()
            .reverse()
            .concat((metadataFromTarget || []).slice().reverse());
    };
    MetadataStorage.prototype.getAncestors = function (target) {
        if (!target)
            return [];
        if (!this._ancestorsMap.has(target)) {
            var ancestors = [];
            for (var baseClass = Object.getPrototypeOf(target.prototype.constructor); typeof baseClass.prototype !== 'undefined'; baseClass = Object.getPrototypeOf(baseClass.prototype.constructor)) {
                ancestors.push(baseClass);
            }
            this._ancestorsMap.set(target, ancestors);
        }
        return this._ancestorsMap.get(target);
    };
    return MetadataStorage;
}());
export { MetadataStorage };
//# sourceMappingURL=MetadataStorage.js.map


text:
<?php

namespace Bigcommerce\Api\Resources;

use Bigcommerce\Api\Resource;
use Bigcommerce\Api\Client;

/**
 * A stock keeping unit for a product.
 */
class Sku extends Resource
{
    protected $ignoreOnCreate = array(
        'product_id',
    );

    protected $ignoreOnUpdate = array(
        'id',
        'product_id',
    );

    public function options()
    {
        $options = array();

        if (!isset($this->fields->options)) {
            return $options;
        }

        foreach ($this->fields->options as $option) {
            $options[] = new SkuOption((object)$option);
        }

        return $options;
    }

    public function create()
    {
        return Client::createResource('/products/' . $this->product_id . '/skus', $this->getCreateFields());
    }

    public function update()
    {
        Client::updateResource('/products/' . $this->product_id . '/skus/' . $this->id, $this->getUpdateFields());
    }
}


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

/////
// Unity 2D Capsule Collider
//   - Creates a capsule shaped collider much like the 3D capsule collider
//   - Uses 2D Circle Colliders and 2D Box Collider to make compound collider
//   - Provides in-editor control to make it feel as native as possible
//
// timothy Kebr, tmkebr@gmail.com
// Originally created October 2015
/////

// executing in edit mode allows us to see the changes in real time without running the game
[ExecuteInEditMode]
public class Capsule2D : MonoBehaviour
{

    // These variables can be set in the editor
    public bool isTrigger;
    public Vector2 Center;
    public float radius;
    public float height;
    public enum Direction { X_Axis, Y_Axis };
    public Direction direction = Direction.X_Axis;

    // These variables will be used to manage the colliders
    List<CircleCollider2D> circles;
    BoxCollider2D box;
    Vector2 oldCenter;
    GameObject boxObject, circle0Object, circle1Object;

    // Use this for initialization
    void OnValidate()
    {
        // create the lists used for storing our collider objects
        circles = new List<CircleCollider2D>(GetComponentsInChildren<CircleCollider2D>());
        box = GetComponentInChildren<BoxCollider2D>();

        // if there aren't any game objects created, then make them as a compound game object
        if (transform.childCount > 0)
        {
            boxObject = transform.GetChild(0).gameObject;
            circle0Object = boxObject.transform.GetChild(0).gameObject;
            circle1Object = boxObject.transform.GetChild(0).gameObject;
        }

        ////
        // Make and position the box, and update the offset value based on the box size
        ////
        makeBox();
        float offset = ((box.size.x) / 2);

        ////
        // Make the circles
        ////
        makeCircle(0, -offset);
        makeCircle(1, offset);

        ////
        // Center the colliders
        ////
        centerColliders();

        ////
        // Rotate the colliders
        ////
        rotateColliders();
    }

    /// <summary>
    /// makes a box collider
    /// </summary>
    void makeBox()
    {
        // creates the box if one doesn't already exist
        if (box == null)
        {
            boxObject = new GameObject();
            boxObject.AddComponent<BoxCollider2D>();
            box = boxObject.GetComponent<BoxCollider2D>();
        }

        // Adjusts the box's size, nesting, name, and trigger values
        box.size = new Vector2((height - radius), radius);
        box.isTrigger = isTrigger;
        boxObject.transform.SetParent(this.transform, false);
        boxObject.name = "Collider";
    }

    /// <summary>
    /// makes a circle collider
    /// </summary>
    /// <param name="i"> the index in the circle list (Circle#) </param>
    /// <param name="offset"> how far to offset the circle based on box size</param>
    void makeCircle(int i, float offset)
    {
        // checks if circles have already been created
        // if they have been, just update the radius and offset values, don't bother making new circles
        if (circles.ElementAtOrDefault(i) != null)
        {
            circles[i].radius = radius / 2;
            circles[i].offset = new Vector2(offset, 0);
        }

        // else no circles have been made yet, so we will make them here
        else
        {

            // Create the circles
            if (i == 0) {
                // if the index is 0, make the first circle and add it to the list, set up nesting, and naming
                circle0Object = new GameObject();
                circles.Insert(i, circle0Object.AddComponent<CircleCollider2D>());
                circle0Object.transform.SetParent(boxObject.transform, false);
                circle0Object.name = ("circle" + i);
            }
            else {
                // if the index is 1, make the second circle and add it to the list, set up nesting, and naming
                circle1Object = new GameObject();
                circles.Insert(i, circle1Object.AddComponent<CircleCollider2D>());
                circle1Object.transform.SetParent(boxObject.transform, false);
                circle1Object.name = ("circle" + i);
            }

            // set the radii and the offsets of the circles
            circles[i].radius = radius / 2;
            circles[i].offset = new Vector2(offset, 0);
        }

        // update the trigger values
        circles[i].isTrigger = isTrigger;
    }

    /// <summary>
    /// Centers the colliders
    /// </summary>
    void centerColliders()
    {
        if (oldCenter != Center)
        {
            box.offset = Center;
            circles[0].offset = circles[0].offset + Center;
            circles[1].offset = circles[1].offset + Center;
        }
    }

    /// <summary>
    /// rotates the colliders
    /// </summary>
    void rotateColliders()
    {
        if (direction == Direction.Y_Axis)
        {
            gameObject.transform.localEulerAngles = new Vector3(0, 0, 90);
        }
        else if (direction == Direction.X_Axis)
        {
            gameObject.transform.localEulerAngles = new Vector3(0, 0, 0);
        }
    }

    // hack to check if the center value has changed
    void onDrawGizmos() {
        oldCenter = Center;
    }
}


text:
goog.provide('ol.geom.MultiPoint');

goog.require('goog.asserts');
goog.require('ol.array');
goog.require('ol.extent');
goog.require('ol.geom.GeometryLayout');
goog.require('ol.geom.GeometryType');
goog.require('ol.geom.Point');
goog.require('ol.geom.SimpleGeometry');
goog.require('ol.geom.flat.deflate');
goog.require('ol.geom.flat.inflate');
goog.require('ol.math');

/**
 * @classdesc
 * Multi-point geometry.
 *
 * @constructor
 * @extends {ol.geom.SimpleGeometry}
 * @param {Array.<ol.Coordinate>} coordinates Coordinates.
 * @param {ol.geom.GeometryLayout=} opt_layout Layout.
 * @api stable
 */
ol.geom.MultiPoint = function(coordinates, opt_layout) {
  ol.geom.SimpleGeometry.call(this);
  this.setCoordinates(coordinates, opt_layout);
};
ol.inherits(ol.geom.MultiPoint, ol.geom.SimpleGeometry);

/**
 * Append the passed point to this multipoint.
 * @param {ol.geom.Point} point Point.
 * @api stable
 */
ol.geom.MultiPoint.prototype.appendPoint = function(point) {
  goog.asserts.assert(point.getLayout() == this.layout,
      'the layout of point should match layout');
  if (!this.flatCoordinates) {
    this.flatCoordinates = point.getFlatCoordinates().slice();
  } else {
    ol.array.extend(this.flatCoordinates, point.getFlatCoordinates());
  }
  this.changed();
};

/**
 * Make a complete copy of the geometry.
 * @return {!ol.geom.MultiPoint} Clone.
 * @api stable
 */
ol.geom.MultiPoint.prototype.clone = function() {
  var multiPoint = new ol.geom.MultiPoint(null);
  multiPoint.setFlatCoordinates(this.layout, this.flatCoordinates.slice());
  return multiPoint;
};

/**
 * @inheritDoc
 */
ol.geom.MultiPoint.prototype.closestPointXY = function(x, y, closestPoint, minSquaredDistance) {
  if (minSquaredDistance <
      ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
    return minSquaredDistance;
  }
  var flatCoordinates = this.flatCoordinates;
  var stride = this.stride;
  var i, ii, j;
  for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
    var squaredDistance = ol.math.squaredDistance(
        x, y, flatCoordinates[i], flatCoordinates[i + 1]);
    if (squaredDistance < minSquaredDistance) {
      minSquaredDistance = squaredDistance;
      for (j = 0; j < stride; ++j) {
        closestPoint[j] = flatCoordinates[i + j];
      }
      closestPoint.length = stride;
    }
  }
  return minSquaredDistance;
};

/**
 * Return the coordinates of the multipoint.
 * @return {Array.<ol.Coordinate>} Coordinates.
 * @api stable
 */
ol.geom.MultiPoint.prototype.getCoordinates = function() {
  return ol.geom.flat.inflate.coordinates(
      this.flatCoordinates, 0, this.flatCoordinates.length, this.stride);
};

/**
 * Return the point at the specified index.
 * @param {number} index Index.
 * @return {ol.geom.Point} Point.
 * @api stable
 */
ol.geom.MultiPoint.prototype.getPoint = function(index) {
  var n = !this.flatCoordinates ?
      0 : this.flatCoordinates.length / this.stride;
  goog.asserts.assert(0 <= index && index < n,
      'index should be in between 0 and n');
  if (index < 0 || n <= index) {
    return null;
  }
  var point = new ol.geom.Point(null);
  point.setFlatCoordinates(this.layout, this.flatCoordinates.slice(
      index * this.stride, (index + 1) * this.stride));
  return point;
};

/**
 * Return the points of this multipoint.
 * @return {Array.<ol.geom.Point>} Points.
 * @api stable
 */
ol.geom.MultiPoint.prototype.getPoints = function() {
  var flatCoordinates = this.flatCoordinates;
  var layout = this.layout;
  var stride = this.stride;
  /** @type {Array.<ol.geom.Point>} */
  var points = [];
  var i, ii;
  for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
    var point = new ol.geom.Point(null);
    point.setFlatCoordinates(layout, flatCoordinates.slice(i, i + stride));
    points.push(point);
  }
  return points;
};

/**
 * @inheritDoc
 * @api stable
 */
ol.geom.MultiPoint.prototype.getType = function() {
  return ol.geom.GeometryType.MULTI_POINT;
};

/**
 * @inheritDoc
 * @api stable
 */
ol.geom.MultiPoint.prototype.intersectsExtent = function(extent) {
  var flatCoordinates = this.flatCoordinates;
  var stride = this.stride;
  var i, ii, x, y;
  for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
    x = flatCoordinates[i];
    y = flatCoordinates[i + 1];
    if (ol.extent.containsXY(extent, x, y)) {
      return true;
    }
  }
  return false;
};

/**
 * Set the coordinates of the multipoint.
 * @param {Array.<ol.Coordinate>} coordinates Coordinates.
 * @param {ol.geom.GeometryLayout=} opt_layout Layout.
 * @api stable
 */
ol.geom.MultiPoint.prototype.setCoordinates = function(coordinates, opt_layout) {
  if (!coordinates) {
    this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null);
  } else {
    this.setLayout(opt_layout, coordinates, 1);
    if (!this.flatCoordinates) {
      this.flatCoordinates = [];
    }
    this.flatCoordinates.length = ol.geom.flat.deflate.coordinates(
        this.flatCoordinates, 0, coordinates, this.stride);
    this.changed();
  }
};

/**
 * @param {ol.geom.GeometryLayout} layout Layout.
 * @param {Array.<number>} flatCoordinates Flat coordinates.
 */
ol.geom.MultiPoint.prototype.setFlatCoordinates = function(layout, flatCoordinates) {
  this.setFlatCoordinatesInternal(layout, flatCoordinates);
  this.changed();
};


text:
'use strict';

var path    = require('path');
var exec    = require('child_process').exec;
var os      = require('os');
var async   = require('async');
var numeral = require('numeral');

/**
 * Diskspace
 * * *
 * @param config
 * @constructor
 */
var Diskspace = function(config) {

    /**
     * Execute a command to retrieve disks list.
     *
     * @param command
     * @param fnCallback
     */
    function _getDrives(command, fnCallback) {
        exec(command, function (err, stdout, stderr) {
                if (err) return fnCallback(err);
                var drives = stdout.split('\n');

                drives.splice(0, 1);
                drives.splice(-1, 1);

                // Removes ram drives
                drives = drives.filter(function(item){ return item != "none"});
                fnCallback(null, drives);
            }
        );
    }

    /**
     * Execute a command.
     *
     * @param command
     * @param callback
     */
    function _getDetail(command, callback) {
        exec(command, function (err, stdout, stderr) {
                if (err) return callback(err);
                callback(null, parseInt(stdout) * 1024);
            }
        );
    }

    /**
     * Execute a command.
     *
     * @param command
     * @param callback
     */
    function _getDetailNaN(command, callback) {
        exec(command, function (err, stdout, stderr) {
                if (err) return callback(err);
                callback(null, stdout);
            }
        );
    }

    /**
     * Retrieve disks list.
     *
     * @param fnCallback
     */
    function drives( fnCallback ) {
        switch (os.platform().toLowerCase()) {
            case 'linux':
            default:
                _getDrives('df | awk \'{print $1}\'', fnCallback);
        }
    }

    /**
     * Retrieve space information about each drives.
     *
     * @param drives
     * @param callback
     */
    function drivesDetail(drives, callback) {
        var drivesDetail = [];

        async.eachSeries(
            drives,
            function (drive, cb) {
                driveDetail(
                    drive,
                    function (err, detail) {
                        if (err) return cb(err);
                        drivesDetail.push(detail);
                        cb();
                    }
                );
            },
            function (err) {
                if (err) return callback(err);
                callback(null, drivesDetail);
            }
        );
    }

    /**
     * Retrieve space information about one drive.
     *
     * @param drive
     * @param callback
     */
    function driveDetail(drive, callback) {
        async.series(
            {
                used: function (callback) {
                    switch (os.platform().toLowerCase()) {
                        case'darwin':
                            _getDetail('df -kl | grep ' + drive + ' | awk \'{print $3}\'', callback);
                            break;
                        case'linux':
                        default:
                            _getDetail('df | grep ' + drive + ' | awk \'{print $3}\'', callback);
                    }
                },
                available: function (callback) {
                    switch (os.platform().toLowerCase()) {
                        case'darwin':
                            _getDetail('df -kl | grep ' + drive + ' | awk \'{print $4}\'', callback);
                            break;
                        case'linux':
                        default:
                            _getDetail('df | grep ' + drive + ' | awk \'{print $4}\'', callback);
                    }
                },
                mountpoint: function (callback) {
                    switch (os.platform().toLowerCase()) {
                        case'darwin':
                            _getDetailNaN('df -kl | grep ' + drive + ' | awk \'{print $9}\'', function(e, d){
                                if (d) d = d.trim();
                                callback(e, d);
                            });
                            break;
                        case'linux':
                        default:
                            _getDetailNaN('df | grep ' + drive + ' | awk \'{print $6}\'', function(e, d){
                                if (d) d = d.trim();
                                callback(e, d);
                            });
                    }
                }
            },
            function (err, results) {
                if (err) return callback(err);
                results.freePer = numeral(results.available / (results.used + results.available) * 100).format('0');
                results.usedPer = numeral(results.used / (results.used + results.available) * 100).format('0');
                results.total = numeral(results.used + results.available).format('0.00 b');
                //results.used = numeral(results.used).format('0.00 b');
                //results.available = numeral(results.available).format('0.00 b');
                results.drive = drive;

                callback(null, results);
            }
        );
    }

    this.drives = drives;
    this.drivesDetail = drivesDetail;
    this.driveDetail = driveDetail;

};

module.exports = Diskspace;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Core Plot (Mac OS): Member List</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>

Core Plot (Mac OS)

Cocoa plotting framework for Mac OS X and iOS

Main Page

Related Pages

Modules

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

CPTDecimalNumberValueTransformer Member List

This is the complete list of members for CPTDecimalNumberValueTransformer, including all inherited members.

bind:toObject:withKeyPath:options:	<NSKeyValueBindingCreation-p>

copy	NSObject

dealloc	NSObject

description	<NSObject-p>

exposeBinding:	<NSKeyValueBindingCreation-p>	 [static]

exposedBindings	<NSKeyValueBindingCreation-p>

hash	<NSObject-p>

infoForBinding:	<NSKeyValueBindingCreation-p>

init	NSObject

isEqual:	<NSObject-p>

optionDescriptionsForBinding:	<NSKeyValueBindingCreation-p>

unbind:	<NSKeyValueBindingCreation-p>

valueClassForBinding:	<NSKeyValueBindingCreation-p>

Generated on Sun Sep 25 2011 15:44:02 for Core Plot (Mac OS) by

     1.7.5


text:
using System;
using System.Globalization;
using System.IO;
using System.Threading;
using Castle.MicroKernel;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Serializers;
using Xunit;
using Xunit.Extensions;

namespace Rhino.ServiceBus.Tests.Bugs
{
    [CLSCompliant(false)]
    public class Serialization_roundtrip
    {
        public class Foo
        {
            public string Name { get; set; }

            public string UName
            {
                get
                {
                    return Name.ToUpper();
                }
            }
        }

        public class Bar
        {
            public DateTime Date { get; set; }
        }

        [Fact]
        public void Can_roundtrip()
        {
            var serializer = new XmlMessageSerializer(new DefaultReflection(),new DefaultKernel());

            var stream = new MemoryStream();
            serializer.Serialize(new object[] {new Foo {Name = "abc"}}, stream);

            stream.Position = 0;

            var foo = (Foo)serializer.Deserialize(stream)[0];
            Assert.Equal("abc", foo.Name);
            Assert.Equal("ABC", foo.UName);
        }

        [Theory]
        [InlineData("it-IT")]
        [InlineData("mi-NZ")]
        [InlineData("es-US")]
        public void Can_roundtrip_with_datetime_on_non_english_culture(string cultureName)
        {
            var oldCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);

            try
            {
                var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel());

                var stream = new MemoryStream();
                var date = DateTime.Now;
                serializer.Serialize(new object[] { new Bar { Date = date } }, stream);

                stream.Position = 0;

                var bar = (Bar)serializer.Deserialize(stream)[0];
                Assert.Equal(date, bar.Date);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = oldCulture;
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>objectScreen</title>
    <link rel="SHORTCUT ICON" href="favicon.ico">
    <link rel="stylesheet" type="text/css" href="./content/css/main.css">

    <link rel="stylesheet" type="text/css" href="./libs/jquery-ui-1.11.1/jquery-ui.css">

    <textarea id="data">["add",{"json":"data"}]</textarea>


text:
<?xml version="1.0" encoding="UTF-8"?>
<scriptmodule xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <description>Enter credit card data in payment on billing page.</description>
  <parameter name="owner" desc="owner"/>
  <parameter name="type" desc="type"/>
  <parameter name="number" desc="number"/>
  <parameter name="month" desc="month"/>
  <parameter name="year" desc="year"/>
  <parameter name="cvn" desc="cvn"/>
  <command name="store" target="css=#dwfrm_billing_paymentMethods_creditCard" value="css_creditcard"/>
  <command name="check" target="css=.payment-method-options .form-row [value="CREDIT_CARD"]"/>
  <command name="type" target="${css_creditcard}_owner" value="@{owner}"/>
  <command name="select" target="${css_creditcard}_type" value="@{type}"/>
  <command name="type" target="css= input[id*=dwfrm_billing_paymentMethods_creditCard_number]" value="@{number}"/>
  <command name="select" target="${css_creditcard}_expiration_month" value="@{month}"/>
  <command name="select" target="${css_creditcard}_expiration_year" value="@{year}"/>
  <command name="type" target="css=input[id*=dwfrm_billing_paymentMethods_creditCard_cvn]" value="@{cvn}"/>
</scriptmodule>


text:
from enum import Enum

from SiddhiCEP3 import SiddhiLoader
from SiddhiCEP3.DataTypes.DataWrapper import unwrapData, wrapData

class ComplexEvent(object):
    class Type(Enum):
        CURRENT = SiddhiLoader._loadType("org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.TypeProxy")().CURRENT(),
        EXPIRED = SiddhiLoader._loadType("org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.TypeProxy")().EXPIRED(),
        TIMER = SiddhiLoader._loadType("org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.TypeProxy")().TIMER(),
        RESET = SiddhiLoader._loadType("org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.TypeProxy")().RESET()

        @classmethod
        def _map_value(cls, type_proxy):
            type_value = None
            if type_proxy.isValueCurrent():
                type_value = ComplexEvent.Type.CURRENT
            elif type_proxy.isValueExpired():
                type_value = ComplexEvent.Type.EXPIRED
            elif type_proxy.isValueTimer():
                type_value = ComplexEvent.Type.TIMER
            elif type_proxy.isValueReset():
                type_value = ComplexEvent.Type.RESET
            else:
                raise TypeError("Unknown Complex Event Type")
            return ComplexEvent.Type(type_value)
    def __init__(self,):
        raise NotImplementedError("Complex Event is Abstract")

    def __new__(cls):
        bare_instance = object.__new__(cls)
        bare_instance._complex_event_proxy = None
        return bare_instance

    @classmethod
    def _fromComplexEventProxy(cls, complex_event_proxy):
        '''
        Internal Constructor to wrap around JAVA Interface Complex Event
        :param complex_event_proxy:
        :return:
        '''
        if complex_event_proxy is None:
            return None
        instance = cls.__new__(cls)
        instance._complex_event_proxy = complex_event_proxy
        return instance

    def getNext(self):
        next_proxy = self._complex_event_proxy.getNext()
        return ComplexEvent._fromComplexEventProxy(next_proxy)

    def setNext(self, next_event):
        self._complex_event_proxy.setNext(next_event._complex_event_proxy)

    next = property(getNext, setNext)

    def getOutputData(self):
        complex_event_static_proxy = SiddhiLoader._loadType("org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.ComplexEventProxy")()
        output_data = unwrapData(complex_event_static_proxy.getOutputData(self._complex_event_proxy))
        return output_data

    def setOutputData(self, datum, index):
        #TODO: Improve logic here by adding support to long. Will need to make a java wrapping for handling long
        complex_event_static_proxy = SiddhiLoader._loadType(
            "org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.ComplexEventProxy")()
        complex_event_static_proxy.setOutputData(self._complex_event_proxy,wrapData(datum),index)

    def getTimestamp(self):
        return self._complex_event_proxy.getTimestamp()

    timestamp = property(fget=getTimestamp, fset=None)

    def getAttribute(self, position):
        return self._complex_event_proxy.getAttribute(position)

    def setAttribute(self, value, position):
        #TODO: Improve logic here by adding support to long. Will need to make a java wrapping for handling long
        self._complex_event_proxy.setAttribute(value,position)

    def getType(self):
        raw_type_proxy = self._complex_event_proxy.getType()
        type_proxy = SiddhiLoader._loadType("org.wso2.siddhi.pythonapi.proxy.core.event.complex_event.TypeProxy")(raw_type_proxy)
        return ComplexEvent.Type._map_value(type_proxy)

    def setType(self, type):
        self._complex_event_proxy.setType(type.value())

    type = property(getType, setType)


text:
package org.coffee.ioc.active;

import org.coffee.ioc.core.bean.Property;

public class ActiveProperty implements Property{

	Type type;
	/**
	 * <pre>
	 * byManual : 给定数值
	 * byType : null
	 * byName : 给定字符串
	 * </pre>
	 * */
	Object value;

	public ActiveProperty(Type type, Object value){
		this.type = type;
		this.value = value;
	}
	/**
	 * @see org.coffee.ioc.core.bean.Property#getType()
	 * */
	public Type getType() {
		return type;
	}
	/**
	 * @see org.coffee.ioc.core.bean.Property#getValue()
	 * */
	public Object getValue() {
		return value;
	}

}


text:
package com.mediatek.settings;

import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.SystemProperties;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.android.settings.R;
import com.mediatek.galleryfeature.clearmotion.ClearMotionQualityJni;

import java.io.IOException;

public class ClearMotionSettings extends Activity implements
        CompoundButton.OnCheckedChangeListener, OnCompletionListener, OnPreparedListener,
        SurfaceHolder.Callback {
    private static final String TAG = "ClearMotionSettingsLog";

    private static final String KEY_CLEAR_MOTION = "clearMotion";
    private static final String KEY_DISPLAY_CLEAR_MOTION = "persist.sys.display.clearMotion";
    private static final String KEY_DISPLAY_CLEAR_MOTION_DIMMED = "sys.display.clearMotion.dimmed";
    private static final String ACTION_CLEARMOTION_DIMMED =
        "com.mediatek.clearmotion.DIMMED_UPDATE";
    private static final String CLEAR_MOTION_VIDEO_NAME = "clear_motion_video.mp4";

    private Switch mActionBarSwitch;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private MediaPlayer mMediaPlayer;
    private View mLineView;
    private TextView mOnText;
    private TextView mOffText;

    /**
     * add for clearMotion
     */
    private BroadcastReceiver mUpdateClearMotionStatusReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context1, Intent intent) {
            Log.d("@M_" + TAG, "mUpdateClearMotionStatusReceiver");

            updateClearMotionStatus();
            updateClearMotionDemo(mActionBarSwitch.isChecked());
            prepareVideo();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_view);

        initViews();
        // WindowManager.LayoutParams winParams = getWindow().getAttributes();
        // winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        // getWindow().setAttributes(winParams);
    }

    private void initViews() {
        mLineView = findViewById(R.id.line_view);
        mOnText = (TextView) findViewById(R.id.text_on);
        mOffText = (TextView) findViewById(R.id.text_off);
        mOnText.setBackgroundColor(Color.argb(155, 0, 0, 0));
        mOffText.setBackgroundColor(Color.argb(155, 0, 0, 0));

        mActionBarSwitch = new Switch(getLayoutInflater().getContext());
        final int padding = getResources().getDimensionPixelSize(R.dimen.action_bar_switch_padding);
        mActionBarSwitch.setPaddingRelative(0, 0, padding, 0);
        getActionBar().setDisplayOptions(
                ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_CUSTOM,
                ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_CUSTOM);
        getActionBar()
                .setCustomView(
                        mActionBarSwitch,
                        new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                                ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL
                                        | Gravity.END));
        getActionBar().setTitle(R.string.clear_motion_title);
        mActionBarSwitch.setOnCheckedChangeListener(this);
        updateClearMotionStatus();
        mSurfaceView = (SurfaceView) findViewById(R.id.surface_view);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        getActionBar().setCustomView(null);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateClearMotionDemo(mActionBarSwitch.isChecked());
        registerReceiver(mUpdateClearMotionStatusReceiver, new IntentFilter(
                ACTION_CLEARMOTION_DIMMED));
    }

    private void updateClearMotionStatus() {
        if (mActionBarSwitch != null) {
            Log.d("@M_" + TAG, "updateClearMotionStatus");
            mActionBarSwitch.setChecked(SystemProperties.get(KEY_DISPLAY_CLEAR_MOTION, "0").equals(
                    "1"));
            mActionBarSwitch.setEnabled(SystemProperties.get(KEY_DISPLAY_CLEAR_MOTION_DIMMED, "0")
                    .equals("0"));
        }
    }

    private void updateClearMotionDemo(boolean status) {
        Log.d("@M_" + TAG, "updateClearMotionDemo status: " + status);
        mLineView.setVisibility(status ? View.VISIBLE : View.GONE);
        mOnText.setVisibility(status ? View.VISIBLE : View.GONE);
        mOffText.setVisibility(status ? View.VISIBLE : View.GONE);
        ClearMotionQualityJni.nativeSetDemoMode(status ? 3 : 0);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mUpdateClearMotionStatusReceiver);
        ClearMotionQualityJni.nativeSetDemoMode(0);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.d("@M_" + TAG, "onCheckedChanged " + isChecked);
        SystemProperties.set(KEY_DISPLAY_CLEAR_MOTION, isChecked ? "1" : "0");
        updateClearMotionDemo(isChecked);
        prepareVideo();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d("@M_" + TAG, "surfaceCreated " + holder);
        mSurfaceHolder = holder;
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setDisplay(mSurfaceHolder);
        prepareVideo();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d("@M_" + TAG, "surfaceChanged " + holder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d("@M_" + TAG, "surfaceDestroyed " + holder);
        releaseMediaPlayer();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.d("@M_" + TAG, "onPrepared ");
        mMediaPlayer.start();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.d("@M_" + TAG, "onCompletion ");
        // cycle play
        mp.seekTo(0);
        mp.start();
    }

    /**
     * error listner, stop play video.
     */
    private OnErrorListener mErrorListener = new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.d("@M_" + TAG, "play error: " + what);
            Log.d("@M_" + TAG, "play error: " + extra);
            releaseMediaPlayer();
            return false;
        }
    };

    private void prepareVideo() {
        try {
            if (mMediaPlayer != null) {
                mMediaPlayer.reset();
                AssetFileDescriptor afd = getAssets().openFd(CLEAR_MOTION_VIDEO_NAME);
                Log.d("@M_" + TAG, "video path = " + afd.getFileDescriptor());
                mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd
                        .getLength());
                afd.close();
                mMediaPlayer.prepare();
                // resizeSurfaceView();
                Log.d("@M_" + TAG, "mMediaPlayer prepare()");
            }
        } catch (IOException e) {
            Log.e("@M_" + TAG, "unable to open file; error: " + e.getMessage(), e);
            releaseMediaPlayer();
        } catch (IllegalStateException e) {
            Log.e("@M_" + TAG, "media player is in illegal state; error: " + e.getMessage(), e);
            releaseMediaPlayer();
        }
    }

    private void releaseMediaPlayer() {
        Log.d("@M_" + TAG, "releaseMediaPlayer");
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}


text:
using System.Web;

namespace Umbraco.Web.Routing
{
    /// <summary>
    /// Event args containing information about why the request was not routable, or if it is routable
    /// </summary>
    public class RoutableAttemptEventArgs : UmbracoRequestEventArgs
    {
        public EnsureRoutableOutcome Outcome { get; private set; }

        public RoutableAttemptEventArgs(EnsureRoutableOutcome reason, UmbracoContext umbracoContext, HttpContextBase httpContext)
            : base(umbracoContext, httpContext)
        {
            Outcome = reason;
        }
    }
}


text:
static const int QUEEN_OFFSET = 0;

// public functions
Queen::Queen(sf::RenderWindow &w, sf::Vector2i p, sf::Texture &t, PieceColor c)
	: Piece(w, p, t, c) {

	// set bishop sprite
	int color_offset = (c == White ? 0 : SQUARE_SIZE);
	sprite.setTextureRect(sf::IntRect(QUEEN_OFFSET, color_offset, SQUARE_SIZE, SQUARE_SIZE));

}

// queens can move any number of spaces along its row, column, or diagonals,
// but it can't jump over any pieces
bool Queen::canReach(sf::Vector2i dest, const Board *b) {

	int x_diff = pos.x - dest.x;
	int y_diff = pos.y - dest.y;

	// along column
	if (x_diff == 0) {

		if (y_diff > 0) { // move up

			int next = pos.y - 1;
			Piece *square = b->getSquare(sf::Vector2i(pos.x, next));

			// move up until another piece or destination is reached
			while (square == NULL && next != dest.y) {

				next--;
				square = b->getSquare(sf::Vector2i(pos.x, next));

			}

			// if destination is reached
			if (next == dest.y) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		} else if (y_diff < 0) { // move down

			int next = pos.y + 1;
			Piece *square = b->getSquare(sf::Vector2i(pos.x, next));

			// move down until another piece or destination is reached
			while (square == NULL && next != dest.y) {

				next++;
				square = b->getSquare(sf::Vector2i(pos.x, next));

			}

			// if destination is reached
			if (next == dest.y) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		}

	}

	// along row
	if (y_diff == 0) {

		if (x_diff > 0) { // move left

			int next = pos.x - 1;
			Piece * square = b->getSquare(sf::Vector2i(next, pos.y));

			// move left until another piece or destination is reached
			while (square == NULL && next != dest.x) {

				next--;
				square = b->getSquare(sf::Vector2i(next, pos.y));

			}

			// if destination is reached
			if (next == dest.x) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		} else if (x_diff < 0) { // move right

			int next = pos.x + 1;
			Piece * square = b->getSquare(sf::Vector2i(next, pos.y));

			// move right until another piece or destination is reached
			while (square == NULL && next != dest.x) {

				next++;
				square = b->getSquare(sf::Vector2i(next, pos.y));

			}

			// if destination is reached
			if (next == dest.x) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		}

	}

	// upper diagonal
	if (y_diff > 0) {

		if (x_diff > 0) { // move up-left

			sf::Vector2i next(pos.x - 1, pos.y - 1);
			Piece *square = b->getSquare(next);

			while (square == NULL && next.x != dest.x && next.y != dest.y) {

				next.x--;
				next.y--;
				square = b->getSquare(next);

			}

			// if destination is reached
			if (next.x == dest.x && next.y == dest.y) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		} else if (x_diff < 0) { // move up-right

			sf::Vector2i next(pos.x + 1, pos.y - 1);
			Piece *square = b->getSquare(next);

			while (square == NULL && next.x != dest.x && next.y != dest.y) {

				next.x++;
				next.y--;
				square = b->getSquare(next);

			}

			// if destination is reached
			if (next.x == dest.x && next.y == dest.y) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		}

	}

	// lower diagonal
	if (y_diff < 0) {

		if (x_diff > 0) { // move down-left

			sf::Vector2i next(pos.x - 1, pos.y + 1);
			Piece *square = b->getSquare(next);

			while (square == NULL && next.x != dest.x && next.y != dest.y) {

				next.x--;
				next.y++;
				square = b->getSquare(next);

			}

			// if destination is reached
			if (next.x == dest.x && next.y == dest.y) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		} else if (x_diff < 0) { // move down-right

			sf::Vector2i next(pos.x + 1, pos.y + 1);
			Piece *square = b->getSquare(next);

			while (square == NULL && next.x != dest.x && next.y != dest.y) {

				next.x++;
				next.y++;
				square = b->getSquare(next);

			}

			// if destination is reached
			if (next.x == dest.x && next.y == dest.y) {

				// destination is empty, valid move
				if (square == NULL)
					return true;

				// destination has an enemy piece, valid move
				if (square->getColor() != color)
					return true;

			}

		}

	}

	return false;

}


text:
#include "SkTileImageFilter.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkReadBuffer.h"
#include "SkWriteBuffer.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkShader.h"
#include "SkValidationUtils.h"

bool SkTileImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& src,
                                      const Context& ctx,
                                      SkBitmap* dst, SkIPoint* offset) const {
    SkBitmap source = src;
    SkImageFilter* input = getInput(0);
    SkIPoint srcOffset = SkIPoint::Make(0, 0);
    if (input && !input->filterImage(proxy, src, ctx, &source, &srcOffset)) {
        return false;
    }

    SkRect dstRect;
    ctx.ctm().mapRect(&dstRect, fDstRect);
    SkIRect dstIRect;
    dstRect.roundOut(&dstIRect);
    int w = dstIRect.width();
    int h = dstIRect.height();
    if (!fSrcRect.width() || !fSrcRect.height() || !w || !h) {
        return false;
    }

    SkRect srcRect;
    ctx.ctm().mapRect(&srcRect, fSrcRect);
    SkIRect srcIRect;
    srcRect.roundOut(&srcIRect);
    srcIRect.offset(-srcOffset);
    SkBitmap subset;
    SkIRect bounds;
    source.getBounds(&bounds);

    if (!srcIRect.intersect(bounds)) {
        offset->fX = offset->fY = 0;
        return true;
    } else if (!source.extractSubset(&subset, srcIRect)) {
        return false;
    }

    SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(w, h));
    if (NULL == device.get()) {
        return false;
    }
    SkCanvas canvas(device);
    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);

    SkMatrix shaderMatrix;
    shaderMatrix.setTranslate(SkIntToScalar(srcOffset.fX),
                              SkIntToScalar(srcOffset.fY));
    SkAutoTUnref<SkShader> shader(SkShader::CreateBitmapShader(subset,
                                  SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode,
                                  &shaderMatrix));
    paint.setShader(shader);
    canvas.translate(-dstRect.fLeft, -dstRect.fTop);
    canvas.drawRect(dstRect, paint);
    *dst = device->accessBitmap(false);
    offset->fX = dstIRect.fLeft;
    offset->fY = dstIRect.fTop;
    return true;
}

bool SkTileImageFilter::onFilterBounds(const SkIRect& src, const SkMatrix& ctm,
                                       SkIRect* dst) const {
    SkRect srcRect;
    ctm.mapRect(&srcRect, fSrcRect);
    SkIRect srcIRect;
    srcRect.roundOut(&srcIRect);
    srcIRect.join(src);
    *dst = srcIRect;
    return true;
}

SkTileImageFilter::SkTileImageFilter(SkReadBuffer& buffer)
  : INHERITED(1, buffer) {
    buffer.readRect(&fSrcRect);
    buffer.readRect(&fDstRect);
    buffer.validate(buffer.isValid() && SkIsValidRect(fSrcRect) && SkIsValidRect(fDstRect));
}

void SkTileImageFilter::flatten(SkWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);
    buffer.writeRect(fSrcRect);
    buffer.writeRect(fDstRect);
}


text:
package com.intellij.lang;

import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class WhitespacesBinders {
  private WhitespacesBinders() { }

  public static final WhitespacesAndCommentsBinder DEFAULT_LEFT_BINDER = new WhitespacesAndCommentsBinder() {
    public int getEdgePosition(List<IElementType> tokens, boolean atStreamEdge, TokenTextGetter getter) {
      return tokens.size();
    }
  };
  public static final WhitespacesAndCommentsBinder DEFAULT_RIGHT_BINDER = new WhitespacesAndCommentsBinder() {
    public int getEdgePosition(List<IElementType> tokens, boolean atStreamEdge, TokenTextGetter getter) {
      return 0;
    }
  };

  public static final WhitespacesAndCommentsBinder GREEDY_LEFT_BINDER = DEFAULT_RIGHT_BINDER;
  public static final WhitespacesAndCommentsBinder GREEDY_RIGHT_BINDER = DEFAULT_LEFT_BINDER;

  public static WhitespacesAndCommentsBinder leadingCommentsBinder(@NotNull TokenSet commentTypes) {
    return new WhitespacesAndCommentsBinder() {
      @Override
      public int getEdgePosition(List<IElementType> tokens, boolean atStreamEdge, TokenTextGetter getter) {
        int i = 0;
        while (i < tokens.size() && !commentTypes.contains(tokens.get(i))) {
          i++;
        }
        return i;
      }
    };
  }

  public static WhitespacesAndCommentsBinder trailingCommentsBinder(@NotNull TokenSet commentTypes) {
    return new WhitespacesAndCommentsBinder() {
      @Override
      public int getEdgePosition(List<IElementType> tokens, boolean atStreamEdge, TokenTextGetter getter) {
        int i = tokens.size() - 1;
        while (i >= 0 && !commentTypes.contains(tokens.get(i))) {
          i--;
        }
        return i + 1;
      }
    };
  }
}


text:
class Systemd(object):
  '''
  Systemd will create/delete systemd files to make sure
  that the containers can survive a reboot

  The systemd files are configuration so they may need to live
  in the salt repo.  This is still to be determined.  Writing out a
  yaml file to salt would fix this problem.  Write it to salt and
  forget about it
  '''
  def __init__(self, manager, salt):
    self.manager = manager
    self.salt = manager.salt_client


text:
extern const char *whitespace;

char *strip_whitespace(char *str);
char *strip_comments(char *str);

// Simply split a string with delims, free with `free_flat_list`
list_t *split_string(const char *str, const char *delims);
void free_flat_list(list_t *list);

// Splits an argument string, keeping quotes intact
char **split_args(const char *str, int *argc);
void free_argv(int argc, char **argv);

char *code_strchr(const char *string, char delimiter);
char *code_strstr(const char *haystack, const char *needle);
int unescape_string(char *string);
char *join_args(char **argv, int argc);
char *join_list(list_t *list, char *separator);

char *strdup(const char *);
#endif


text:
@interface ABOViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextView *md5Source;
@property (strong, nonatomic) IBOutlet UITextView *md5Result;
- (IBAction)goMD5:(id)sender;
- (IBAction)resetMD5:(id)sender;

@end


text:
using Grace.DependencyInjection;
using Grace.Tests.Classes.Simple;
using Xunit;

namespace Grace.Tests.DependencyInjection.Named
{
    public class NamedScopedTests
    {
        [Fact]
        public void Scoped_Export_AsName()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c => c.Export<BasicService>().AsName("BasicService"));

            using (var scope = container.BeginLifetimeScope())
            {
                var instance = scope.LocateByName("BasicService");

                Assert.NotNull(instance);
                Assert.IsType<BasicService>(instance);
            }
        }

        [Fact]
        public void Scoped_Export_Disposable_AsName()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c => c.Export<DisposableService>().AsName("DisposableService"));

            var disposed = false;

            using (var scope = container.BeginLifetimeScope())
            {
                var instance = (IDisposableService)scope.LocateByName("DisposableService");

                Assert.NotNull(instance);
                Assert.IsType<DisposableService>(instance);

                instance.Disposing += (sender, args) => disposed = true;
            }

            Assert.True(disposed);
        }

        [Fact]
        public void Scoped_Export_TypeSet_ByName()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c => c.ExportAssemblyContaining<NamedTests>().ByName());

            using (var scope = container.BeginLifetimeScope())
            {
                var instance = scope.LocateByName("BasicService");

                Assert.NotNull(instance);
                Assert.IsType<BasicService>(instance);
            }
        }

        [Fact]
        public void Scoped_TryLocateByName_Find()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c => c.Export<BasicService>().AsName("BasicService"));

            object instance;

            using (var scope = container.BeginLifetimeScope())
            {
                var returnValue = scope.TryLocateByName("BasicService", out instance);

                Assert.True(returnValue);
                Assert.NotNull(instance);
                Assert.IsType<BasicService>(instance);
            }
        }

        [Fact]
        public void Scoped_TryLocateByName_Cant_Find()
        {
            var container = new DependencyInjectionContainer();

            object instance;

            using (var scope = container.BeginLifetimeScope())
            {
                var returnValue = scope.TryLocateByName("BasicService", out instance);

                Assert.False(returnValue);
                Assert.Null(instance);
            }
        }

        [Fact]
        public void Scoped_LocateAllByName()
        {
            var container = new DependencyInjectionContainer();

            container.Configure(c =>
            {
                c.Export<MultipleService1>().AsName("MultipleService");
                c.Export<MultipleService2>().AsName("MultipleService");
                c.Export<MultipleService3>().AsName("MultipleService");
                c.Export<MultipleService4>().AsName("MultipleService");
                c.Export<MultipleService5>().AsName("MultipleService");
            });

            using (var scope = container.BeginLifetimeScope())
            {
                var services = scope.LocateAllByName("MultipleService");

                Assert.Equal(5, services.Count);
                Assert.IsType<MultipleService1>(services[0]);
                Assert.IsType<MultipleService2>(services[1]);
                Assert.IsType<MultipleService3>(services[2]);
                Assert.IsType<MultipleService4>(services[3]);
                Assert.IsType<MultipleService5>(services[4]);
            }
        }
    }
}


text:
import eventlet
import fixtures
import mock
import testscenarios

from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import importutils
from testtools.content import text_content

from neutron.agent.common import utils
from neutron.agent.linux import ip_lib
from neutron.cmd.sanity import checks
from neutron.common import constants as n_const
from neutron.plugins.ml2.drivers.openvswitch.agent.common import constants
from neutron.plugins.ml2.drivers.openvswitch.agent \
    import ovs_neutron_agent as ovsagt
from neutron.tests import base as tests_base
from neutron.tests.common import base as common_base
from neutron.tests.common import net_helpers
from neutron.tests.functional.agent import test_ovs_lib
from neutron.tests.functional import base
from neutron.tests import tools

OVS_TRACE_FINAL_FLOW = 'Final flow'
OVS_TRACE_DATAPATH_ACTIONS = 'Datapath actions'

cfg.CONF.import_group('OVS', 'neutron.plugins.ml2.drivers.openvswitch.agent.'
                      'common.config')

class OVSAgentTestBase(test_ovs_lib.OVSBridgeTestBase,
                       base.BaseSudoTestCase):
    scenarios = testscenarios.multiply_scenarios([
        ('ofctl', {'main_module': ('neutron.plugins.ml2.drivers.openvswitch.'
                                  'agent.openflow.ovs_ofctl.main')}),
        ('native', {'main_module': ('neutron.plugins.ml2.drivers.openvswitch.'
                                  'agent.openflow.native.main')})],
        test_ovs_lib.OVSBridgeTestBase.scenarios)

    def setUp(self):
        super(OVSAgentTestBase, self).setUp()
        self.br = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
        self.of_interface_mod = importutils.import_module(self.main_module)
        self.br_int_cls = None
        self.br_tun_cls = None
        self.br_phys_cls = None
        self.br_int = None
        self.init_done = False
        self.init_done_ev = eventlet.event.Event()
        self.main_ev = eventlet.event.Event()
        self.addCleanup(self._kill_main)
        retry_count = 3
        while True:
            cfg.CONF.set_override('of_listen_port',
                                  net_helpers.get_free_namespace_port(
                                      n_const.PROTO_NAME_TCP),
                                  group='OVS')
            self.of_interface_mod.init_config()
            self._main_thread = eventlet.spawn(self._kick_main)

            # Wait for _kick_main -> of_interface main -> _agent_main
            # NOTE(yamamoto): This complexity came from how "native"
            # of_interface runs its openflow controller.  "native"
            # of_interface's main routine blocks while running the
            # embedded openflow controller.  In that case, the agent
            # rpc_loop runs in another thread.  However, for FT we
            # need to run setUp() and test_xxx() in the same thread.
            # So I made this run of_interface's main in a separate
            # thread instead.
            try:
                while not self.init_done:
                    self.init_done_ev.wait()
                break
            except fixtures.TimeoutException:
                self._kill_main()
            retry_count -= 1
            if retry_count < 0:
                raise Exception('port allocation failed')

    def _run_trace(self, brname, spec):
        required_keys = [OVS_TRACE_FINAL_FLOW, OVS_TRACE_DATAPATH_ACTIONS]
        t = utils.execute(["ovs-appctl", "ofproto/trace", brname, spec],
                          run_as_root=True)
        trace = {}
        trace_lines = t.splitlines()
        for line in trace_lines:
            (l, sep, r) = line.partition(':')
            if not sep:
                continue
            elif l in required_keys:
                trace[l] = r
        for k in required_keys:
            if k not in trace:
                self.fail("%s not found in trace %s" % (k, trace_lines))

        return trace

    def _kick_main(self):
        with mock.patch.object(ovsagt, 'main', self._agent_main):
            self.of_interface_mod.main()

    def _kill_main(self):
        self.main_ev.send()
        self._main_thread.wait()

    def _agent_main(self, bridge_classes):
        self.br_int_cls = bridge_classes['br_int']
        self.br_phys_cls = bridge_classes['br_phys']
        self.br_tun_cls = bridge_classes['br_tun']
        self.br_int = self.br_int_cls(self.br.br_name)
        self.br_int.set_secure_mode()
        self.br_int.setup_controllers(cfg.CONF)
        self.br_int.setup_default_table()

        # signal to setUp()
        self.init_done = True
        self.init_done_ev.send()

        self.main_ev.wait()

class ARPSpoofTestCase(OVSAgentTestBase):
    def setUp(self):
        # NOTE(kevinbenton): it would be way cooler to use scapy for
        # these but scapy requires the python process to be running as
        # root to bind to the ports.
        self.addOnException(self.collect_flows_and_ports)
        super(ARPSpoofTestCase, self).setUp()
        self.skip_without_arp_support()
        self.src_addr = '192.168.0.1'
        self.dst_addr = '192.168.0.2'
        self.src_namespace = self.useFixture(
            net_helpers.NamespaceFixture()).name
        self.dst_namespace = self.useFixture(
            net_helpers.NamespaceFixture()).name
        self.src_p = self.useFixture(
            net_helpers.OVSPortFixture(self.br, self.src_namespace)).port
        self.dst_p = self.useFixture(
            net_helpers.OVSPortFixture(self.br, self.dst_namespace)).port
        # wait to add IPs until after anti-spoof rules to ensure ARP doesn't
        # happen before

    def collect_flows_and_ports(self, exc_info):
        nicevif = lambda x: ['%s=%s' % (k, getattr(x, k))
                             for k in ['ofport', 'port_name', 'switch',
                                       'vif_id', 'vif_mac']]
        nicedev = lambda x: ['%s=%s' % (k, getattr(x, k))
                             for k in ['name', 'namespace']] + x.addr.list()
        details = {'flows': self.br.dump_all_flows(),
                   'vifs': map(nicevif, self.br.get_vif_ports()),
                   'src_ip': self.src_addr,
                   'dest_ip': self.dst_addr,
                   'sourt_port': nicedev(self.src_p),
                   'dest_port': nicedev(self.dst_p)}
        self.addDetail('arp-test-state',
                       text_content(jsonutils.dumps(details, indent=5)))

    @common_base.no_skip_on_missing_deps
    def skip_without_arp_support(self):
        if not checks.arp_header_match_supported():
            self.skipTest("ARP header matching not supported")

    def test_arp_spoof_doesnt_block_normal_traffic(self):
        self._setup_arp_spoof_for_port(self.src_p.name, [self.src_addr])
        self._setup_arp_spoof_for_port(self.dst_p.name, [self.dst_addr])
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def test_mac_spoof_blocks_wrong_mac(self):
        self._setup_arp_spoof_for_port(self.src_p.name, [self.src_addr])
        self._setup_arp_spoof_for_port(self.dst_p.name, [self.dst_addr])
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)
        # changing the allowed mac should stop the port from working
        self._setup_arp_spoof_for_port(self.src_p.name, [self.src_addr],
                                       mac='00:11:22:33:44:55')
        net_helpers.assert_no_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_doesnt_block_ipv6(self):
        self.src_addr = '2000::1'
        self.dst_addr = '2000::2'
        self._setup_arp_spoof_for_port(self.src_p.name, [self.src_addr])
        self._setup_arp_spoof_for_port(self.dst_p.name, [self.dst_addr])
        self.src_p.addr.add('%s/64' % self.src_addr)
        self.dst_p.addr.add('%s/64' % self.dst_addr)
        # make sure the IPv6 addresses are ready before pinging
        self.src_p.addr.wait_until_address_ready(self.src_addr)
        self.dst_p.addr.wait_until_address_ready(self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_blocks_response(self):
        # this will prevent the destination from responding to the ARP
        # request for it's own address
        self._setup_arp_spoof_for_port(self.dst_p.name, ['192.168.0.3'])
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_no_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_blocks_icmpv6_neigh_advt(self):
        self.src_addr = '2000::1'
        self.dst_addr = '2000::2'
        # this will prevent the destination from responding (i.e., icmpv6
        # neighbour advertisement) to the icmpv6 neighbour solicitation
        # request for it's own address (2000::2) as spoofing rules added
        # below only allow '2000::3'.
        self._setup_arp_spoof_for_port(self.dst_p.name, ['2000::3'])
        self.src_p.addr.add('%s/64' % self.src_addr)
        self.dst_p.addr.add('%s/64' % self.dst_addr)
        # make sure the IPv6 addresses are ready before pinging
        self.src_p.addr.wait_until_address_ready(self.src_addr)
        self.dst_p.addr.wait_until_address_ready(self.dst_addr)
        net_helpers.assert_no_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_blocks_request(self):
        # this will prevent the source from sending an ARP
        # request with its own address
        self._setup_arp_spoof_for_port(self.src_p.name, ['192.168.0.3'])
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        ns_ip_wrapper = ip_lib.IPWrapper(self.src_namespace)
        try:
            ns_ip_wrapper.netns.execute(['arping', '-I', self.src_p.name,
                                         '-c1', self.dst_addr])
            tools.fail("arping should have failed. The arp request should "
                       "have been blocked.")
        except RuntimeError:
            pass

    def test_arp_spoof_allowed_address_pairs(self):
        self._setup_arp_spoof_for_port(self.dst_p.name, ['192.168.0.3',
                                                         self.dst_addr])
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_icmpv6_neigh_advt_allowed_address_pairs(self):
        self.src_addr = '2000::1'
        self.dst_addr = '2000::2'
        self._setup_arp_spoof_for_port(self.dst_p.name, ['2000::3',
                                                         self.dst_addr])
        self.src_p.addr.add('%s/64' % self.src_addr)
        self.dst_p.addr.add('%s/64' % self.dst_addr)
        # make sure the IPv6 addresses are ready before pinging
        self.src_p.addr.wait_until_address_ready(self.src_addr)
        self.dst_p.addr.wait_until_address_ready(self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_allowed_address_pairs_0cidr(self):
        self._setup_arp_spoof_for_port(self.dst_p.name, ['9.9.9.9/0',
                                                         '1.2.3.4'])
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_disable_port_security(self):
        # block first and then disable port security to make sure old rules
        # are cleared
        self._setup_arp_spoof_for_port(self.dst_p.name, ['192.168.0.3'])
        self._setup_arp_spoof_for_port(self.dst_p.name, ['192.168.0.3'],
                                       psec=False)
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def test_arp_spoof_disable_network_port(self):
        # block first and then disable port security to make sure old rules
        # are cleared
        self._setup_arp_spoof_for_port(self.dst_p.name, ['192.168.0.3'])
        self._setup_arp_spoof_for_port(
            self.dst_p.name, ['192.168.0.3'],
            device_owner=n_const.DEVICE_OWNER_ROUTER_GW)
        self.src_p.addr.add('%s/24' % self.src_addr)
        self.dst_p.addr.add('%s/24' % self.dst_addr)
        net_helpers.assert_ping(self.src_namespace, self.dst_addr, count=2)

    def _setup_arp_spoof_for_port(self, port, addrs, psec=True,
                                  device_owner='nobody', mac=None):
        vif = next(
            vif for vif in self.br.get_vif_ports() if vif.port_name == port)
        ip_addr = addrs.pop()
        details = {'port_security_enabled': psec,
                   'fixed_ips': [{'ip_address': ip_addr}],
                   'device_owner': device_owner,
                   'allowed_address_pairs': [
                        dict(ip_address=ip) for ip in addrs]}
        if mac:
            vif.vif_mac = mac
        ovsagt.OVSNeutronAgent.setup_arp_spoofing_protection(
            self.br_int, vif, details)

class CanaryTableTestCase(OVSAgentTestBase):
    def test_canary_table(self):
        self.br_int.delete_flows()
        self.assertEqual(constants.OVS_RESTARTED,
                         self.br_int.check_canary_table())
        self.br_int.setup_canary_table()
        self.assertEqual(constants.OVS_NORMAL,
                         self.br_int.check_canary_table())

class OVSFlowTestCase(OVSAgentTestBase):
    """Tests defined in this class use ovs-appctl ofproto/trace commands,
    which simulate processing of imaginary packets, to check desired actions
    are correctly set up by OVS flows.  In this way, subtle variations in
    flows between of_interface drivers are absorbed and the same tests work
    against those drivers.
    """

    def setUp(self):
        cfg.CONF.set_override('enable_distributed_routing',
                              True,
                              group='AGENT')
        super(OVSFlowTestCase, self).setUp()
        self.phys_br = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
        self.br_phys = self.br_phys_cls(self.phys_br.br_name)
        self.br_phys.set_secure_mode()
        self.br_phys.setup_controllers(cfg.CONF)
        self.router_addr = '192.168.0.1/24'
        self.namespace = self.useFixture(
            net_helpers.NamespaceFixture()).name
        self.phys_p = self.useFixture(
            net_helpers.OVSPortFixture(self.br_phys, self.namespace)).port

        self.tun_br = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
        self.br_tun = self.br_tun_cls(self.tun_br.br_name)
        self.br_tun.set_secure_mode()
        self.br_tun.setup_controllers(cfg.CONF)
        self.tun_p = self.br_tun.add_patch_port(
            cfg.CONF.OVS.tun_peer_patch_port,
            cfg.CONF.OVS.int_peer_patch_port)
        self.br_tun.setup_default_table(self.tun_p, True)

    def test_provision_local_vlan(self):
        kwargs = {'port': 123, 'lvid': 888, 'segmentation_id': 777}
        self.br_phys.provision_local_vlan(distributed=False, **kwargs)
        trace = self._run_trace(self.phys_br.br_name,
                                "in_port=%(port)d,dl_src=12:34:56:78:aa:bb,"
                                "dl_dst=24:12:56:78:aa:bb,dl_type=0x0800,"
                                "nw_src=192.168.0.1,nw_dst=192.168.0.2,"
                                "nw_proto=1,nw_tos=0,nw_ttl=128,"
                                "icmp_type=8,icmp_code=0,dl_vlan=%(lvid)d"
                                % kwargs)
        self.assertTrue(("dl_vlan=%(segmentation_id)d" % kwargs) in
                        trace["Final flow"])

    def test_install_dvr_to_src_mac(self):
        other_dvr_mac = 'fa:16:3f:01:de:ad'
        other_dvr_port = 333
        kwargs = {'vlan_tag': 888,
                  'gateway_mac': '12:34:56:78:aa:bb',
                  'dst_mac': '12:34:56:78:cc:dd',
                  'dst_port': 123}
        self.br_int.install_dvr_to_src_mac(network_type='vlan', **kwargs)
        self.br_int.add_dvr_mac_vlan(mac=other_dvr_mac, port=other_dvr_port)

        trace = self._run_trace(self.br.br_name,
                                "in_port=%d," % other_dvr_port +
                                "dl_src=" + other_dvr_mac + "," +
                                "dl_dst=%(dst_mac)s,dl_type=0x0800,"
                                "nw_src=192.168.0.1,nw_dst=192.168.0.2,"
                                "nw_proto=1,nw_tos=0,nw_ttl=128,"
                                "icmp_type=8,icmp_code=0,"
                                "dl_vlan=%(vlan_tag)d" % kwargs)
        self.assertTrue("vlan_tci=0x0000" in trace["Final flow"])
        self.assertTrue(("dl_src=%(gateway_mac)s" % kwargs) in
                        trace["Final flow"])

    def test_install_flood_to_tun(self):
        attrs = {
            'remote_ip': '192.0.2.1',  # RFC 5737 TEST-NET-1
            'local_ip': '198.51.100.1',  # RFC 5737 TEST-NET-2
        }
        kwargs = {'vlan': 777, 'tun_id': 888}
        port_name = tests_base.get_rand_device_name(net_helpers.PORT_PREFIX)
        ofport = self.br_tun.add_tunnel_port(port_name, attrs['remote_ip'],
                                             attrs['local_ip'])
        self.br_tun.install_flood_to_tun(ports=[ofport], **kwargs)
        test_packet = ("icmp,in_port=%d," % self.tun_p +
                       "dl_src=12:34:56:ab:cd:ef,dl_dst=12:34:56:78:cc:dd,"
                       "nw_src=192.168.0.1,nw_dst=192.168.0.2,nw_ecn=0,"
                       "nw_tos=0,nw_ttl=128,icmp_type=8,icmp_code=0,"
                       "dl_vlan=%(vlan)d,dl_vlan_pcp=0" % kwargs)
        trace = self._run_trace(self.tun_br.br_name, test_packet)
        self.assertTrue(("tun_id=0x%(tun_id)x" % kwargs) in
                        trace["Final flow"])
        self.assertTrue("vlan_tci=0x0000," in trace["Final flow"])

        self.br_tun.delete_flood_to_tun(kwargs['vlan'])

        trace = self._run_trace(self.tun_br.br_name, test_packet)
        self.assertEqual(" unchanged", trace["Final flow"])
        self.assertTrue("drop" in trace["Datapath actions"])


text:
title: "Winking, but you can't tell"
excerpt: "PaperFaces portrait of @idPro drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-idpro-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-idpro-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS, beard]
---

Oops, I didn't paint any eyes. PaperFaces portrait of [@idPro](https://twitter.com/idPro).

{% include_cached boilerplate/paperfaces-2.md %}


text:
<?php
require_once(DIR_APPLICATION . "controller/payment/mollie/base.php");

class ControllerPaymentMolliePrzelewy24 extends ControllerPaymentMollieBase
{
	const MODULE_NAME = MollieHelper::MODULE_NAME_PRZELEWY24;
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;

using ILCompiler.DependencyAnalysisFramework;

using Internal.Text;
using Internal.TypeSystem;

namespace ILCompiler.DependencyAnalysis.ReadyToRun
{
    public class AvailableType : DependencyNodeCore<NodeFactory>, IEETypeNode
    {
        private readonly TypeDesc _type;

        public AvailableType(NodeFactory factory, TypeDesc type)
        {
            _type = type;

            //
            // This check encodes rules specific to CoreRT. Ie, no function pointer classes allowed.
            // Eventually we will hit situations where this check fails when it shouldn't and we'll need to
            // split the logic. It's a good sanity check for the time being though.
            //
            EETypeNode.CheckCanGenerateEEType(factory, type);
        }

        public TypeDesc Type => _type;

        public int Offset => 0;

        public bool RepresentsIndirectionCell => false;

        public int ClassCode => 345483495;

        public override bool InterestingForDynamicDependencyAnalysis => false;

        public override bool HasDynamicDependencies => false;

        public override bool HasConditionalStaticDependencies => false;

        public override bool StaticDependenciesAreComputed => true;

        public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
        {
            sb.Append(nameMangler.GetMangledTypeName(_type));
        }

        public int CompareToImpl(ISortableNode other, CompilerComparer comparer)
        {
            return comparer.Compare(Type, ((AvailableType)other).Type);
        }

        public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory context) => null;
        public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory context) => null;
        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context) => null;

        protected override string GetName(NodeFactory factory) => $"Available type {Type.ToString()}";
    }
}