text:
<link rel="import" href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="../things-id/things-guid-behavior.html">
<link rel="import" href="../things-msg-box-behavior/things-msg-box-behavior.html">

<script src='../../../lib/grid/dataludi.lic.eval-1.2.0.min.js'></script>
<script src='../../../lib/grid/dataludi.eval-1.2.1.min.js'></script>

<script>

  window.Things = window.Things || {};

  /**
   * 트리 그리드 설정을 담당하는 Behavior.
   * 트리 그리드, 트리 그리드 모델, 트리 그리드 컬럼에 대한 설정을 통해 그리드를 설정하고 그리는 기능까지 담당한다.
   * Dataludi grid를 사용하고 중요한 설정사항은 크게 grid config, grid fields (model), grid columns 및 event 설정이 있다.
   *
   * @polymerBehavior Things.TreeGridConfigBehavior
   */
  Things.TreeGridConfigBehaviorImpl = {

    properties: {

      /**
       * Grid container id
       * Grid container id가 중복이 되면 grid가 다른 grid container에 생성될 수 있으므로 GUID로 한다.
       */
      gridContainerId: {
        type: String
      },

      /**
       * Dataludi grid
       */
      grid: {
        type: Object
      },

      /**
       * Grid mode 'canvas'/'html'
       */
      mode: {
        type: String,
        value: 'canvas'
      },

      /**
       * Grid Config
       */
      config: {
        type: Object,
        observer: '_setGridConfig'
      },

      /**
       * Grid Data Model - array of fields
       */
      model: {
        type: Array,
        reflectToAttribute: true // For TEST
      },

      /**
       * Grid view column
       */
      columns: {
        type: Array,
        reflectToAttribute: true // For TEST
      },

      /**
       * Grid data set
       */
      dataSet: {
        type: Object,
        value: function() {
          return DataLudi.createTreeDataSet();
        }
      },

      /**
       * Read data
       */
      data: {
        type: Object
      },

      /**
       * Grid Height
       */
      gridHeight: {
        type: Number,
        value: 300
      },

      /**
       * 그리드 이미지 루트
       */
      gridImageDir: {
        type: String,
        value: 'images/grid/'
      },

      /**
       * Grid에서 사용할 이미지 리스트
       */
      gridImageItems: {
        type: Array,
        value: function() {
          return [
            'iconDetail.png',
            'ellipsis_hover.png',
            'indicator_insert.png',
            'menu_button.png',
            'menu_button_hover.png'
          ];
        }
      },

      /**
       * Grid Cell Styles
       */
      gridCellStyles: {
        type: Array,
        value: function() {
          return [ {
            expression: "state == 'c'",
            styles: {
              background: '#1000ff00'
            }
          }, {
            expression: "(row % 2) > 0",
            styles: {
              background: '#20006060'
            }
          } ];
        }
      },

      /**
      * 핸들링하고자 하는 grid event를 설정한다. { grid event 명 : 'event handler 명' }
      */
      events : {
        type: Object,
        value: {
          'onDataCellClicked': '_gridCellClicked',
          'onDataCellDblClicked': '_gridCellDblClicked'
        }
      },

      /**
       * 상세보기 버튼을 활성화할 지 여부
       */
      enableDetailColumn: {
        type: Boolean,
        value: false
      },

      /**
       * 그리드 footer를 보여줄 지 여부
       */
      showGridFooter: {
        type: Boolean,
        value: false
      },

      /**
       * 선택된 row data
       */
      selectedRowData: {
        type: Object,
        notify: true,
        readOnly: true
      },

      /**
       * 선택된 cell data
       */
      selectedCellData: {
        type: Object,
        notify: true,
        readOnly: true
      }
      /**
       * 그리드 구성 전 발생하는 이벤트
       *
       * @event things-grid-configure
       */
      /**
       * 그리드 구성이 완료된 후 발생하는 이벤트
       *
       * @event things-grid-configured
       */
      /**
       * 그리드 구성 도중 에러가 발생한 경우 발생하는 이벤트
       *
       * @event things-grid-configure-failed
       */
      /**
       * 그리드 이벤트 Behavior 구성 전 발생하는 이벤트
       *
       * @event things-grid-event-configure
       */
      /**
       * 그리드 이벤트 Behavior 구성이 완료된 후 발생하는 이벤트
       *
       * @event things-grid-event-configured
       */
      /**
       * 그리드 Resize 전 발생하는 이벤트
       *
       * @event things-grid-resize
       */
      /**
       * 그리드 Resize 후 발생하는 이벤트
       *
       * @event things-grid-resized
       */
      /**
       * 그리드 Data 변경 전 발생하는 이벤트
       *
       * @event things-grid-data-change
       */
      /**
       * 그리드 Data 변경 후 발생하는 이벤트
       *
       * @event things-grid-data-changed
       */
      /**
       * 그리드 상세 버튼이 클릭 되었을 경우 발생하는 이벤트
       *
       * @event things-grid-detail-tap
       */
      /**
       * 그리드 Row Data가 선택되었을 경우 발생하는 이벤트
       *
       * @event things-grid-row-data-select
       */
      /**
       * 그리드 Cell Data가 선택되었을 경우 발생하는 이벤트
       *
       * @event things-grid-cell-data-select
       */
      /**
       * 그리드 셀 중에서 Resource Column 속성인 Resource Column을 Edit하고자 하는 경우 발생하는 이벤트
       * 외부에서는 이 이벤트를 받아서 사용자가 데이터를 선택할 수 있도록 Resource Selector 창을 띄운다.
       *
       * @event things-grid-resource-column-edit
       */
    },

    listeners: {
      'iron-resize': '_gridScreenResizeHandler'
    },

    observers: [
      '_configurationsChanged(model, columns)',
      '_gridDataChanged(data)'
    ],

    /**
     * Life Cycle - Detached
     */
    detached: function() {
      this.clearGrid();
    },

    /**
     * Initialize Grid
     */
    initializeGrid: function() {
      if(this.grid || !this.model || !this.columns) return;

      if(!this.gridContainerId || this.gridContainerId == '') {
        this.gridContainerId = this.generateGuid();
      }

      if(!this.parentNode.offsetWidth || this.parentNode.offsetWidth == 0) {
        return;
      }

      DataLudi.setRootContext('');
      DataLudi.setAssetRoot(this.gridImageDir);
      this.grid = DataLudi.createTreeView(this.gridContainerId, null, false);
      this.grid.setDataSource(this.dataSet);
      this.grid.registerImageList({
        name: 'images',
        root: this.gridImageDir,
        items: this.gridImageItems});
      this.grid.body().setCellDynamicStyles(this.gridCellStyles);
      this.grid.footer().setVisible(this.showGridFooter);

      this.grid._container_ = this;

      if(this.config) {
        this._setGridConfig(this.config);
      }

      if(this.model) {
        this._setGridModel(this.model);
      }

      if(this.columns) {
        this._setGridColumns(this.columns);
      }

      if(this.data) {
        this.dataSet.setRows(this.data);
      }

      if (this.grid && this.events) {
        var evt = this.fire('things-grid-event-configure', this.grid, { cancelable: true });
        if(!evt.defaultPrevented) {
          for (var eventName in this.events) {
            this.grid[eventName] = this[this.events[eventName]];
          }

          this.fire('things-grid-event-configured', this.grid);
        }
      }

      this.resizeGrid(this.parentNode, this.querySelector('div'));
    },

    /**
     * Clear Grid
     */
    clearGrid: function() {
      this.data = null;
      this.dataSet = null;
      this.model = null;
      this.columns = null;

      if(this.grid && this.grid._container_) {
        this.grid._container_ = null;
      }

      this.grid = null;
    },

    /**
     * Get Grid Object
     */
    getGridObject : function () {
      return this.grid;
    },

    /**
     * Get Grid DataSet
     */
    getGridDataSet : function () {
      return this.dataSet;
    },

    /**
     * 그리드 리사이즈 - parentNode 사이즈에 따라 그리드를 리사이즈
     *
     * @param {Object} parentNode
     * @param {Object} gridContainer
     */
    resizeGrid: function(parentNode, gridContainer) {
      gridContainer.style.width = (parentNode.offsetWidth - 20) + 'px';
      gridContainer.style.height = this.gridHeight + 'px';
      this.grid.resetSize();
    },

    /**********************************************************************************
     *                            Grid Configuration
     **********************************************************************************

    /**
     * Configurations changed
     *
     * @param {Object} model
     * @param {Object} columns
     */
    _configurationsChanged: function(model, columns) {
      if(model && columns && !this.grid) {
        var evtDetail = { config: this.config, model: model, columns: columns };
        var evt = this.fire('things-grid-configure', evtDetail, { cancelable: true });
        if(!evt.defaultPrevented) {
          try {
            this.initializeGrid();
          } catch(e) {
            evtDetail.error = e;
            this.fire('things-grid-configure-failed', evtDetail);
          }

          this.fire('things-grid-configured', evtDetail);
        }
      }
    },

    /**
     * Set Grid Model Fields
     *
     * @param {Array} / {String} gridModel
     */
    _setGridModel: function(gridModel) {
      if(!gridModel || !this.grid) return;

      var fields = (typeof(gridModel) === 'string') ? JSON.parse(gridModel) : gridModel;

      if (fields && fields.length > 0) {
        this.dataSet.setFields(fields);
        this.dataSet.setCheckStates(true);
      }
    },

    /**
     * Set Grid Column Views
     *
     * @param {Array} / {String} columns
     */
    _setGridColumns: function(columns) {
      if(!columns || !this.grid) return;

      var gridColumns = (typeof(columns) === 'string') ? JSON.parse(columns) : columns;

      if(this.enableDetailColumn) {
        gridColumns.unshift({
          name: 'Detail',
          width: 30,
          imageList: 'images',
          header: { text: ' ' },
          renderer: { type: 'icon' },
          styles: {
            iconIndex: 'iconDetail.png',
            iconLocation: 'center'
          }
        });
      }

      if(gridColumns.length > 0) {
        this.grid.setColumns(gridColumns);
      }

      this.grid.resetSize();
    },

    /**
     * Set grid initial config information
     *
     * @param {Object} config
     */
    _setGridConfig: function(config) {
      if(!config || !this.grid) return;

      var gridConfig = (typeof(config) === 'string') ? JSON.parse(config) : config;

      if(!gridConfig) {
        this.grid.setEditOptions({ readOnly : true });

      } else {
        var grid = this.grid;
        Object.keys(gridConfig).forEach(function(confKey) {
          switch (confKey) {
            case 'body':
              grid.setBody(gridConfig[confKey]);
              break;

            case 'checkBar':
              grid.setCheckBar(gridConfig[confKey]);
              break;

            case 'header':
              grid.setHeader(gridConfig[confKey]);
              break;

            case 'footer':
              grid.setFooter(gridConfig[confKey]);
              break;

            case 'columnLayout':
              grid.setColumnLayout(gridConfig[confKey]);
              break;

            case 'dataCellRenderers':
              grid.dataCellRenderers().addRenderers(gridConfig[confKey]);
              break;

            case 'displayOptions':
              grid.setDisplayOptions(gridConfig[confKey]);
              break;

            case 'editOptions':
              grid.setEditOptions(gridConfig[confKey]);
              break;

            case 'summaryMode':
              var SummaryMode = DataLudi.SummaryMode[gridConfig[confKey].toUpperCase()];
                grid.setSummaryMode(SummaryMode);
              break;

            case 'button':
              gridConfig[confKey].forEach(function(button) {
                buttons.push(button);
              });
              break;

            case 'rowIndicator':
              grid.rowIndicator().setProperties(gridConfig[confKey]);
              break;

            case 'gridColumnPopupMenus':
              gridConfig[confKey].forEach(function(columnMenu) {
                grid.registerPopupMenu(columnMenu.name, columnMenu.menu);
              })
              break;

            default:
              break;
          }
        });
      }
    },

    /**********************************************************************************
     *                            Grid Event
     **********************************************************************************

    /**
     * 데이터 변경 이벤트 핸들러
     *
     * @param {event} e
     */
    _gridDataChanged: function(e) {
      var evt = this.fire('things-grid-data-change', this.data, { cancelable: true });
      if(!evt.defaultPrevented && this.data && this.dataSet) {
        DataLudi.loadJsonData(this.dataSet, data, { rows: '', childRows: 'items' });
        this.fire('things-grid-data-changed', this.data);
      }
    },

    /**
     * 화면 리사이즈 시 이벤트 핸들러
     *
     * @param {event} iron-resize 이벤트
     */
    _gridScreenResizeHandler: function(e) {
      var evt = this.fire('things-grid-resize', this.grid, { cancelable: true });
      if(!evt.defaultPrevented) {
        if(this.parentNode.offsetWidth > 0 && this.grid == null) {
          this.initializeGrid();
        }

        if(this.grid != null && this.grid._container) {
          this.resizeGrid(this.parentNode, this.querySelector('div'));
        }

        this.fire('things-grid-resized', this.grid);
      }
    },

    /**
     * Grid Cell Click 이벤트 핸들러
     *
     * @param {Object} grid
     * @param {Object} cellData
     */
    _gridCellClicked: function(grid, cellData) {
      if(!grid._container_ || !cellData) return;

      var thingsGrid = grid._container_;

      if (cellData.dataColumn() && cellData.getDataIndex(grid) >= 0) {
        var rowIndex = cellData.getDataIndex(grid);
        var colIndex = cellData.dataField();
        var row = grid.focusedRow();

        if(row && row.dataIndex() >= 0) {
          thingsGrid._setSelectedRowData(row.getRowObject());
          thingsGrid.fire('things-grid-row-data-select', thingsGrid.selectedRowData);
        }

        if(thingsGrid.dataSet && cellData.dataField() >= 0) {
          thingsGrid._setSelectedCellData(thingsGrid.dataSet.getValue(rowIndex, colIndex));
          thingsGrid.fire('things-grid-cell-data-select', { row: thingsGrid.selectedRowData, cell: cellData });
        }

        if(thingsGrid.enableDetailColumn && cellData.column._name == 'Detail' &&
           cellData.column._renderer && cellData.column._renderer.type == 'icon') {
          thingsGrid._setSelectedRowData(row.getRowObject());
          thingsGrid.fire('things-grid-detail-tap', thingsGrid.selectedRowData);
        }
      }
    },

    /**
     * Grid Cell Double Click 이벤트 핸들러
     *
     * @param {Object} grid
     * @param {Object} index
     */
    _gridCellDblClicked: function(grid, index) {
      var me = grid._container_;
      var column = index.column;

      if(column._header && column._header._text == '...' &&
         column._renderer && column._renderer.type && column._renderer.type == 'icon') {
        var matchColumn = me.columns.filter(function(col) { return (column._name == col.name); });
        me.fire('things-grid-resource-column-edit', {
          userObj : matchColumn ? matchColumn[0].userObj : null,
          index: index
        });
      }
    }
  };

  Things.TreeGridConfigBehavior = [
    Things.TreeGridConfigBehaviorImpl,
    Polymer.IronResizableBehavior,
    Things.GUIDBehavior,
    Things.MsgBoxBehavior
  ];

</script>


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2003</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Pattern Matching</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>patterns.xml</file>

    <title>Pattern Matching</title>

Variables are bound to values through the pattern matching mechanism. Pattern matching occurs when
      evaluating a function call, <c>case</c>- <c>receive</c>-
      <c>try</c>- expressions and match operator (=) expressions.

In a pattern matching, a left-hand side
      <seealso marker="expressions#pattern">pattern</seealso> is matched
      against a right-hand side
      <seealso marker="expressions#term">term</seealso>. If
      the matching succeeds, any unbound variables in the pattern
      become bound. If the matching fails, a run-time error occurs.

Examples:

1> <input>X.</input>
** 1: variable 'X' is unbound **
2> <input>X = 2.</input>
2
3> <input>X + 1.</input>
3
4> <input>{X, Y} = {1, 2}.</input>
** exception error: no match of right hand side value {1,2}
5> <input>{X, Y} = {2, 3}.</input>
{2,3}
6> <input>Y.</input>
3

</chapter>

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.cloud.stream.config.contentType;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Vinicius Carvalho
 * @author Oleg Zhurakousky
 */
@SuppressWarnings("serial")
public class User implements Serializable {

	private String name;

	public User() {
	}

	@JsonCreator
	public User(@JsonProperty("name") String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		final StringBuffer sb = new StringBuffer("User{");
		sb.append("name='").append(this.name).append('\'');
		sb.append('}');
		return sb.toString();
	}

}


text:
module.exports = function example(request, response, callback) {
	var self = this;

	self.properties = {
		responseMechanism: 'sendJSON',
		name: 'example',
		verb: 'post'
	};

	self.test = function test(params) {
		response.message.error = false;
    response.message.data = params.username;
		callback();
	};

	return self;
};


text:
'use strict';

var stub         = require('../fixtures/stub');
var Plugin       = require('../fixtures/stub_plugin');
var Connection   = require('../fixtures/stub_connection');
var Address      = require('../../address');
var config       = require('../../config');

var _set_up = function (done) {

    this.plugin = new Plugin('spamassassin');
    this.plugin.config = config;
    this.plugin.cfg = { main: { } };

    this.connection = Connection.createConnection();
    this.connection.transaction = stub;
    this.connection.transaction.notes = {};

    done();
};

exports.register = {
    setUp : _set_up,
    'loads the spamassassin plugin': function (test) {
        test.expect(1);
        test.equal('spamassassin', this.plugin.name);
        test.done();
    },
    'register loads spamassassin.ini': function (test) {
        test.expect(2);
        this.plugin.register();
        test.ok(this.plugin.cfg);
        test.ok(this.plugin.cfg.main.spamd_socket);
        test.done();
    },
};

exports.load_spamassassin_ini = {
    setUp : _set_up,
    'loads spamassassin.ini': function (test) {
        test.expect(2);
        test.equal(undefined, this.plugin.cfg.main.spamd_socket);
        this.plugin.load_spamassassin_ini();
        test.ok(this.plugin.cfg.main.spamd_socket);
        test.done();
    },
};

exports.msg_too_big = {
    setUp : _set_up,
    'max_size not set': function (test) {
        test.expect(1);
        test.equal(false, this.plugin.msg_too_big(this.connection));
        test.done();
    },
    'max_size 10, data_bytes 9 = false': function (test) {
        test.expect(1);
        this.plugin.cfg.main = { max_size: 10 };
        this.connection.transaction.data_bytes = 9;
        test.equal(false, this.plugin.msg_too_big(this.connection));
        test.done();
    },
    'max_size 10, data_bytes 11 = true': function (test) {
        test.expect(1);
        this.plugin.cfg.main = { max_size: 10 };
        this.connection.transaction.data_bytes = 11;
        test.equal(true, this.plugin.msg_too_big(this.connection));
        test.done();
    },
};

// console.log(this.plugin.cfg);

exports.get_spamd_headers = {
    setUp : _set_up,
    'returns a spamd protocol request': function (test) {
        test.expect(1);
        this.connection.transaction.mail_from = new Address.Address('<matt@example.com>');
        this.connection.transaction.uuid = 'THIS-IS-A-TEST-UUID';
        var headers = this.plugin.get_spamd_headers(this.connection, 'test_user');
        var expected_headers = [
            'HEADERS SPAMC/1.3',
            'User: test_user',
            '',
            'X-Envelope-From: matt@example.com',
            'X-Haraka-UUID: THIS-IS-A-TEST-UUID'
        ];
        test.deepEqual(headers, expected_headers);
        test.done();
    },
};

exports.get_spamd_username = {
    setUp : _set_up,
    'default': function (test) {
        test.expect(1);
        test.equal('default', this.plugin.get_spamd_username(this.connection));
        test.done();
    },
    'set in txn.notes.spamd_user': function (test) {
        test.expect(1);
        this.connection.transaction.notes.spamd_user = 'txuser';
        test.equal('txuser', this.plugin.get_spamd_username(this.connection));
        test.done();
    },
    'set in cfg.main.spamd_user': function (test) {
        test.expect(1);
        this.plugin.cfg.main.spamd_user = 'cfguser';
        test.equal('cfguser', this.plugin.get_spamd_username(this.connection));
        test.done();
    },
    'set to first-recipient': function (test) {
        this.plugin.cfg.main.spamd_user = 'first-recipient';
        this.connection.transaction.rcpt_to = [ new Address.Address('<matt@example.com>') ];
        test.equal('matt@example.com', this.plugin.get_spamd_username(this.connection));

        test.done();
    },
};

exports.score_too_high = {
    setUp : _set_up,
    'no threshhold is not too high': function (test) {
        test.expect(1);
        test.ok(!this.plugin.score_too_high(this.connection, {score: 5}));
        test.done();
    },
    'too high score is too high': function (test) {
        test.expect(1);
        this.plugin.cfg.main.reject_threshold = 5;
        test.equal('spam score exceeded threshold', this.plugin.score_too_high(this.connection, {score: 6}));
        test.done();
    },
    'ok score with relaying is ok': function (test) {
        test.expect(1);
        this.connection.relaying = true;
        this.plugin.cfg.main.relay_reject_threshold = 7;
        test.equal(false, this.plugin.score_too_high(this.connection, {score: 6}));
        test.done();
    },
    'too high score with relaying is too high': function (test) {
        test.expect(1);
        this.connection.relaying = true;
        this.plugin.cfg.main.relay_reject_threshold = 7;
        test.equal('spam score exceeded relay threshold', this.plugin.score_too_high(this.connection, {score: 8}));
        test.done();
    },
};


text:
define([
	"../core",
	"../var/document",
	"../var/documentElement",
	"../var/support"
], function( jQuery, document, documentElement, support ) {

(function() {
	var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE9-11+
	// Style of cloned element affects source element cloned (#8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
		"padding:0;margin-top:1px;position:absolute";
	container.appendChild( div );

	// Executing both pixelPosition & boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {
		div.style.cssText =
			// Support: Android 2.3
			// Vendor-prefix box-sizing
			"-webkit-box-sizing:border-box;box-sizing:border-box;" +
			"display:block;position:absolute;" +
			"margin:0;margin-top:1%;margin-right:50%;" +
			"border:1px;padding:1px;" +
			"top:1%;width:50%;height:4px";
		div.innerHTML = "";
		documentElement.appendChild( container );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";
		boxSizingReliableVal = divStyle.height === "4px";
		pixelMarginRightVal = divStyle.marginRight === "4px";

		documentElement.removeChild( container );
	}

	jQuery.extend( support, {
		pixelPosition: function() {
			// This test is executed only once but we still do memoizing
			// since we can use the boxSizingReliable pre-computing.
			// No need to check if the test was already performed, though.
			computeStyleTests();
			return pixelPositionVal;
		},
		boxSizingReliable: function() {
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return boxSizingReliableVal;
		},
		pixelMarginRight: function() {
			// Support: Android 4.0-4.3
			// We're checking for boxSizingReliableVal here instead of pixelMarginRightVal
			// since that compresses better and they're computed together anyway.
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return pixelMarginRightVal;
		},
		reliableMarginRight: function() {

			// Support: Android 2.3
			// Check if div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container. (#3333)
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			// This support function is only executed once so no memoizing is needed.
			var ret,
				marginDiv = div.appendChild( document.createElement( "div" ) );

			// Reset CSS: box-sizing; display; margin; border; padding
			marginDiv.style.cssText = div.style.cssText =
				// Support: Android 2.3
				// Vendor-prefix box-sizing
				"-webkit-box-sizing:content-box;box-sizing:content-box;" +
				"display:block;margin:0;border:0;padding:0";
			marginDiv.style.marginRight = marginDiv.style.width = "0";
			div.style.width = "1px";
			documentElement.appendChild( container );

			ret = !parseFloat( window.getComputedStyle( marginDiv ).marginRight );

			documentElement.removeChild( container );
			div.removeChild( marginDiv );

			return ret;
		}
	});
})();

return support;

});


text:
package org.nutz.dao.impl;

import static java.lang.String.format;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.nutz.dao.SqlManager;
import org.nutz.dao.SqlNotFoundException;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.nutz.lang.Strings;
import org.nutz.lang.util.LinkedCharArray;

/**
 *
 * @author zozoh(zozohtnt@gmail.com)
 * @author wendal(wendal1985@gmail.com)
 * @author mawenming at 2010-4-10 上午10:04:17
 *
 */
public abstract class AbstractSqlManager implements SqlManager {

    protected Map<String, String> _sql_map;
    private List<String> _sql_keys;

    private boolean allowDuplicate = true;

    private Map<String, String> map() {
        if (null == _sql_map)
            this.refresh();
        return _sql_map;
    }

    private List<String> keylist() {
        if (null == _sql_keys)
            this.refresh();
        return _sql_keys;
    }

    public boolean contains(String key) {
        return map().containsKey(key);
    }

    public void saveAs(File f) throws IOException {
        Writer w = Streams.fileOutw(f);
        for (String key : keylist()) {
            w.append("/*").append(Strings.dup('-', 60)).append("*/\n");
            String sql = map().get(key);
            w.append(format("/*%s*/\n", key));
            w.append(sql).append('\n');
        }
        w.flush();
        w.close();
    }

    public String get(String key) {
        String sql = map().get(key);
        if (null == sql)
            throw new SqlNotFoundException(key);
        return sql;
    }

    public Sql create(String key) throws SqlNotFoundException {
        return Sqls.create(get(key));
    }

    public List<Sql> createCombo(String... keys) {
        if (null == keys || keys.length == 0)
            keys = this.keys();
        List<Sql> list = new ArrayList<Sql>(keys.length);
        for (String key : keys) {
            Sql sql = create(key);
            list.add(sql);
        }
        return list;
    }

    public int count() {
        return map().size();
    }

    public String[] keys() {
        return keylist().toArray(new String[keylist().size()]);
    }

    public void addSql(String key, String value) {
        if (map().containsKey(key) && !allowDuplicate)
            throw Lang.makeThrow("duplicate key '%s'", key);
        key = Strings.trim(key);
        map().put(key, value);
        keylist().add(key);
    }

    static final Pattern ptn = Pattern.compile("(?<=^\n/[*])(.*)(?=[*]/)");

    static class InnerStack {

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        LinkedCharArray list = new LinkedCharArray();
        LinkedCharArray cmts = new LinkedCharArray();
        String key = null;
        boolean inNormalComment;

        void eat(int c) {
            if (inNormalComment) {
                if (cmts.push(c).endsWith("*/")) {
                    cmts.clear();
                    inNormalComment = false;
                }
            } else if (key != null) {
                if (list.push(c).endsWith("\n/*")) {
                    list.popLast(3);
                    addOne();
                    list.push("\n/*");
                } else if (list.endsWith("/*")) {
                    list.popLast(2);
                    inNormalComment = true;
                }
            } else {
                if (list.size() < 3) {
                    if (!"\n/*".startsWith(list.push(c).toString())) {
                        list.clear();
                    }
                } else {
                    if (list.push(c).endsWith("*/")) {
                        Matcher matcher = ptn.matcher(list.popAll());
                        if (matcher.find()) {
                            key = Strings.trim(matcher.group());
                        }
                    }
                }
            }
        }

        void addOne() {
            String value = Strings.trim(list.popAll());
            if (!Strings.isBlank(value))
                map.put(key, value);
            key = null;
        }

    }

    static class SqlFileBuilder {
        LinkedHashMap<String, String> map;

        SqlFileBuilder(BufferedReader reader) throws IOException {
            InnerStack stack = new InnerStack();
            int c;
            stack.eat('\n');
            while (-1 != (c = reader.read())) {
                stack.eat(c);
            }
            if (stack.key != null)
                stack.addOne();
            map = stack.map;
            Streams.safeClose(reader);
        }

        Set<String> keys() {
            return map.keySet();
        }

        String get(String key) {
            return map.get(key);
        }
    }

    public void remove(String key) {
        this.keylist().remove(key);
        this.map().remove(key);
    }

    /**
     * 执行根据字符流来加载sql内容的操作
     *
     * @param reader
     * @throws IOException
     */
    protected void loadSQL(Reader reader) throws IOException {
        BufferedReader bufferedReader = null;
        try {
            if(reader instanceof BufferedReader)
                bufferedReader = (BufferedReader)reader;
            else
                bufferedReader = new BufferedReader(reader);
            SqlFileBuilder p = new SqlFileBuilder(bufferedReader);

            Iterator<String> it = p.keys().iterator();
            _sql_keys = new ArrayList<String>(p.map.size());
            while (it.hasNext()) {
                String key = it.next();
                String value = Strings.trim(p.get(key));
                addSql(key, value);
            }
        }
        finally {
            Streams.safeClose(bufferedReader);
        }

    }

    public void setAllowDuplicate(boolean allowDuplicate) {
        this.allowDuplicate = allowDuplicate;
    }
}


text:
layout: post
title: OAuth 2.0 Security - Going Beyond Bearer Tokens
permalink: /2012/09/oauth-2-0-security-going-beyond-bearer-tokens
tags: [oauth]
---

The OAuth working group have released an initial security review of the OAuth 2.0 specification which looks at a number of potential threats that implementors could face and how to mitigate them.

The document can be read here [http://tools.ietf.org/html/draft-tschofenig-oauth-security-00](http://tools.ietf.org/html/draft-tschofenig-oauth-security-00).

The abstract of the document is below:

> The OAuth working group has finished work on the OAuth 2.0 core protocol as well as the Bearer Token specification. The Bearer Tokenis a TLS-based solution for ensuring that neither the interaction with the Authorization Server (when requesting a token) nor the interaction with the Resource Server (for accessing a protected resource) leads to token leakage. There has, however, always been the desire to develop a security solution that is "better" than Bearer Tokens (or at least different) where the Client needs to show
possession of some keying material when accessing a Resource Server.

> This document tries to capture the discussion and to come up with requirements to process the work on solutions.

> This document aims to discuss threats, security requirements and desired design properties of an enhanced OAuth security mechanism.


text:
package com.google.inject.grapher;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Binding;
import com.google.inject.spi.ConstructorBinding;
import com.google.inject.spi.DefaultBindingTargetVisitor;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.HasDependencies;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.InstanceBinding;
import com.google.inject.spi.ProviderInstanceBinding;
import java.lang.reflect.Member;
import java.util.Collection;
import java.util.List;

/**
 * Default node creator.
 *
 * @author bojand@google.com (Bojan Djordjevic)
 */
final class DefaultNodeCreator implements NodeCreator {
  @Override
  public Iterable<Node> getNodes(Iterable<Binding<?>> bindings) {
    List<Node> nodes = Lists.newArrayList();
    NodeVisitor visitor = new NodeVisitor();
    for (Binding<?> binding : bindings) {
      nodes.addAll(binding.acceptTargetVisitor(visitor));
    }
    return nodes;
  }

  /**
   * {@link BindingTargetVisitor} that adds nodes to the graph based on the visited {@link Binding}.
   */
  private static final class NodeVisitor
      extends DefaultBindingTargetVisitor<Object, Collection<Node>> {

    /** Returns a new interface node for the given {@link Binding}. */
    private InterfaceNode newInterfaceNode(Binding<?> binding) {
      return new InterfaceNode(NodeId.newTypeId(binding.getKey()), binding.getSource());
    }

    /**
     * Returns a new implementation node for the given binding.
     *
     * @param binding binding for the node to create
     * @param members members to add to the node
     * @return implementation node for the given binding
     */
    private ImplementationNode newImplementationNode(
        Binding<?> binding, Collection<Member> members) {
      return new ImplementationNode(
          NodeId.newTypeId(binding.getKey()), binding.getSource(), members);
    }

    /**
     * Returns a new instance node for the given {@link Binding}.
     *
     * @param binding binding for the node to create
     * @param instance value of the instance
     * @return instance node for the given binding
     */
    private <T extends Binding<?> & HasDependencies> InstanceNode newInstanceNode(
        T binding, Object instance) {
      Collection<Member> members = Lists.newArrayList();
      for (Dependency<?> dependency : binding.getDependencies()) {
        InjectionPoint injectionPoint = dependency.getInjectionPoint();

        if (injectionPoint != null) {
          members.add(injectionPoint.getMember());
        }
      }
      return new InstanceNode(
          NodeId.newInstanceId(binding.getKey()), binding.getSource(), instance, members);
    }

    /**
     * Visitor for {@link ConstructorBinding}s. These are for classes that Guice will instantiate to
     * satisfy injection requests.
     */
    @Override
    public Collection<Node> visit(ConstructorBinding<?> binding) {
      Collection<Member> members = Lists.newArrayList();
      members.add(binding.getConstructor().getMember());
      for (InjectionPoint injectionPoint : binding.getInjectableMembers()) {
        members.add(injectionPoint.getMember());
      }

      return ImmutableList.<Node>of(newImplementationNode(binding, members));
    }

    /**
     * Visitor for {@link InstanceBinding}. We render two nodes in this case: an interface node for
     * the binding's {@link Key}, and then an implementation node for the instance {@link Object}
     * itself.
     */
    @Override
    public Collection<Node> visit(InstanceBinding<?> binding) {
      return ImmutableList.<Node>of(
          newInterfaceNode(binding), newInstanceNode(binding, binding.getInstance()));
    }

    /**
     * Same as {@link #visit(InstanceBinding)}, but the binding edge is {@link
     * BindingEdgeType#PROVIDER}.
     */
    @Override
    public Collection<Node> visit(ProviderInstanceBinding<?> binding) {
      return ImmutableList.<Node>of(
          newInterfaceNode(binding), newInstanceNode(binding, binding.getUserSuppliedProvider()));
    }

    @Override
    public Collection<Node> visitOther(Binding<?> binding) {
      return ImmutableList.<Node>of(newInterfaceNode(binding));
    }
  }
}


text:
/* */
"format cjs";
import warning from 'warning'

/*eslint-disable no-empty */
const KeyPrefix = '@@History/'
const QuotaExceededError = 'QuotaExceededError'

function createKey(key) {
  return KeyPrefix + key
}

export function saveState(key, state) {
  try {
    window.sessionStorage.setItem(createKey(key), JSON.stringify(state))
  } catch (error) {
    if (error.name === QuotaExceededError || window.sessionStorage.length === 0) {
      // Probably in Safari "private mode" where sessionStorage quota is 0. #42
      warning(
        false,
        '[history] Unable to save state; sessionStorage is not available in Safari private mode'
      )

      return
    }

    throw error
  }
}

export function readState(key) {
  const json = window.sessionStorage.getItem(createKey(key))

  if (json) {
    try {
      return JSON.parse(json)
    } catch (error) {
      // Ignore invalid JSON.
    }
  }

  return null
}


text:
#include "singa/singa_config.h"
#ifdef USE_CUDA
#include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand.h>
#include <chrono>
#include <iostream>
#include "singa/core/device.h"
#include "singa/utils/cuda_utils.h"
namespace singa {

const cudaMemcpyKind copyKind[] = {cudaMemcpyHostToHost, cudaMemcpyHostToDevice,
                                   cudaMemcpyDeviceToHost,
                                   cudaMemcpyDeviceToDevice};

CudaGPU::~CudaGPU() {
  if (ctx_.cublas_handle) CUBLAS_CHECK(cublasDestroy(ctx_.cublas_handle));
  if (ctx_.curand_generator)
    CURAND_CHECK(curandDestroyGenerator(ctx_.curand_generator));
#ifdef USE_CUDNN
  if (ctx_.cudnn_handle) {
    auto status = cudnnDestroy(ctx_.cudnn_handle);
    CHECK_EQ(status, CUDNN_STATUS_SUCCESS) << cudnnGetErrorString(status);
  }
#endif
}
const int kNumCudaStream = 1;

CudaGPU::CudaGPU(int id) : Device(id, kNumCudaStream) {
  MemPoolConf conf;
  conf.add_device(id);
  pool_ = std::make_shared<CnMemPool>(conf);
  Setup();
}

CudaGPU::CudaGPU(int id, std::shared_ptr<DeviceMemPool> pool)
    : Device(id, kNumCudaStream) {
  CHECK(pool != nullptr);
  pool_ = pool;
  Setup();
}

void CudaGPU::Setup() {
  lang_ = kCuda;
  ctx_.stream = NULL;  // use the default sync stream
  // TODO(wangwei) create one handle for each steam?
  CUDA_CHECK(cudaSetDevice(id_));
  // use curandCreateGeneratorHost for CudaHost device
  CURAND_CHECK(
      curandCreateGenerator(&ctx_.curand_generator, CURAND_RNG_PSEUDO_DEFAULT));
  auto seed = std::chrono::system_clock::now().time_since_epoch().count();
  SetRandSeed(seed);
  // TODO(wangwei) if one generator per stream, then need diff offset per gen?
  CURAND_CHECK(curandSetGeneratorOffset(ctx_.curand_generator, 0));
  CUBLAS_CHECK(cublasCreate(&(ctx_.cublas_handle)));

#ifdef USE_CUDNN
  // TODO(wangwei) create one handle for each stream?
  auto status = cudnnCreate(&ctx_.cudnn_handle);
  CHECK_EQ(status, CUDNN_STATUS_SUCCESS) << cudnnGetErrorString(status);
#endif  // USE_CUDNN
}

void CudaGPU::SetRandSeed(unsigned seed) {
  CHECK(ctx_.curand_generator);
  CURAND_CHECK(curandSetPseudoRandomGeneratorSeed(ctx_.curand_generator, seed));
}

void CudaGPU::DoExec(function<void(Context*)>&& fn, int executor) { fn(&ctx_); }

void CudaGPU::CopyToFrom(void* dst, const void* src, size_t nBytes,
                         CopyDirection direction, Context* ctx) {
  cudaMemcpy(dst, src, nBytes, copyKind[direction]);
  // TODO(wangwei) use async copy
  // cudaMemcpyAsync(dst, src, nBytes,cudaMemcpyDefault, ctx_.stream);
}

size_t CudaGPU::GetAllocatedMem() {
  if (pool_ != nullptr) {
    auto ret = pool_->GetMemUsage();
    return ret.second - ret.first;
  }
  LOG(ERROR) << "The memory pool is not set";
  return 0u;
}

/// Allocate gpu memory.
void* CudaGPU::Malloc(int size) {
  void* ptr = nullptr;
  if (size > 0) {
    CUDA_CHECK(cudaSetDevice(id_));
    pool_->Malloc((void**)&ptr, size);
    // TODO(wangwei) remove the memset.
    CUDA_CHECK(cudaMemset(ptr, 0, size));
  }
  return ptr;
}

/// Free gpu memory.
void CudaGPU::Free(void* ptr) {
  if (ptr != nullptr) {
    CUDA_CHECK(cudaSetDevice(id_));
    pool_->Free(ptr);
  }
}

}  // namespace singa
#endif  // USE_CUDA


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

using System;
using System.Runtime.InteropServices;
using VsChromium.Core.Ipc;
using VsChromium.Core.Win32.Memory;
using VsChromium.Core.Win32.Strings;

namespace VsChromium.Server.NativeInterop {
  public class AsciiCompiledTextSearchNative : CompiledTextSearchBase {
    private readonly SafeSearchHandle _handle;
    private readonly SafeHGlobalHandle _patternHandle;
    private readonly int _searchBufferSize;

    public AsciiCompiledTextSearchNative(
        NativeMethods.SearchAlgorithmKind kind,
        string pattern,
        NativeMethods.SearchOptions searchOptions) {
      _patternHandle = new SafeHGlobalHandle(Marshal.StringToHGlobalAnsi(pattern));
      var patternLength = pattern.Length;

      _handle = CreateSearchHandle(kind, _patternHandle, patternLength, searchOptions);
      _searchBufferSize = NativeMethods.AsciiSearchAlgorithm_GetSearchBufferSize(_handle);
    }

    private static unsafe SafeSearchHandle CreateSearchHandle(
        NativeMethods.SearchAlgorithmKind kind,
        SafeHGlobalHandle patternHandle,
        int patternLength,
        NativeMethods.SearchOptions searchOptions) {
      NativeMethods.SearchCreateResult createResult;
      var result = NativeMethods.AsciiSearchAlgorithm_Create(
          kind,
          patternHandle.Pointer,
          patternLength,
          searchOptions,
          out createResult);

      if (createResult.HResult < 0) {
        // The error is recoverable, since we are dealing with an invalid pattern
        // or something along the lines.
        var message = Marshal.PtrToStringAnsi(new IntPtr(createResult.ErrorMessage));
        throw new RecoverableErrorException(message);
      }

      return result;
    }

    protected override int SearchBufferSize {
      get { return _searchBufferSize; }
    }

    protected override void Search(ref NativeMethods.SearchParams searchParams) {
      NativeMethods.AsciiSearchAlgorithm_Search(_handle, ref searchParams);
    }

    protected override void CancelSearch(ref NativeMethods.SearchParams searchParams) {
      NativeMethods.AsciiSearchAlgorithm_CancelSearch(_handle, ref searchParams);
    }

    public override void Dispose() {
      _handle.Dispose();
      _patternHandle.Dispose();
    }
  }
}


text:
const debug = require('./../debug');

module.exports = (path) => debug(`first-class/${path}`);


text:
import { FontStyle, FontWeight } from "../../../scene/shape/text";
import { DropShadow } from "../../../scene/dropShadow";
import { HighlightStyle, SeriesNodeDatum, CartesianTooltipRendererParams as HistogramTooltipRendererParams } from "../series";
import { Label } from "../../label";
import { LegendDatum } from "../../legend";
import { CartesianSeries } from "./cartesianSeries";
import { ChartAxisDirection } from "../../chartAxis";
import { TooltipRendererResult } from "../../chart";
import { TypedEvent } from "../../../util/observable";
declare class HistogramSeriesLabel extends Label {
    formatter?: (params: {
        value: number;
    }) => string;
}
export { HistogramTooltipRendererParams };
interface HistogramNodeDatum extends SeriesNodeDatum {
    readonly x: number;
    readonly y: number;
    readonly width: number;
    readonly height: number;
    readonly fill?: string;
    readonly stroke?: string;
    readonly strokeWidth: number;
    readonly label?: {
        readonly text: string;
        readonly x: number;
        readonly y: number;
        readonly fontStyle?: FontStyle;
        readonly fontWeight?: FontWeight;
        readonly fontSize: number;
        readonly fontFamily: string;
        readonly fill: string;
    };
}
export interface HistogramSeriesNodeClickEvent extends TypedEvent {
    readonly type: 'nodeClick';
    readonly event: MouseEvent;
    readonly series: HistogramSeries;
    readonly datum: any;
    readonly xKey: string;
}
export declare type HistogramAggregation = 'count' | 'sum' | 'mean';
export declare class HistogramBin {
    data: any[];
    aggregatedValue: number;
    frequency: number;
    domain: [number, number];
    constructor([domainMin, domainMax]: [number, number]);
    addDatum(datum: any): void;
    readonly domainWidth: number;
    readonly relativeHeight: number;
    calculateAggregatedValue(aggregationName: HistogramAggregation, yKey: string): void;
    getY(areaPlot: boolean): number;
}
export declare class HistogramSeries extends CartesianSeries {
    static className: string;
    static type: string;
    private rectGroup;
    private textGroup;
    private rectSelection;
    private textSelection;
    private binnedData;
    private xDomain;
    private yDomain;
    readonly label: HistogramSeriesLabel;
    private seriesItemEnabled;
    tooltipRenderer?: (params: HistogramTooltipRendererParams) => string | TooltipRendererResult;
    fill: string | undefined;
    stroke: string | undefined;
    fillOpacity: number;
    strokeOpacity: number;
    lineDash?: number[];
    lineDashOffset: number;
    constructor();
    directionKeys: {
        x: string[];
        y: string[];
    };
    getKeys(direction: ChartAxisDirection): string[];
    protected _xKey: string;
    xKey: string;
    private _areaPlot;
    areaPlot: boolean;
    private _bins;
    bins: [number, number][];
    private _aggregation;
    aggregation: HistogramAggregation;
    private _binCount;
    binCount: number;
    protected _xName: string;
    xName: string;
    protected _yKey: string;
    yKey: string;
    protected _yName: string;
    yName: string;
    private _strokeWidth;
    strokeWidth: number;
    private _shadow?;
    shadow: DropShadow | undefined;
    highlightStyle: HighlightStyle;
    onHighlightChange(): void;
    setColors(fills: string[], strokes: string[]): void;
    protected highlightedDatum?: HistogramNodeDatum;
    private deriveBins;
    private placeDataInBins;
    readonly xMax: number;
    processData(): boolean;
    getDomain(direction: ChartAxisDirection): any[];
    fireNodeClickEvent(event: MouseEvent, datum: HistogramNodeDatum): void;
    update(): void;
    private generateNodeData;
    private updateRectSelection;
    private updateRectNodes;
    private updateTextSelection;
    private updateTextNodes;
    getTooltipHtml(nodeDatum: HistogramNodeDatum): string;
    listSeriesItems(legendData: LegendDatum[]): void;
    toggleSeriesItem(itemId: string, enabled: boolean): void;
}


text:
package org.apache.tinkerpop.gremlin.driver;

import org.apache.tinkerpop.gremlin.driver.message.RequestMessage;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class ResultSetTest extends AbstractResultQueueTest {

    private static final Map<String,Object> ATTRIBUTES = new HashMap<String,Object>() {{
        put("this", "that");
    }};

    private ResultSet resultSet;

    @Before
    public void setupThis() {
        resultSet = new ResultSet(resultQueue, pool, readCompleted, RequestMessage.build("traversal").create(), null);
    }

    @Test
    public void shouldReturnEmptyMapForNoResponseAttributes() throws Exception {
        final CompletableFuture<Map<String,Object>> attrs = resultSet.statusAttributes();
        readCompleted.complete(null);
        assertThat(attrs.get().isEmpty(), is(true));
    }

    @Test
    public void shouldHaveAllItemsAvailableAsynchronouslyOnReadComplete() throws InterruptedException {
        final CompletableFuture<Void> all = resultSet.allItemsAvailableAsync();
        assertThat(all.isDone(), is(false));
        readCompleted.complete(null);
        // flush all tasks in pool
        pool.awaitTermination(2, TimeUnit.SECONDS);
        assertThat(all.isDone(), is(true));
    }

    @Test
    public void shouldHaveAllItemsAvailableAsynchronouslyOnReadCompleteExceptionally() throws InterruptedException {
        final CompletableFuture<Void> all = resultSet.allItemsAvailableAsync();
        assertThat(all.isDone(), is(false));
        readCompleted.completeExceptionally(new RuntimeException());
        // flush all tasks in pool
        pool.awaitTermination(2, TimeUnit.SECONDS);
        assertThat(all.isDone(), is(true));
        assertThat(all.isCompletedExceptionally(), is(true));
    }

    @Test
    public void shouldHaveStatusAttributesCompleteOnReadComplete() throws InterruptedException {
        final CompletableFuture<Map<String,Object>> attrbFut = resultSet.statusAttributes();
        readCompleted.complete(null);
        // flush all tasks in pool
        pool.awaitTermination(2, TimeUnit.SECONDS);
        assertThat(attrbFut.isDone(), is(true));
    }

    @Test
    public void shouldHaveStatusAttributesCompleteOnReadCompleteExceptionally() throws InterruptedException {
        final CompletableFuture<Map<String,Object>> attrbFut = resultSet.statusAttributes();
        readCompleted.completeExceptionally(new RuntimeException());
        // flush all tasks in pool
        pool.awaitTermination(2, TimeUnit.SECONDS);
        assertThat(attrbFut.isDone(), is(true));
        assertThat(attrbFut.isCompletedExceptionally(), is(true));
    }

    @Test
    public void shouldHaveAllItemsAvailableOnReadComplete() throws InterruptedException {
        assertThat(resultSet.allItemsAvailable(), is(false));
        readCompleted.complete(null);
        // flush all tasks in pool
        pool.awaitTermination(2, TimeUnit.SECONDS);
        assertThat(resultSet.allItemsAvailable(), is(true));
    }

    @Test
    public void shouldHaveAllItemsAvailableAsynchronouslyOnReadCompleteWhileLoading() throws Exception {
        final CompletableFuture<Void> all = resultSet.allItemsAvailableAsync();
        assertThat(all.isDone(), is(false));

        final AtomicBoolean atLeastOnce = new AtomicBoolean(false);
        addToQueue(1000, 1, true, true);
        while (!readCompleted.isDone()) {
            atLeastOnce.set(true);
            if (!atLeastOnce.get())
                assertThat(all.isDone(), is(false));
        }

        assertThat(atLeastOnce.get(), is(true));

        // ensure there is enough time for the readComplete to complete the "all" future
        all.get(30000, TimeUnit.MILLISECONDS);
        assertThat(all.isDone(), is(true));
    }

    @Test
    public void shouldHaveAllItemsAvailableOnReadCompleteWhileLoading() throws Exception {
        assertThat(resultSet.allItemsAvailable(), is(false));

        final AtomicBoolean atLeastOnce = new AtomicBoolean(false);
        addToQueue(1000, 1, true, true);
        while (!readCompleted.isDone()) {
            atLeastOnce.set(true);
            if (!atLeastOnce.get())
                assertThat(resultSet.allItemsAvailable(), is(false));
        }

        assertThat(atLeastOnce.get(), is(true));
        assertThat(resultSet.allItemsAvailable(), is(true));
    }

    @Test
    public void shouldAwaitEverythingAndFlushOnMarkCompleted() throws Exception {
        final CompletableFuture<List<Result>> future = resultSet.some(4);
        resultQueue.add(new Result("test1"));
        resultQueue.add(new Result("test2"));
        resultQueue.add(new Result("test3"));

        assertThat(future.isDone(), is(false));
        resultQueue.markComplete(ATTRIBUTES);
        assertThat(future.isDone(), is(true));

        final List<Result> results = future.get();
        assertEquals("test1", results.get(0).getString());
        assertEquals("test2", results.get(1).getString());
        assertEquals("test3", results.get(2).getString());
        assertEquals(3, results.size());

        assertThat(resultSet.allItemsAvailable(), is(true));
        assertEquals(0, resultSet.getAvailableItemCount());

        assertEquals("that", resultQueue.getStatusAttributes().get("this"));
    }

    @Test
    public void shouldGetAllOnlyOnComplete() throws Exception {
        final CompletableFuture<List<Result>> future = resultSet.all();
        resultQueue.add(new Result("test1"));
        resultQueue.add(new Result("test2"));
        resultQueue.add(new Result("test3"));

        assertThat(future.isDone(), is(false));
        resultQueue.markComplete(ATTRIBUTES);

        final List<Result> results = future.get();
        assertEquals("test1", results.get(0).getString());
        assertEquals("test2", results.get(1).getString());
        assertEquals("test3", results.get(2).getString());
        assertEquals(3, results.size());

        assertThat(future.isDone(), is(true));
        assertThat(resultSet.allItemsAvailable(), is(true));
        assertEquals(0, resultSet.getAvailableItemCount());

        assertEquals("that", resultQueue.getStatusAttributes().get("this"));
    }

    @Test
    public void shouldIterate() throws Exception {
        final Iterator itty = resultSet.iterator();
        final AtomicInteger counter = new AtomicInteger(0);

        addToQueue(100, 1, true, true);

        while (itty.hasNext()) {
            itty.next();
            counter.incrementAndGet();
        }

        assertEquals(100, counter.get());
    }

    @Test
    public void shouldIterateWithoutCheckingHasNext() throws Exception {
        final Iterator itty = resultSet.iterator();
        final AtomicInteger counter = new AtomicInteger(0);

        addToQueue(100, 1, true, true);

        for (int ix = 0; ix < 100; ix++) {
            itty.next();
            counter.incrementAndGet();
        }

        assertEquals(100, counter.get());
        assertThat(itty.hasNext(), is(false));
    }

    @Test
    public void shouldIterateAndThenThrowIfCallToNextExceedsAvailableResultItems() throws Exception {
        final Iterator itty = resultSet.iterator();

        addToQueue(3, 1, true, true);

        assertThat(itty.hasNext(), is(true));
        itty.next();
        assertThat(itty.hasNext(), is(true));
        itty.next();
        itty.next();
        assertThat(itty.hasNext(), is(false));

        try {
            itty.next();
            fail("Should throw exception");
        } catch (NoSuchElementException ignore) {
            // this is the right path - an exception should toss here
        }
    }

    @Test
    public void shouldStream() throws Exception {
        final Stream<Result> stream = resultSet.stream();
        final AtomicInteger counter = new AtomicInteger(0);

        addToQueue(100, 1, true, true);

        stream.forEach(r -> counter.incrementAndGet());

        assertEquals(100, counter.get());
    }

    @Test
    public void shouldCallHasNextWithoutSideEffect() throws Exception {
        final Iterator itty = resultSet.iterator();
        final AtomicInteger counter = new AtomicInteger(0);

        addToQueue(100, 1, true, true);

        for (int i = 0; i < 101; i++) {
        	assertThat(itty.hasNext(), is(true));
        }

        while (itty.hasNext()) {
            itty.next();
            counter.incrementAndGet();
        }

        assertEquals(100, counter.get());
    }
}


text:
import pygame
# import PyQt4, OpenGL

import geometry

class Trigger(object):

	'''
	Docstring goes here

	'''

	def __init__(self, bbox, ontriggered):

		'''
		Docstring goes here

		'''

		self.bbox = bbox
		self.ontriggered = ontriggered

	def trigger(self, position):
		# TODO: Provide arguments to ontriggered (?)
		if position in self.bbox:
			self.ontriggered()

class App(object):

	'''
	Docstring goes here

	'''

	def __init__(self):

		#
		self.size = 720, 480
		self.title = 'Sir Jon'

		self.running = True

		#
		pygame.init()
		self.surface = pygame.display.set_mode(self.size)
		self.clock = pygame.time.Clock()

		# Events
		self.listeners = {
			pygame.QUIT: lambda e: self.quit(),
			pygame.MOUSEMOTION: lambda e: None,
			pygame.MOUSEBUTTONDOWN: lambda e: None,
			pygame.MOUSEBUTTONDOWN: lambda e: None
		}

		self.noop = lambda event: None #

	def run(self):
		self.mainloop()

	def quit(self):
		self.running = False

	def mainloop(self):
		while self.running:
			event = pygame.event.poll()                      # Poll the event queue
			self.listeners.get(event.type, self.noop)(event) # Dispatch

def main():

	'''
	Docstring goes here

	'''

	App().run()

if __name__ == '__main__':
	main()


text:
from django.core.urlresolvers import reverse
from django.views.generic import RedirectView, TemplateView

class HomeView(TemplateView):
    """
    This is the home page and will typically live at /
    """
    template_name = 'promotions/home.html'

class RecordClickView(RedirectView):
    """
    Simple RedirectView that helps recording clicks made on promotions
    """
    permanent = False
    model = None

    def get_redirect_url(self, **kwargs):
        try:
            prom = self.model.objects.get(pk=kwargs['pk'])
        except self.model.DoesNotExist:
            return reverse('promotions:home')

        if prom.promotion.has_link:
            prom.record_click()
            return prom.link_url
        return reverse('promotions:home')


text:
<?php
date_default_timezone_set('UTC');
define('ROOT_PATH', dirname(__FILE__) . '/');
define('TIME_START', microtime(true));
chdir(ROOT_PATH);

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

if (version_compare(PHP_VERSION, '5.6.0', '<=')) {
  ini_set('mbstring.internal_encoding', 'UTF-8');
  ini_set('mbstring.func_overload', 7);
  ini_set('iconv.internal_encoding', 'UTF-8');
}

ini_set('default_charset', 'UTF-8');

function autoload($class_name) {
  $class_name = strtolower($class_name);

  $libs_path = ROOT_PATH . '/libs/' . $class_name . '.class.php';
  $models_path = ROOT_PATH . '/models/' . $class_name . '.php';

  if (file_exists($libs_path)) {
    include $libs_path;
    return;
  }

  if (file_exists($models_path)) {
    include $models_path;
    return;
  }

  trigger_error('class ' . $class_name . ' not found');
  exit;
}

include(ROOT_PATH . '/system/common.php');

spl_autoload_register('autoload');
set_error_handler(array('ErrorHandler', 'handleError'), E_ALL | E_STRICT);
register_shutdown_function(array('App', 'shutdown'));

App::run();
?>


text:
package org.kie.api.builder;

import org.kie.api.io.Resource;

/**
 * KieRepository is a singleton acting as a repository for all the available KieModules
 * regardless if they are stored in the maven repository or programmatically built by the user
 */
public interface KieRepository {

    /**
     * Returns the default ReleaseId used to identify a KieModule in this KieRepository
     * if the user didn't explicitly provide one
     * @return The default ReleaseId
     */
    ReleaseId getDefaultReleaseId();

    /**
     * Adds a new KieModule to this KieRepository
     */
    void addKieModule(KieModule kModule);

    /**
     * Creates a new KieModule using the provided resource and dependencies
     * and automatically adds it to this KieRepository
     * @param resource
     * @param dependencies
     * @return The newly created KieModule
     */
    KieModule addKieModule(Resource resource, Resource... dependencies);

    /**
     * Retrieve a KieModule with the given ReleaseId in this KieRepository.
     * It is possible to use maven's conventions and version ranges like in
     *

     *     KieModule kieModule = kieRepository.getKieModule( KieServices.Factory.get().newReleaseId("group", "artifact", "LATEST") );
     *

     * or
     *

     *     KieModule kieModule = kieRepository.getKieModule( KieServices.Factory.get().newReleaseId("group", "artifact", "[1.0,1.2)") );
     *

     * @param releaseId The releaseId identifying the KieModule to be returned
     * @return The KieModule identified by the given releaseId or null if such KieModule doesn't exist
     */
    KieModule getKieModule(ReleaseId releaseId);

    /**
     * Remove a no longer useful KieModule, identified by the given ReleaseId, from this KieRepository
     * @param releaseId The releaseId identifying the KieModule to be removed
     * @return The removed KieModule or null if such KieModule didn't exist
     */
    KieModule removeKieModule(ReleaseId releaseId);
}


text:
This example cookbook demonstrates how you could wrap the audit cookbook with a customizable internal cookbook. This might be done to easily change default attributes set in the audit cookbook.  The wrapper also helps you control the versioning of the audit cookbook in your environment.  It can also be useful to help create roles to target where the audit cookbook applies, or even set attributes on nodes to apply Compliance profiles (if you had some you want to run on all machines).

## Requirements

### Platforms
- Windows Server 2008 R2
- Windows Server 2012
- Windows Server 2012 R2
- Ubuntu 12.04
- Ubuntu 14.04

### Chef

- Chef 12+

### Cookbooks

- `audit`
- `automate_win`

## Attributes

There are no custom attributes for this cookbook.

## Usage

Include `wrapper_audit::default` in a node's `run_list`.  This will also pull down the community audit cookbook, which is used to run Chef Compliance profiles.  These profiles will create a report and send it to Chef Compliance or Chef Automate, depending on your `['audit']['reporter']` setting.

This cookbook also consumes the example cookbook `automate_win`, which demonstrates how to setup chef-client to ingest Chef Automate data.


text:
import math
import numpy as np
import torch
import copy

# eps for numerical stability
DEBUG = True
eps = 1e-6

if DEBUG:
  import logging
  logging.basicConfig(filename="./num.log",level=logging.DEBUG)

class YFOptimizer(object):
  def __init__(self, var_list, lr=0.1, mu=0.0, clip_thresh=None, weight_decay=0.0,
    beta=0.999, curv_win_width=20, zero_debias=True, sparsity_debias=True, delta_mu=0.0,
    auto_clip_fac=None, force_non_inc_step=False, lr_grad_norm_thresh=1.0,
    h_max_log_smooth=False, h_min_log_smooth=False, checkpoint_interval=500):
    '''
    clip thresh is the threshold value on ||lr * gradient||
    delta_mu can be place holder/variable/python scalar. They are used for additional
    momentum in situations such as asynchronous-parallel training. The default is 0.0
    for basic usage of the optimizer.
    Args:
      lr: python scalar. The initial value of learning rate, we use 1.0 in our paper.
      mu: python scalar. The initial value of momentum, we use 0.0 in our paper.
      clip_thresh: python scalar. The manaully-set clipping threshold for tf.clip_by_global_norm.
        if None, the automatic clipping can be carried out. The automatic clipping
        feature is parameterized by argument auto_clip_fac. The auto clip feature
        can be switched off with auto_clip_fac = None
      beta: python scalar. The smoothing parameter for estimations.
      sparsity_debias: gradient norm and curvature are biased to larger values when
      calculated with sparse gradient. This is useful when the model is very sparse,
      e.g. LSTM with word embedding. For non-sparse CNN, turning it off could slightly
      accelerate the speed.
      delta_mu: for extensions. Not necessary in the basic use.
      force_non_inc_step: in some very rare cases, it is necessary to force ||lr * gradient||
      to be not increasing dramatically for stableness after some iterations.
      In practice, if turned on, we enforce lr * sqrt(smoothed ||grad||^2)
      to be less than 2x of the minimal value of historical value on smoothed || lr * grad ||.
      This feature is turned off by default.
    Other features:
      If you want to manually control the learning rates, self.lr_factor is
      an interface to the outside, it is an multiplier for the internal learning rate
      in YellowFin. It is helpful when you want to do additional hand tuning
      or some decaying scheme to the tuned learning rate in YellowFin.
      Example on using lr_factor can be found here:
      https://github.com/JianGoForIt/YellowFin_Pytorch/blob/master/pytorch-cifar/main.py#L109
    '''
    self._lr = lr
    self._mu = mu
    # we convert var_list from generator to list so that
    # it can be used for multiple times
    self._var_list = list(var_list)
    self._clip_thresh = clip_thresh
    self._auto_clip_fac = auto_clip_fac
    self._beta = beta
    self._curv_win_width = curv_win_width
    self._zero_debias = zero_debias
    self._sparsity_debias = sparsity_debias
    self._force_non_inc_step = force_non_inc_step
    self._optimizer = torch.optim.SGD(self._var_list, lr=self._lr,
      momentum=self._mu, weight_decay=weight_decay)
    self._iter = 0
    # global states are the statistics
    self._global_state = {}

    # for decaying learning rate and etc.
    self._lr_factor = 1.0

    # lr threshold
    self._lr_grad_norm_thresh = lr_grad_norm_thresh

    # smoothing options
    self._h_max_log_smooth = h_max_log_smooth
    self._h_min_log_smooth = h_min_log_smooth

    # checkpoint interval
    self._checkpoint_interval = checkpoint_interval

    if DEBUG:
      logging.debug('This message should go to the log file')

  def state_dict(self):
    # for checkpoint saving
    sgd_state_dict = self._optimizer.state_dict()
    # for recover model internally in case of numerical issue
    model_state_list = [p.data \
      for group in self._optimizer.param_groups for p in group['params'] ]
    global_state = self._global_state
    lr_factor = self._lr_factor
    iter = self._iter
    lr = self._lr
    mu = self._mu
    clip_thresh = self._clip_thresh
    beta = self._beta
    curv_win_width = self._curv_win_width
    zero_debias = self._zero_debias
    h_min = self._h_min
    h_max = self._h_max

    return {
      "sgd_state_dict": sgd_state_dict,
      "model_state_list": model_state_list,
      "global_state": global_state,
      "lr_factor": lr_factor,
      "iter": iter,
      "lr": lr,
      "mu": mu,
      "clip_thresh": clip_thresh,
      "beta": beta,
      "curv_win_width": curv_win_width,
      "zero_debias": zero_debias,
      "h_min": h_min,
      "h_max": h_max
    }

  def load_state_dict(self, state_dict):
    # for checkpoint saving
    self._optimizer.load_state_dict(state_dict['sgd_state_dict'])
    # for recover model internally if any numerical issue happens
    param_id = 0
    for group in self._optimizer.param_groups:
      for p in group["params"]:
        p.data = state_dict["model_state_list"][param_id]
        param_id += 1
    self._global_state = state_dict['global_state']
    self._lr_factor = state_dict['lr_factor']
    self._iter = state_dict['iter']
    self._lr = state_dict['lr']
    self._mu = state_dict['mu']
    self._clip_thresh = state_dict['clip_thresh']
    self._beta = state_dict['beta']
    self._curv_win_width = state_dict['curv_win_width']
    self._zero_debias = state_dict['zero_debias']
    self._h_min = state_dict["h_min"]
    self._h_max = state_dict["h_max"]
    return

  def set_lr_factor(self, factor):
    self._lr_factor = factor
    return

  def get_lr_factor(self):
    return self._lr_factor

  def zero_grad(self):
    self._optimizer.zero_grad()
    return

  def zero_debias_factor(self):
    return 1.0 - self._beta ** (self._iter + 1)

  def zero_debias_factor_delay(self, delay):
    # for exponentially averaged stat which starts at non-zero iter
    return 1.0 - self._beta ** (self._iter - delay + 1)

  def curvature_range(self):
    global_state = self._global_state
    if self._iter == 0:
      global_state["curv_win"] = torch.FloatTensor(self._curv_win_width, 1).zero_()
    curv_win = global_state["curv_win"]
    grad_norm_squared = self._global_state["grad_norm_squared"]
    # curv_win[self._iter % self._curv_win_width] = np.log(grad_norm_squared + eps)
    curv_win[self._iter % self._curv_win_width] = grad_norm_squared
    valid_end = min(self._curv_win_width, self._iter + 1)
    # we use running average over log scale, accelerating
    # h_max / min in the begining to follow the varying trend of curvature.
    beta = self._beta
    if self._iter == 0:
      global_state["h_min_avg"] = 0.0
      global_state["h_max_avg"] = 0.0
      self._h_min = 0.0
      self._h_max = 0.0
    if self._h_min_log_smooth:
      global_state["h_min_avg"] = \
        global_state["h_min_avg"] * beta + (1 - beta) * torch.min(np.log(curv_win[:valid_end] + eps) )
    else:
      global_state["h_min_avg"] = \
        global_state["h_min_avg"] * beta + (1 - beta) * torch.min(curv_win[:valid_end] )
    if self._h_max_log_smooth:
      global_state["h_max_avg"] = \
        global_state["h_max_avg"] * beta + (1 - beta) * torch.max(np.log(curv_win[:valid_end] + eps) )
    else:
      global_state["h_max_avg"] = \
        global_state["h_max_avg"] * beta + (1 - beta) * torch.max(curv_win[:valid_end] )
    if self._zero_debias:
      debias_factor = self.zero_debias_factor()
      if self._h_min_log_smooth:
        self._h_min = np.exp(global_state["h_min_avg"] / debias_factor)
      else:
        self._h_min = global_state["h_min_avg"] / debias_factor
      if self._h_max_log_smooth:
        self._h_max = np.exp(global_state["h_max_avg"] / debias_factor)
      else:
        self._h_max = global_state["h_max_avg"] / debias_factor
    else:
      if self._h_min_log_smooth:
        self._h_min = np.exp(global_state["h_min_avg"] )
      else:
        self._h_min = global_state["h_min_avg"]
      if self._h_max_log_smooth:
        self._h_max = np.exp(global_state["h_max_avg"] )
      else:
        self._h_max = global_state["h_max_avg"]
    if self._sparsity_debias:
      self._h_min *= self._sparsity_avg
      self._h_max *= self._sparsity_avg
    return

  def grad_variance(self):
    global_state = self._global_state
    beta = self._beta
    self._grad_var = np.array(0.0, dtype=np.float32)
    for group_id, group in enumerate(self._optimizer.param_groups):
      for p_id, p in enumerate(group['params'] ):
        if p.grad is None:
          continue
        grad = p.grad.data
        state = self._optimizer.state[p]
        if self._iter == 0:
          state["grad_avg"] = grad.new().resize_as_(grad).zero_()
          state["grad_avg_squared"] = 0.0
        state["grad_avg"].mul_(beta).add_(1 - beta, grad)
        self._grad_var += torch.sum(state["grad_avg"] * state["grad_avg"] )

    if self._zero_debias:
      debias_factor = self.zero_debias_factor()
    else:
      debias_factor = 1.0

    self._grad_var /= -(debias_factor**2)
    self._grad_var += global_state['grad_norm_squared_avg'] / debias_factor
    # in case of negative variance: the two term are using different debias factors
    self._grad_var = max(self._grad_var, eps)
    if self._sparsity_debias:
      self._grad_var *= self._sparsity_avg
    return

  def dist_to_opt(self):
    global_state = self._global_state
    beta = self._beta
    if self._iter == 0:
      global_state["grad_norm_avg"] = 0.0
      global_state["dist_to_opt_avg"] = 0.0
    global_state["grad_norm_avg"] = \
      global_state["grad_norm_avg"] * beta + (1 - beta) * math.sqrt(global_state["grad_norm_squared"] )
    global_state["dist_to_opt_avg"] = \
      global_state["dist_to_opt_avg"] * beta \
      + (1 - beta) * global_state["grad_norm_avg"] / (global_state['grad_norm_squared_avg'] + eps)
    if self._zero_debias:
      debias_factor = self.zero_debias_factor()
      self._dist_to_opt = global_state["dist_to_opt_avg"] / debias_factor
    else:
      self._dist_to_opt = global_state["dist_to_opt_avg"]
    if self._sparsity_debias:
      self._dist_to_opt /= (np.sqrt(self._sparsity_avg) + eps)
    return

  def grad_sparsity(self):
    global_state = self._global_state
    if self._iter == 0:
      global_state["sparsity_avg"] = 0.0
    non_zero_cnt = 0.0
    all_entry_cnt = 0.0
    for group in self._optimizer.param_groups:
      for p in group['params']:
        if p.grad is None:
          continue
        grad = p.grad.data
        grad_non_zero = grad.nonzero()
        if grad_non_zero.dim() > 0:
          non_zero_cnt += grad_non_zero.size()[0]
        all_entry_cnt += torch.numel(grad)
    beta = self._beta
    global_state["sparsity_avg"] = beta * global_state["sparsity_avg"] \
      + (1 - beta) * non_zero_cnt / float(all_entry_cnt)
    self._sparsity_avg = \
      global_state["sparsity_avg"] / self.zero_debias_factor()

    if DEBUG:
      logging.debug("sparsity %f, sparsity avg %f", non_zero_cnt / float(all_entry_cnt), self._sparsity_avg)

    return

  def lr_grad_norm_avg(self):
    # this is for enforcing lr * grad_norm not
    # increasing dramatically in case of instability.
    #  Not necessary for basic use.
    global_state = self._global_state
    beta = self._beta
    if "lr_grad_norm_avg" not in global_state:
      global_state['grad_norm_squared_avg_log'] = 0.0
    global_state['grad_norm_squared_avg_log'] = \
      global_state['grad_norm_squared_avg_log'] * beta \
      + (1 - beta) * np.log(global_state['grad_norm_squared'] + eps)
    if "lr_grad_norm_avg" not in global_state:
      global_state["lr_grad_norm_avg"] = \
        0.0 * beta + (1 - beta) * np.log(self._lr * np.sqrt(global_state['grad_norm_squared'] ) + eps)
      # we monitor the minimal smoothed ||lr * grad||
      global_state["lr_grad_norm_avg_min"] = \
        np.exp(global_state["lr_grad_norm_avg"] / self.zero_debias_factor() )
    else:
      global_state["lr_grad_norm_avg"] = global_state["lr_grad_norm_avg"] * beta \
        + (1 - beta) * np.log(self._lr * np.sqrt(global_state['grad_norm_squared'] ) + eps)
      global_state["lr_grad_norm_avg_min"] = \
        min(global_state["lr_grad_norm_avg_min"],
            np.exp(global_state["lr_grad_norm_avg"] / self.zero_debias_factor() ) )

  def before_apply(self):
    # compute running average of gradient and norm of gradient
    beta = self._beta
    global_state = self._global_state
    if self._iter == 0:
      global_state["grad_norm_squared_avg"] = 0.0

    global_state["grad_norm_squared"] = 0.0
    for group_id, group in enumerate(self._optimizer.param_groups):
      for p_id, p in enumerate(group['params'] ):
        if p.grad is None:
          continue
        grad = p.grad.data
        param_grad_norm_squared = torch.sum(grad * grad)
        global_state['grad_norm_squared'] += param_grad_norm_squared

        if DEBUG:
          logging.debug("Iteration  %f", self._iter)
          logging.debug("param grad squared gid %d, pid %d, %f, %f", group_id, p_id, param_grad_norm_squared,
            np.log(param_grad_norm_squared) / np.log(10) )

    global_state['grad_norm_squared_avg'] = \
      global_state['grad_norm_squared_avg'] * beta + (1 - beta) * global_state['grad_norm_squared']

    if DEBUG:
      logging.debug("overall grad norm squared %f, %f",
        global_state['grad_norm_squared'], np.log(global_state['grad_norm_squared'] ) / np.log(10))

    if self._sparsity_debias:
      self.grad_sparsity()

    self.curvature_range()
    self.grad_variance()
    self.dist_to_opt()

    if DEBUG:
      logging.debug("h_min %f, %f", self._h_min, np.log(self._h_min) )
      logging.debug("h_max %f, %f", self._h_max, np.log(self._h_max) )
      logging.debug("dist %f, %f", self._dist_to_opt, np.log(self._dist_to_opt) )
      logging.debug("var %f, %f", self._grad_var, np.log(self._grad_var) )

    if self._iter > 0:
      self.get_mu()
      self.get_lr()

      self._lr = beta * self._lr + (1 - beta) * self._lr_t
      self._mu = beta * self._mu + (1 - beta) * self._mu_t

      if DEBUG:
        logging.debug("lr_t %f", self._lr_t)
        logging.debug("mu_t %f", self._mu_t)
        logging.debug("lr %f", self._lr)
        logging.debug("mu %f", self._mu)

    return

  def get_lr(self):
    self._lr_t = (1.0 - math.sqrt(self._mu_t) )**2 / (self._h_min + eps)
    return

  def get_cubic_root(self):
    # We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2
    # where x = sqrt(mu).
    # We substitute x, which is sqrt(mu), with x = y + 1.
    # It gives y^3 + py = q
    # where p = (D^2 h_min^2)/(2*C) and q = -p.
    # We use the Vieta's substution to compute the root.
    # There is only one real solution y (which is in [0, 1] ).
    # http://mathworld.wolfram.com/VietasSubstitution.html
    # eps in the numerator is to prevent momentum = 1 in case of zero gradient
    p = (self._dist_to_opt + eps)**2 * (self._h_min + eps)**2 / 2 / (self._grad_var + eps)
    w3 = (-math.sqrt(p**2 + 4.0 / 27.0 * p**3) - p) / 2.0
    w = math.copysign(1.0, w3) * math.pow(math.fabs(w3), 1.0/3.0)
    y = w - p / 3.0 / (w + eps)
    x = y + 1

    if DEBUG:
      logging.debug("p %f, den %f", p, self._grad_var + eps)
      logging.debug("w3 %f ", w3)
      logging.debug("y %f, den %f", y, w + eps)

    return x

  def get_mu(self):
    root = self.get_cubic_root()
    dr = (self._h_max + eps) / (self._h_min + eps)
    self._mu_t = max(root**2, ( (np.sqrt(dr) - 1) / (np.sqrt(dr) + 1) )**2 )
    return

  def update_hyper_param(self):
    for group in self._optimizer.param_groups:
      group['momentum'] = self._mu
      if self._force_non_inc_step == False:
        group['lr'] = min(self._lr * self._lr_factor,
          self._lr_grad_norm_thresh / (math.sqrt(self._global_state["grad_norm_squared"] ) + eps) )
      elif self._iter > self._curv_win_width:
        # force to guarantee lr * grad_norm not increasing dramatically.
        # Not necessary for basic use. Please refer to the comments
        # in YFOptimizer.__init__ for more details
        self.lr_grad_norm_avg()
        debias_factor = self.zero_debias_factor()
        group['lr'] = min(self._lr * self._lr_factor,
          2.0 * self._global_state["lr_grad_norm_avg_min"] \
          / (np.sqrt(np.exp(self._global_state['grad_norm_squared_avg_log'] / debias_factor) ) + eps) )
    return

  def auto_clip_thresh(self):
    # Heuristic to automatically prevent sudden exploding gradient
    # Not necessary for basic use.
    return math.sqrt(self._h_max) * self._auto_clip_fac

  def step(self):
    # add weight decay
    for group in self._optimizer.param_groups:
      for p in group['params']:
        if p.grad is None:
            continue
        grad = p.grad.data

        if group['weight_decay'] != 0:
            grad = grad.add(group['weight_decay'], p.data)

    if self._clip_thresh != None:
      torch.nn.utils.clip_grad_norm(self._var_list, self._clip_thresh)
    elif (self._iter != 0 and self._auto_clip_fac != None):
      # do not clip the first iteration
      torch.nn.utils.clip_grad_norm(self._var_list, self.auto_clip_thresh() )

    if True:#try:
      # before appply
      self.before_apply()

      # update learning rate and momentum
      self.update_hyper_param()

      # apply update
      self._optimizer.step()

      # periodically save model and states
      if self._iter % self._checkpoint_interval == 1:
        self._state_checkpoint = copy.deepcopy(self.state_dict() )

      self._iter += 1
    #except:
    #  # load the last checkpoint
    #  logging.warning("Numerical issue triggered restore with backup states. Resumed from last internal checkpoint.")
    #  self.load_state_dict(self._state_checkpoint)

    return


text:
package com.helospark.lightdi.definitioncollector;

import static com.helospark.lightdi.util.AnnotationUtil.hasAnnotation;
import static com.helospark.lightdi.util.BeanNameGenerator.createBeanNameForStereotypeAnnotatedClass;
import static com.helospark.lightdi.util.BeanNameGenerator.createQualifierForMethodAnnotatedWithBean;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;

import com.helospark.lightdi.annotation.Bean;
import com.helospark.lightdi.annotation.Configuration;
import com.helospark.lightdi.conditional.ConditionalAnnotationsExtractor;
import com.helospark.lightdi.conditional.condition.DependencyCondition;
import com.helospark.lightdi.descriptor.DependencyDescriptor;
import com.helospark.lightdi.descriptor.bean.BeanDependencyDescriptor;
import com.helospark.lightdi.descriptor.stereotype.StereotypeDependencyDescriptor;
import com.helospark.lightdi.util.AnnotationUtil;
import com.helospark.lightdi.util.BeanOrderExtractor;
import com.helospark.lightdi.util.IsLazyExtractor;
import com.helospark.lightdi.util.IsPrimaryExtractor;
import com.helospark.lightdi.util.LightDiAnnotation;
import com.helospark.lightdi.util.QualifierExtractor;

public class ConfigurationClassBeanDefinitionCollectorChainItem implements BeanDefinitionCollectorChainItem {
    private ConditionalAnnotationsExtractor conditionalAnnotationsExtractor;

    public ConfigurationClassBeanDefinitionCollectorChainItem(
            ConditionalAnnotationsExtractor conditionalAnnotationsExtractor) {
        this.conditionalAnnotationsExtractor = conditionalAnnotationsExtractor;
    }

    @Override
    public List<DependencyDescriptor> collectDefinitions(Class<?> clazz) {
        if (hasAnnotation(clazz, Configuration.class)) {
            List<DependencyDescriptor> result = new ArrayList<>();
            StereotypeDependencyDescriptor configurationDescriptor = createConfigurationBeanDescriptor(clazz);
            result.add(configurationDescriptor);
            result.addAll(collectBeanMethodDescriptors(clazz, configurationDescriptor));
            return result;
        } else {
            return Collections.emptyList();
        }
    }

    private StereotypeDependencyDescriptor createConfigurationBeanDescriptor(Class<?> clazz) {
        return StereotypeDependencyDescriptor.builder().withClazz(clazz)
                .withQualifier(createBeanNameForStereotypeAnnotatedClass(clazz))
                .withScope(QualifierExtractor.extractScope(clazz)).withIsLazy(IsLazyExtractor.isLazy(clazz))
                .withIsPrimary(IsPrimaryExtractor.isPrimary(clazz))
                .withConditions(conditionalAnnotationsExtractor.extractConditions(clazz))
                .withMergedAnnotations(AnnotationUtil.getAllMergedAnnotations(clazz))
                .build();
    }

    private SortedSet<DependencyDescriptor> collectBeanMethodDescriptors(Class<?> clazz,
            StereotypeDependencyDescriptor configurationDescriptor) {
        return Arrays.stream(clazz.getDeclaredMethods())
                .filter(method -> hasAnnotation(method, Bean.class))
                .map(method -> createDescriptor(method, configurationDescriptor))
                .collect(Collectors.toCollection(() -> new TreeSet<>()));
    }

    private DependencyDescriptor createDescriptor(Method method,
            StereotypeDependencyDescriptor configurationDescriptor) {
        Class<?> returnType = method.getReturnType();
        return BeanDependencyDescriptor.builder()
                .withClazz(returnType)
                .withGenericType(method.getGenericReturnType())
                .withScope(QualifierExtractor.extractScope(method)).withMethod(method)
                .withQualifier(createQualifierForMethodAnnotatedWithBean(method))
                .withIsLazy(IsLazyExtractor.isLazy(method)).withIsPrimary(IsPrimaryExtractor.isPrimary(method))
                .withConfigurationDescriptor(configurationDescriptor)
                .withConditions(getConditions(method, configurationDescriptor))
                .withOrder(BeanOrderExtractor.extractOrder(method))
                .withMergedAnnotations(mergeSets(AnnotationUtil.getAllMergedAnnotations(method), configurationDescriptor.getMergedAnnotations()))
                .build();
    }

    private Set<LightDiAnnotation> mergeSets(Set<LightDiAnnotation> a, Set<LightDiAnnotation> b) {
        Set<LightDiAnnotation> result = new HashSet<>();
        result.addAll(a);
        result.addAll(b);
        return result;
    }

    private List<DependencyCondition> getConditions(Method method,
            StereotypeDependencyDescriptor configurationDescriptor) {
        List<DependencyCondition> conditions = new ArrayList<>();
        conditions.addAll(configurationDescriptor.getConditions());
        conditions.addAll(conditionalAnnotationsExtractor.extractConditions(method));
        return conditions;
    }

}


text:
<?php
/**
 *
 *
 * @author Sebastian Lagemann <sebastian@iqu.com>
 */

namespace Iqu\Sdk\Event;

use Iqu\Sdk\Traits\EventGetData;

class Marketing extends \Iqu\Sdk\Event {
	use EventGetData;

	const TYPE = 'marketing';

	private $partner;
	private $campaign;
	private $ad;
	private $subid;
	private $subsubid;

	public function getPartner() {
		return $this->partner;
	}
	public function setPartner($value) {
		$this->partner = strval($value);
		return $this;
	}

	public function getCampaign() {
		return $this->campaign;
	}
	public function setCampaign($value) {
		$this->campaign = strval($value);
		return $this;
	}

	public function getAd() {
		return $this->ad;
	}
	public function setAd($value) {
		$this->ad = strval($value);
		return $this;
	}

	public function getSubId() {
		return $this->subid;
	}
	public function setSubId($value) {
		$this->subid = strval($value);
		return $this;
	}

	public function getSubSubId() {
		return $this->subsubid;
	}
	public function setSubSubId($value) {
		$this->subsubid = strval($value);
		return $this;
	}
}

?>