text:
/* globals protractor, element, by, browser */
/**
 * @ngdoc overview
 * @name ui.grid.e2eTestLibrary
 * @description
 * End to end test functions.  Whenever these are updated, it may also be necessary
 * to update the associated tutorial.
 *
 */

/**
 * @ngdoc service
 * @name ui.grid.e2eTestLibrary.api:gridTest
 * @description
 * End to end test functions.  Whenever these are updated, it may also be necessary
 * to update the associated tutorial.
 *
 */
module.exports = {
  /**
  * Helper function for returning a grid element.
  * @param gridId Id of grid to return.
  *
  * @returns {ElementFinder|Grid}  Grid wrapped in an ElementFinder
  *
  * @example
  *

  *   var grid = gridTestUtils.getGrid( 'myGrid' ); //or internally
  *   var row = this.getGrid( gridId );
  *

  */
  getGrid: function( gridId ) {
    return element( by.id( gridId ) );
  },

  /**
  * Helper function for returning a row.
  *
  * @param gridId {string}
  * @param rowNum {integer}
  *
  * @returns {ElementFinder|*}
  *
  * @example
  *

  *   var row = gridTestUtils.getRow( 'myGrid', 0); //or internally
  *   var row = this.getRow( gridId, rowNum );
  *

  */
  getRow: function( gridId, rowNum ) {
    return this.getGrid( gridId ).element( by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index').row( rowNum )  );
  },

  /**
  * Helper function to select a row.
  *
  * @param gridId {string}
  * @param rowNum {integer}
  *
  *
  * @example
  *

  *   var row = gridTestUtils.selectRow( 'myGrid', 0 );
  *

  */
  selectRow: function( gridId, rowNum ) {
    this.getRow( gridId, rowNum ).click();
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectRowCount
  * @description Checks that a grid has the specified number of rows. Note
  * that this only returns the number of rendered rows, and the grid does
  * row virtualisation - that is that the browser can only see the rendered
  * rows, not all the rows in the dataset.  This method is useful when doing
  * functional tests with small numbers of data, but typically with numbers
  * greater than about 10 you'll find that some of the rows are not rendered
  * and therefore an error is given.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedNumRows the number of visible rows you expect the
  * grid to have
  *
  * @example
  *

  *   gridTestUtils.expectRowCount('myGrid', 2);
  *

  *
  */
  expectRowCount: function( gridId, expectedNumRows ) {

    var rows = this.getGrid( gridId ).all( by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index') );
    expect(rows.count()).toEqual(expectedNumRows);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectHeaderColumnCount
  * @description Checks that a grid header body render container (the default render container)
  * has the specified number of columns.  If you are using pinned columns then you may also want
  * to check expectHeaderLeftColumnCount
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedNumCols the number of visible columns you expect the
  * body to have
  *
  * @example
  *

  *   gridTestUtils.expectHeaderColumnCount('myGrid', 2);
  *

  *
  */
  expectHeaderColumnCount: function( gridId, expectedNumCols ) {
    var headerCols = this.getGrid( gridId ).element( by.css('.ui-grid-render-container-body')).element( by.css('.ui-grid-header') ).all( by.repeater('col in colContainer.renderedColumns track by col.colDef.name') );
    expect(headerCols.count()).toEqual(expectedNumCols);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectHeaderLeftColumnCount
  * @description Checks that a grid header left render container has the specified number of columns.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedNumCols the number of visible columns you expect the
  * left render container to have
  *
  * @example
  *

  *   gridTestUtils.expectHeaderLeftColumnCount('myGrid', 2);
  *

  *
  */
  expectHeaderLeftColumnCount: function( gridId, expectedNumCols ) {
    var headerCols = this.getGrid( gridId ).element( by.css('.ui-grid-render-container-left')).element( by.css('.ui-grid-header') ).all( by.repeater('col in colContainer.renderedColumns track by col.colDef.name') );
    expect(headerCols.count()).toEqual(expectedNumCols);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectFooterColumnCount
  * @description Checks that a grid footer has the specified number of rows.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedNumCols the number of visible columns you expect the
  * grid to have
  *
  * @example
  *

  *   gridTestUtils.expectColumnCount('myGrid', 2);
  *

  *
  */
  expectFooterColumnCount: function( gridId, expectedNumCols ) {
    var footerCols = this.getGrid( gridId ).element( by.css('.ui-grid-footer') ).all( by.repeater('col in colContainer.renderedColumns track by col.colDef.name') );
    expect(footerCols.count()).toEqual(expectedNumCols);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name headerCell
  * @description Internal method used to return a headerCell element
  * given the grid and column
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} col the number of the column (within the visible columns)
  * that you want to return
  *
  * @example
  *

  *   gridTestUtils.headerCell('myGrid', 2);
  *

  *
  */
  headerCell: function( gridId, expectedCol, expectedValue ) {
    return this.getGrid( gridId ).element( by.css('.ui-grid-render-container-body')).element( by.css('.ui-grid-header') ).element( by.repeater('col in colContainer.renderedColumns track by col.colDef.name').row( expectedCol)  );
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name footerCell
  * @description Internal method used to return a footerCell element
  * given the grid and column
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} col the number of the column (within the visible columns)
  * that you want to return
  *
  * @example
  *

  *   gridTestUtils.headerCell('myGrid', 2);
  *

  *
  */
  footerCell: function( gridId, expectedCol, expectedValue ) {
    return this.getGrid( gridId ).element( by.css('.ui-grid-footer') ).element( by.repeater('col in colContainer.renderedColumns track by col.colDef.name').row( expectedCol)  );
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name dataCell
  * @description Internal method used to return a dataCell element
  * given the grid and column, note it only returns from the 'body'
  * render container
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} fetchRow the number of the row (within the visible rows)
  * that you want to return
  * @param {integer} fetchCol the number of the col (within the visible cols)
  * that you want to return
  *
  * @example
  *

  *   myElement = gridTestUtils.dataCell('myGrid', 2, 2);
  *

  *
  */
  dataCell: function( gridId, fetchRow, fetchCol ) {
    var row = this.getGrid( gridId ).element( by.css('.ui-grid-render-container-body')).element( by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index').row( fetchRow )  );
    return row.element( by.repeater('(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name').row( fetchCol ));
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectHeaderCellValueMatch
  * @description Checks that a header cell matches the specified value,
  * takes a regEx or a simple string.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedCol the number of the column (within the visible columns)
  * that you want to check the value of
  * @param {string} expectedValue a regex or string of the value you expect in that header
  *
  * @example
  *

  *   gridTestUtils.expectHeaderCellValueMatch('myGrid', 2, 'HeaderValue');
  *

  *
  */
  expectHeaderCellValueMatch: function( gridId, expectedCol, expectedValue ) {
    var headerCell = this.headerCell( gridId, expectedCol);
    expect(headerCell.getText()).toMatch(expectedValue);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectFooterCellValueMatch
  * @description Checks that a footer cell matches the specified value,
  * takes a regEx or a simple string.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedCol the number of the column (within the visible columns)
  * that you want to check the value of
  * @param {string} expectedValue a regex or string of the value you expect in that footer
  *
  * @example
  *

  *   gridTestUtils.expectFooterCellValueMatch('myGrid', 2, 'FooterValue');
  *

  *
  */
  expectFooterCellValueMatch: function( gridId, expectedCol, expectedValue ) {
    var footerCell = this.footerCell( gridId, expectedCol);
    expect(footerCell.getText()).toMatch(expectedValue);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectCellValueMatch
  * @description Checks that a cell matches the specified value,
  * takes a regEx or a simple string.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedRow the number of the row (within the visible rows)
  * that you want to check the value of
  * @param {integer} expectedCol the number of the column (within the visible columns)
  * that you want to check the value of
  * @param {string} expectedValue a regex or string of the value you expect in that cell
  *
  * @example
  *

  *   gridTestUtils.expectCellValueMatch('myGrid', 0, 2, 'CellValue');
  *

  *
  */
  expectCellValueMatch: function( gridId, expectedRow, expectedCol, expectedValue ) {
    var dataCell = this.dataCell( gridId, expectedRow, expectedCol );
    expect(dataCell.getText()).toMatch(expectedValue);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectRowValuesMatch
  * @description Checks that a row matches the specified values,
  * takes an array of regExes or simple strings.
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectedRow the number of the row (within the visible rows)
  * that you want to check the value of
  * @param {array} expectedValueArray an array of regexes or strings of the values you expect in that row
  *
  * @example
  *

  *   gridTestUtils.expectRowValuesMatch('myGrid', 0, [ 'CellValue1', '^cellvalue2', 'cellValue3$' ]);
  *

  *
  */
  expectRowValuesMatch: function( gridId, expectedRow, expectedValueArray ) {
    var row = this.getRow( gridId, expectedRow );

    for ( var i = 0; i < expectedValueArray.length; i++){
      expect(row.element( by.repeater('(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name').row(i)).getText()).toMatch(expectedValueArray[i], 'Expected to match: ' + expectedValueArray[i] + ' in column: ' + i);
    }
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickHeaderCell
  * @description Clicks on the header of the specified column,
  * which would usually result in a sort
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to click on
  *
  * @example
  *

  *   gridTestUtils.clickHeaderCell('myGrid', 0);
  *

  *
  */
  clickHeaderCell: function( gridId, colNumber ) {
    var headerCell = this.headerCell( gridId, colNumber);

    headerCell.click();
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name resizeHeaderCell
  * @description Drags the left resizer border towards the column menu button,
  * which will perform a column resizing.
  * @param {string} gridId the id of the grid that you want to adjust
  * @param {integer} colNumber the number of the column (within the visible columns)
  * which left resizer border you wish to drag (this will increase the size of colNumber-1).
  *
  * @example
  *

  *   gridTestUtils.resizeHeaderCell('myGrid', 1);
  *

  *
  */
  resizeHeaderCell: function( gridId, colNumber ) {
    var headerCell = this.headerCell(gridId, colNumber);

    var resizer = headerCell.all( by.css( '.ui-grid-column-resizer' )).first();
    var menuButton = headerCell.element( by.css( '.ui-grid-column-menu-button' ));

    browser.actions()
      .mouseDown(resizer)
      .mouseMove(menuButton)
      .mouseUp()
      .perform();

  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name shiftClickHeaderCell
  * @description Shift-clicks on the header of the specified column,
  * which would usually result in adding a second column to the sort
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to click on
  *
  * @example
  *

  *   gridTestUtils.shiftClickHeaderCell('myGrid', 0);
  *

  *
  */
  shiftClickHeaderCell: function( gridId, colNumber ) {
    var headerCell = this.headerCell( gridId, colNumber);

    browser.actions()
      .keyDown(protractor.Key.SHIFT)
      .click(headerCell)
      .keyUp(protractor.Key.SHIFT)
      .perform();
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickColumnMenu
  * @description Clicks on the specified option in the specified column
  * menu.  Using this method is fragile, as any change to menu ordering
  * will break all the tests.  For this reason it is recommended to wrap
  * this into "clickColumnMenu<ItemName>" methods, each with a constant
  * for the item you want to click on.  You could alternatively develop
  * a method that finds a menu item by text value, but given that
  * ui-grid has i18n, the text values could also change easily
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to sort on
  * @param {integer} menuItemNumber the number of the item in the menu that
  * you want to click on
  *
  * @example
  *

  *   gridTestUtils.clickColumnMenu('myGrid', 0, 0);
  *

  *
  */
  clickColumnMenu: function( gridId, colNumber, menuItemNumber ) {
    var headerCell = this.headerCell( gridId, colNumber);

    headerCell.element( by.css( '.ui-grid-column-menu-button' ) ).click();

    var columnMenu = this.getGrid( gridId ).element( by.css( '.ui-grid-column-menu' ));
    columnMenu.element( by.repeater('item in menuItems').row(menuItemNumber) ).click();
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickColumnMenuSortAsc
  * @description Clicks on the sort ascending item within the specified
  * column menu.  Although it feels cumbersome to write lots of individual
  * "click this menu item" helpers, it is quite useful if the column menus are
  * changed to not have to go to every test script and change the menu item number
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to sort on
  *
  * @example
  *

  *   gridTestUtils.clickColumnMenuSortAsc('myGrid', 0);
  *

  *
  */
  clickColumnMenuSortAsc: function( gridId, colNumber ) {
    this.clickColumnMenu( gridId, colNumber, 0);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickColumnMenuSortDesc
  * @description Clicks on the sort descending item within the specified
  * column menu.  Although it feels cumbersome to write lots of individual
  * "click this menu item" helpers, it is quite useful if the column menus are
  * changed to not have to go to every test script and change the menu item number
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to sort on
  *
  * @example
  *

  *   gridTestUtils.clickColumnMenuSortDesc('myGrid', 0);
  *

  *
  */
  clickColumnMenuSortDesc: function( gridId, colNumber ) {
    this.clickColumnMenu( gridId, colNumber, 1);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickColumnMenuRemoveSort
  * @description Clicks on the remove sort item within the specified
  * column menu.  Although it feels cumbersome to write lots of individual
  * "click this menu item" helpers, it is quite useful if the column menus are
  * changed to not have to go to every test script and change the menu item number
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to remove the sort from
  *
  * @example
  *

  *   gridTestUtils.clickColumnMenuRemoveSort('myGrid', 0);
  *

  *
  */
  clickColumnMenuRemoveSort: function( gridId, colNumber ) {
    this.clickColumnMenu( gridId, colNumber, 2);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickColumnMenuHide
  * @description Clicks on the hide item within the specified
  * column menu.  Although it feels cumbersome to write lots of individual
  * "click this menu item" helpers, it is quite useful if the column menus are
  * changed to not have to go to every test script and change the menu item number
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to hide
  *
  * @example
  *

  *   gridTestUtils.clickColumnMenuHide('myGrid', 0);
  *

  *
  */
  clickColumnMenuHide: function( gridId, colNumber ) {
    this.clickColumnMenu( gridId, colNumber, 3);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectFilterBoxInColumn
  * @description Checks that a filter box exists in the specified column
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to verify the filter box is in
  * @param {integer} count the number filter boxes you expect - 0 meaning none, 1 meaning
  * a standard filter, 2 meaning a numerical filter with greater than / less than.
  *
  * @example
  *

  *   gridTestUtils.expectFilterBoxInColumn('myGrid', 0, 0);
  *

  *
  */
  expectFilterBoxInColumn: function( gridId, colNumber, count ) {
    var headerCell = this.headerCell( gridId, colNumber);

    expect( headerCell.all( by.css( '.ui-grid-filter-input' ) ).count() ).toEqual(count);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name cancelFilterInColumn
  * @description Cancels the filter in a column
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to cancel the filter in
  *
  * @example
  *

  *   gridTestUtils.cancelFilterInColumn('myGrid', 0);
  *

  *
  */
  cancelFilterInColumn: function( gridId, colNumber ) {
    var headerCell = this.headerCell( gridId, colNumber);

    headerCell.element( by.css( '.ui-grid-icon-cancel' ) ).click();
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name enterFilterInColumn
  * @description Enters a filter in a column
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to enter the filter in
  * @param {string} filterValue the value you want to enter into the filter
  *
  * @example
  *

  *   gridTestUtils.cancelFilterInColumn('myGrid', 0);
  *

  *
  */
  enterFilterInColumn: function( gridId, colNumber, filterValue ) {
    var headerCell = this.headerCell( gridId, colNumber);

    headerCell.element( by.css( '.ui-grid-filter-input' ) ).sendKeys(filterValue);
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectVisibleColumnMenuItems
  * @description Checks how many visible menu items there are in the column menu
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} colNumber the number of the column (within the visible columns)
  * that you want to check the count for
  * @param {integer} expectItems the number of visible items you expect
  *
  * @example
  *

  *   gridTestUtils.visibleColumnMenuItems('myGrid', 0, 3);
  *

  *
  */
  expectVisibleColumnMenuItems: function( gridId, colNumber, expectItems ) {
    var headerCell = this.headerCell( gridId, colNumber );
    headerCell.element( by.css( '.ui-grid-column-menu-button' ) ).click();

    var displayedCount = 0;
    var columnMenu = this.getGrid( gridId ).element( by.css( '.ui-grid-column-menu' ));

    var menuItems = columnMenu.all( by.css( '.ui-grid-menu-item' ) );

    menuItems.map(function(elm) {
      return elm.isDisplayed();
    }).then( function( displayedArray ){
      for ( var i = 0; i < displayedArray.length; i++ ){
        if ( displayedArray[i] ){
          displayedCount++;
        }
      }
      expect(displayedCount).toEqual( expectItems );
    });
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name expectVisibleGridMenuItems
  * @description Checks how many visible menu items there are in the grid menu
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} expectItems the number of visible items you expect
  *
  * @example
  *

  *   gridTestUtils.expectVisibleGridMenuItems('myGrid', 3);
  *

  *
  */
  expectVisibleGridMenuItems: function( gridId, expectItems ) {
    var gridMenuButton = this.getGrid( gridId ).element( by.css ( '.ui-grid-menu-button' ) );
    gridMenuButton.click();

    var displayedCount = 0;

    var menuItems = gridMenuButton.all( by.css( '.ui-grid-menu-item' ) );

    menuItems.map(function(elm) {
      return elm.isDisplayed();
    }).then( function( displayedArray ){
      for ( var i = 0; i < displayedArray.length; i++ ){
        if ( displayedArray[i] ){
          displayedCount++;
        }
      }
      expect(displayedCount).toEqual( expectItems );
    });
  },

  /**
  * @ngdoc method
  * @methodOf ui.grid.e2eTestLibrary.api:gridTest
  * @name clickGridMenuItem
  * @description Clicks on a numbered grid menu item.  Note that it's clicking
  * the item based on the underlying repeater - and that some of the items will
  * not be visible.  So the item you want to click on may not be the same
  * as the item number when you look at the ui
  * @param {string} gridId the id of the grid that you want to inspect
  * @param {integer} itemNumber the number of visible items you expect
  *
  * @example
  *

  *   gridTestUtils.clickVisibleGridMenuItem('myGrid', 9);
  *

  *
  */
  clickGridMenuItem: function( gridId, itemNumber ) {
    var gridMenuButton = this.getGrid( gridId ).element( by.css ( '.ui-grid-menu-button' ) );
    gridMenuButton.click();

    gridMenuButton.element( by.repeater('item in menuItems').row( itemNumber) ).click();
  }
};


text:
""" Comverted from matlab code
Source: http://www.robots.ox.ac.uk/~fwood/teaching/AIMS_CDT_ML_2015/homework/HW_1_sum_product/
"""

import numpy as np
import itertools

class Factor:
    """ factor : this class is a container class for the factor matrix

     properties

     factor_matrix : a tensor which given the factor value for any
                     configuration of the neighboring variable nodes
    """

    def __init__(self, factor_matrix):
        """ factor : constructor method for object

        :param: factor_matrix : factor matrix
        """

        self.factor_matrix = factor_matrix;

    def product(self, product_of_messages):
        """ product_matrix : method to get the result of an element wise
                          product of an input tensor and the factor matrix

        :param: product_of_messages : tensor to product with factor matrix
        """

        product_matrix = product_of_messages * self.factor_matrix
        return product_matrix

    def getValue(self, indices):
        """ getValue : method to get the value of a given element of the
                    factor matrix

        :param: varargin : variable length input array of indices into
                           factor matrix.  varargin should have the same
                           number of values as the factor matrix has
                           dimensions.
        """

        return self.factor_matrix[indices]

    def display(self):
        """ display : overides the default display behavior
        """

        print(self.factor_matrix)

class Node:

    """ node : this object is the basic element of a graph.  for inference on
            factor graphs we will need both factor nodes and variable nodes.
            both of those types of objects will be descended from this object.

     properties

     unid      : unique string identifier for the node
     nodes     : cell array of neighboring nodes
     messages  : cell array of messages from neighbor nodes.  all messages are
                 column vectors
     updated   : indicator variable for scheduling of message passing in loopy
                 beleif propagation
    """

    def __init__(self, unid=None):
        self.unid = unid
        self.nodes = []
        self.messages = []
        self.updated = 0

    def setNotUpdated(self):
        """ setNotUpdated : recursive method to set this the updated field of
                         this node and recursively all nodes in the graph
                         to 0
        """
        self.updated = 0
        for i in range(len(self.nodes)):
            if self.nodes[i].updated:
                self.nodes[i].setNotUpdated()

    def loopy_bp(self):
        """ loopy_bp : recursive method to prompt this node and recursively
                    all nodes in the graph to update their received
                    messages
        """
        self.updateMessages()
        self.updated = 1
        for i in range(len(self.nodes)):
            if not self.nodes[i].updated:
                self.nodes[i].loopy_bp()

    def updateMessages(self):
        """  updateMessages : method to ask all neighboring nodes for an
                          updated message
        """
        for i in range(len(self.nodes)):
            self.messages[i] = self.nodes[i].getMessage(self.unid)

    def passMessageIn(self, to_unid):
        """  passMessageIn : recursive method to pass messages in from the
                         edges to the given node

        :param: to_unid : node to which message is being passed
        """

        ind = -1
        for i in range(len(self.nodes)):
            if self.nodes[i].unid == to_unid:
                ind = i
                break
        if ind == -1:
            raise ValueError('must be connected to each other')

        self.messages[i] = self.nodes[i].getMessage(self.unid)

        for i in range(len(self.nodes)):
            if i != ind:
                self.nodes[i].passMessageIn(self.unid)

    def passMessageOut(self, from_unid):
        """ passMessageOut : recursive method to pass messages out to the
                          corners from a central node

        :param: from_unid : node from which we were prompted to pass
                            messages out, i.e. node to which we do not
                            need to pass a message
        """

        ind = -1
        for i in range(len(self.nodes)):
            if self.nodes[i].unid == from_unid:
                ind = i
                break

        if ind == -1:
            raise ValueError('must be connected to each other')

        self.messages[i] = self.nodes[i].getMessage(self.unid)

        for i in range(len(self.nodes)):
            if i != ind:
                self.nodes[i].passMessageOut(self.unid)

    def addNode(self, node):
        """ addNode : method to add a neighboring node to the list of
                   neighboring nodes

        :param: node : node to add as neighbor
        """

        raise ValueError('this function is meant to be abstract and over written')

    def getMessage(self, to_unid):
        """  getMessage : get the message to the given node

         :param: to_unid : node to which the message is being passed
        """

        raise ValueError('this function is meant to be abstract and over written')

    def display(self):
        """ display : overide of default display behavior
        """

        print('description : ')
        print(self.unid)
        print(' ')
        print(['this node has ' + str(len(self.nodes)) + ' neighboring nodes, they are'])
        for i in range(len(self.nodes)):
            print(self.nodes[i].unid)

class VariableNode(Node):
    """ variable_node

     object specifically for variable nodes.

     properties

     dimension : dimension of discrete variable represented by node
     observed  : indicator indicating if the variable is observed
     value     : value of the node if it has been observed
    """

    def __init__(self, unid, dimension):
        """ variable_node : method to construct the this variable node

        :param: unid      : unique identifier for this node
        :param: dimension : dimension of this node
        """

        Node.__init__(self, unid)
        self.dimension = dimension
        self.observed = False

    def addNode(self, node):
        """ addNode : method to add a neighboring node to the list of
                   neighboring nodes

        :param: node : node to add as neighbor
        """

        self.nodes.append(node)
        self.messages.append(np.ones(self.dimension))

    def getMessage(self, to_unid):
        """ getMessage : override of getMessage in node class.  THIS IS A
                      METHOD WHICH MUST BE FILLED OUT BY THE STUDENT

        :param: to_unid : node to which message is being passed.
        """

        if self.observed:
            message = self.value
        else:
            message = np.ones(self.dimension)
            for i in range(len(self.nodes)):
                if self.nodes[i].unid != to_unid:
                    message *= self.messages[i]

        message /= np.sum(message)

        return message

    def passMessagesIn(self):
        """ passMessagesIn : method to pass messages from the edge to this node
        """

        for i in range(len(self.nodes)):
            self.messages[i] = self.nodes[i].passMessageIn(self.unid)

    def passMessagesOut(self):
        """ passMessagesOut : method to pass messages out from this node to the edges
        """
        for i in range(len(self.nodes)):
            self.nodes[i].passMessageOut(self.unid)

    def getMarginalDistribution(self):
        """ getMarginalDistribution : method to get the marginal distribution
        of the variable represented by this node. THIS IS A METHOD WHICH MUST BE
        FILLED OUT BY THE STUDENT.
        """

        if self.observed:
            return self.value
        else:
            marginal = np.product(self.messages, axis=0)
            marginal /= np.sum(marginal)
            return marginal

    def setValue(self, val):
        """ setValue : method to set the vaue of this variable node.
        """

        assert(len(val) == self.dimension)

        self.value = val
        self.observed = True

    def display(self):
        """ print : overrides the default print behavior
        """
        print('var dimension is = ', self.dimension)
        if self.observed:
            print('this var is observed as ' + str(self.value))
        else:
            print('this var is hidden')

class FactorNode(Node):
    """ factor_node : object used for factor nodes in a factor graph
     representation of a graphical model.

     properties

    factor : factor object associated with this factor node
    """

    def __init__(self, unid, factor):
        """ factor_node : constructor method to create this factor node

        :param: factor : factor associated with this factor node
        """

        Node.__init__(self, unid)
        self.factor = factor

    def addNode(self, node):
        """ addNode : method to add a neighboring node to the list of
        neighboring nodes

        :param: node : node to add as neighbor
        """
        self.nodes.append(node)
        self.messages.append(np.ones(node.dimension))

    def getMessage(self, to_unid):
        """ getMessage : gets the message to be sent to the given node. THIS
        METHOD IS ONE WITH STUDENT NEEDS TO FILL OUT.

        :param: to_unid : node to which message will be sent
        """

        to_index = [node.unid for node in self.nodes].index(to_unid)
        dim_node_to = self.nodes[to_index].dimension
        n = len(self.nodes)
        l = [range(node.dimension) for node in self.nodes]
        indices = [i for i in range(n) if i != to_index]

        message = np.zeros(dim_node_to)

        for x in range(dim_node_to):
            l[to_index] = (x,)
            my_iterators = tuple(l)
            for iterator in itertools.product(*my_iterators):
                to_multiply = [self.messages[j][iterator[j]] for j in indices]
                message[x] += np.product(to_multiply) * self.factor.getValue(iterator)

        message /= np.sum(message)

        return message

    def display(self):
        """ display : overides the default display behavior
        """
        print('factor is = ', self.factor);

redpajama_set_name: RedPajamaGithub


text:
package org.vanilladb.core.storage.tx.concurrency;

import java.util.concurrent.locks.ReentrantLock;

class LatchTable {

	private final ReentrantLock latches[] = new ReentrantLock[1009];

	public LatchTable() {
		for (int i = 0; i < latches.length; i++) {
			latches[i] = new ReentrantLock();
		}
	}

	public ReentrantLock getLatch(Object obj) {
		int code = Math.abs(obj.hashCode()); // avoid negative value
		code %= latches.length;

		return (ReentrantLock) latches[code];
	}
}


text:
FROM centos:7
MAINTAINER Alex Miller <alex@thinkmassive.org>
RUN yum update -y
RUN yum install -y epel-release
RUN yum update -y
RUN yum groupinstall -y 'Development Tools'
RUN yum install -y git leveldb-devel libmicrohttpd-devel

RUN curl -o install-cmake.sh https://cmake.org/files/v3.8/cmake-3.8.2-Linux-x86_64.sh
RUN chmod u+rx install-cmake.sh
RUN ./install-cmake.sh --skip-license --prefix=/usr/local

RUN git clone --recursive https://github.com/ethereum/cpp-ethereum.git /opt/cpp-ethereum
RUN cd /opt/cpp-ethereum && mkdir build

RUN cd /opt/cpp-ethereum/build && cmake .. && cmake --build .

#ENTRYPOINT /opt/cpp-ethereum/build/eth/eth


text:
namespace Aspose.Tasks.Examples.CSharp
{
    using System;
    using NUnit.Framework;

    [TestFixture]
    public class ExHeaderFooterInfo : ApiExampleBase
    {
        [Test] // ExSkip
        public void WorkWithHeaderFooterInfo()
        {
            // ExStart:ReadHeaderFooterInfo
            // ExFor: HeaderFooterInfo
            // ExFor: HeaderFooterInfo.#ctor
            // ExFor: HeaderFooterInfo.LeftImage
            // ExFor: HeaderFooterInfo.LeftImageSize
            // ExFor: HeaderFooterInfo.LeftText
            // ExFor: HeaderFooterInfo.CenteredImage
            // ExFor: HeaderFooterInfo.CenteredImageSize
            // ExFor: HeaderFooterInfo.CenteredText
            // ExFor: HeaderFooterInfo.RightImage
            // ExFor: HeaderFooterInfo.RightImageSize
            // ExFor: HeaderFooterInfo.RightText
            // ExSummary: Shows how to read page header/footer info.
            var project = new Project(DataDir + "Blank2010.mpp");
            var info = project.DefaultView.PageInfo;

            Console.WriteLine("Header left text: {0} ", info.Header.LeftText);
            Console.WriteLine("Header left image: {0} ", info.Header.LeftImage);
            Console.WriteLine("Header left image size: {0} ", info.Header.LeftImageSize);
            Console.WriteLine("Header center text: {0} ", info.Header.CenteredText);
            Console.WriteLine("Header center image: {0} ", info.Header.CenteredImage);
            Console.WriteLine("Header center image size: {0} ", info.Header.CenteredImageSize);
            Console.WriteLine("Header right text: {0} ", info.Header.RightText);
            Console.WriteLine("Header right image: {0} ", info.Header.RightImage);
            Console.WriteLine("Header right image size: {0} ", info.Header.RightImageSize);
            Console.WriteLine();
            Console.WriteLine("Footer left text: {0} ", info.Footer.LeftText);
            Console.WriteLine("Footer left image: {0} ", info.Footer.LeftImage);
            Console.WriteLine("Footer left image size: {0} ", info.Footer.LeftImageSize);
            Console.WriteLine("Footer center text: {0} ", info.Footer.CenteredText);
            Console.WriteLine("Footer center image: {0} ", info.Footer.CenteredImage);
            Console.WriteLine("Footer center size: {0} ", info.Footer.CenteredImageSize);
            Console.WriteLine("Footer right text: {0} ", info.Footer.RightText);
            Console.WriteLine("Footer right image: {0} ", info.Footer.RightImage);
            Console.WriteLine("Footer right image size: {0} ", info.Footer.RightImageSize);
            // ExEnd:WorkWithHeaderFooterInfo
        }
    }
}


text:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1250, 768)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.btn_Capture = QtGui.QPushButton(self.centralwidget)
        self.btn_Capture.setGeometry(QtCore.QRect(340, 410, 158, 27))
        self.btn_Capture.setObjectName(_fromUtf8("btn_Capture"))
        self.feFrame = QtGui.QFrame(self.centralwidget)
        self.feFrame.setGeometry(QtCore.QRect(20, 10, 390, 390))
        self.feFrame.setFrameShape(QtGui.QFrame.Panel)
        self.feFrame.setFrameShadow(QtGui.QFrame.Plain)
        self.feFrame.setLineWidth(3)
        self.feFrame.setMidLineWidth(0)
        self.feFrame.setObjectName(_fromUtf8("feFrame"))
        self.feLabel = QtGui.QLabel(self.feFrame)
        self.feLabel.setGeometry(QtCore.QRect(10, 10, 370, 370))
        self.feLabel.setText(_fromUtf8(""))
        self.feLabel.setWordWrap(False)
        self.feLabel.setIndent(-1)
        self.feLabel.setObjectName(_fromUtf8("feLabel"))
        self.ptzFrame = QtGui.QFrame(self.centralwidget)
        self.ptzFrame.setGeometry(QtCore.QRect(420, 10, 390, 390))
        self.ptzFrame.setFrameShape(QtGui.QFrame.Panel)
        self.ptzFrame.setFrameShadow(QtGui.QFrame.Plain)
        self.ptzFrame.setLineWidth(3)
        self.ptzFrame.setMidLineWidth(0)
        self.ptzFrame.setObjectName(_fromUtf8("ptzFrame"))
        self.ptzLabel = QtGui.QLabel(self.ptzFrame)
        self.ptzLabel.setGeometry(QtCore.QRect(10, 10, 370, 370))
        self.ptzLabel.setText(_fromUtf8(""))
        self.ptzLabel.setWordWrap(False)
        self.ptzLabel.setIndent(-1)
        self.ptzLabel.setObjectName(_fromUtf8("ptzLabel"))
        self.gb_Absolute = QtGui.QGroupBox(self.centralwidget)
        self.gb_Absolute.setGeometry(QtCore.QRect(960, 90, 171, 191))
        self.gb_Absolute.setAutoFillBackground(False)
        self.gb_Absolute.setObjectName(_fromUtf8("gb_Absolute"))
        self.btn_AbsUp = QtGui.QPushButton(self.gb_Absolute)
        self.btn_AbsUp.setGeometry(QtCore.QRect(60, 30, 50, 30))
        self.btn_AbsUp.setObjectName(_fromUtf8("btn_AbsUp"))
        self.btn_AbsLeft = QtGui.QPushButton(self.gb_Absolute)
        self.btn_AbsLeft.setGeometry(QtCore.QRect(20, 60, 50, 30))
        self.btn_AbsLeft.setObjectName(_fromUtf8("btn_AbsLeft"))
        self.btn_AbsRight = QtGui.QPushButton(self.gb_Absolute)
        self.btn_AbsRight.setGeometry(QtCore.QRect(100, 60, 50, 30))
        self.btn_AbsRight.setObjectName(_fromUtf8("btn_AbsRight"))
        self.btn_AbsDown = QtGui.QPushButton(self.gb_Absolute)
        self.btn_AbsDown.setGeometry(QtCore.QRect(60, 90, 50, 30))
        self.btn_AbsDown.setObjectName(_fromUtf8("btn_AbsDown"))
        self.btn_AbsZoomOut = QtGui.QPushButton(self.gb_Absolute)
        self.btn_AbsZoomOut.setGeometry(QtCore.QRect(90, 140, 75, 30))
        self.btn_AbsZoomOut.setObjectName(_fromUtf8("btn_AbsZoomOut"))
        self.btn_AbsZoomIn = QtGui.QPushButton(self.gb_Absolute)
        self.btn_AbsZoomIn.setGeometry(QtCore.QRect(10, 140, 75, 30))
        self.btn_AbsZoomIn.setObjectName(_fromUtf8("btn_AbsZoomIn"))
        self.gb_Continuous = QtGui.QGroupBox(self.centralwidget)
        self.gb_Continuous.setGeometry(QtCore.QRect(950, 300, 171, 181))
        self.gb_Continuous.setFlat(False)
        self.gb_Continuous.setCheckable(False)
        self.gb_Continuous.setObjectName(_fromUtf8("gb_Continuous"))
        self.btn_ContUp = QtGui.QPushButton(self.gb_Continuous)
        self.btn_ContUp.setGeometry(QtCore.QRect(60, 30, 50, 30))
        self.btn_ContUp.setObjectName(_fromUtf8("btn_ContUp"))
        self.btn_ContLeft = QtGui.QPushButton(self.gb_Continuous)
        self.btn_ContLeft.setGeometry(QtCore.QRect(20, 60, 50, 30))
        self.btn_ContLeft.setObjectName(_fromUtf8("btn_ContLeft"))
        self.btn_ContRight = QtGui.QPushButton(self.gb_Continuous)
        self.btn_ContRight.setGeometry(QtCore.QRect(100, 60, 50, 30))
        self.btn_ContRight.setObjectName(_fromUtf8("btn_ContRight"))
        self.btn_ContDown = QtGui.QPushButton(self.gb_Continuous)
        self.btn_ContDown.setGeometry(QtCore.QRect(60, 90, 50, 30))
        self.btn_ContDown.setObjectName(_fromUtf8("btn_ContDown"))
        self.btn_ContZoomOut = QtGui.QPushButton(self.gb_Continuous)
        self.btn_ContZoomOut.setGeometry(QtCore.QRect(90, 130, 75, 30))
        self.btn_ContZoomOut.setObjectName(_fromUtf8("btn_ContZoomOut"))
        self.btn_ContZoomIn = QtGui.QPushButton(self.gb_Continuous)
        self.btn_ContZoomIn.setGeometry(QtCore.QRect(10, 130, 75, 30))
        self.btn_ContZoomIn.setObjectName(_fromUtf8("btn_ContZoomIn"))
        self.btn_RecVideoFE = QtGui.QPushButton(self.centralwidget)
        self.btn_RecVideoFE.setGeometry(QtCore.QRect(250, 450, 158, 27))
        self.btn_RecVideoFE.setObjectName(_fromUtf8("btn_RecVideoFE"))
        self.btn_RecVideoPTZ = QtGui.QPushButton(self.centralwidget)
        self.btn_RecVideoPTZ.setGeometry(QtCore.QRect(420, 450, 158, 27))
        self.btn_RecVideoPTZ.setObjectName(_fromUtf8("btn_RecVideoPTZ"))
        self.gb_Home = QtGui.QGroupBox(self.centralwidget)
        self.gb_Home.setGeometry(QtCore.QRect(960, 10, 171, 71))
        self.gb_Home.setObjectName(_fromUtf8("gb_Home"))
        self.btn_GotoHome = QtGui.QPushButton(self.gb_Home)
        self.btn_GotoHome.setGeometry(QtCore.QRect(20, 30, 50, 30))
        self.btn_GotoHome.setObjectName(_fromUtf8("btn_GotoHome"))
        self.btn_SetHome = QtGui.QPushButton(self.gb_Home)
        self.btn_SetHome.setGeometry(QtCore.QRect(100, 30, 50, 30))
        self.btn_SetHome.setObjectName(_fromUtf8("btn_SetHome"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1250, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "Principal", None))
        self.btn_Capture.setText(_translate("MainWindow", "Capturar", None))
        self.gb_Absolute.setTitle(_translate("MainWindow", "Movimiento por paso", None))
        self.btn_AbsUp.setText(_translate("MainWindow", "Arriba", None))
        self.btn_AbsLeft.setText(_translate("MainWindow", "Izq", None))
        self.btn_AbsRight.setText(_translate("MainWindow", "Der", None))
        self.btn_AbsDown.setText(_translate("MainWindow", "Abajo", None))
        self.btn_AbsZoomOut.setText(_translate("MainWindow", "Zoom Out", None))
        self.btn_AbsZoomIn.setText(_translate("MainWindow", "Zoom In", None))
        self.gb_Continuous.setTitle(_translate("MainWindow", "Movimiento continuo", None))
        self.btn_ContUp.setText(_translate("MainWindow", "Arriba", None))
        self.btn_ContLeft.setText(_translate("MainWindow", "Izq", None))
        self.btn_ContRight.setText(_translate("MainWindow", "Der", None))
        self.btn_ContDown.setText(_translate("MainWindow", "Abajo", None))
        self.btn_ContZoomOut.setText(_translate("MainWindow", "Zoom Out", None))
        self.btn_ContZoomIn.setText(_translate("MainWindow", "Zoom In", None))
        self.btn_RecVideoFE.setText(_translate("MainWindow", "Grabar de Fisheye", None))
        self.btn_RecVideoPTZ.setText(_translate("MainWindow", "Grabar de PTZ", None))
        self.gb_Home.setTitle(_translate("MainWindow", "Home", None))
        self.btn_GotoHome.setText(_translate("MainWindow", "Ir", None))
        self.btn_SetHome.setText(_translate("MainWindow", "Set", None))


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Br. Mus. nat. Hist. , Bot. 9(1): 8 (1981)

#### Original name
Asterophoma mazaediicola D. Hawksw.

### Remarks
null


text:
@interface PodsDummy_MSSimpleGauge : NSObject
@end
@implementation PodsDummy_MSSimpleGauge
@end


text:
package de.holisticon.vaadin.pageobject;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

public class VaadinTreePageObject extends VaadinPageObject {

	private static final String CLASS_NAME_TREE_NODE = "v-tree-node";

	public VaadinTreePageObject(WebDriver driver) {
		super(driver);
	}

	public VaadinTreePageObject select(String caption) {
		for (WebElement item : allVisibleItems()) {
			WebElement clickableItem = item.findElement(By.tagName("span"));
			if (caption.equals(clickableItem.getText())) {
				clickableItem.click();
				return this;
			}
		}
		return this;
	}

	public VaadinTreePageObject expand(String caption) {
		for (WebElement item : allVisibleItems()) {
			if (caption.equals(item.getText())) {
				while (!item.getAttribute("class").contains(
						"v-tree-node-expanded")) {
					item.click();
				}
				return this;
			}
		}
		return this;
	}

	public WebElement selection() {
		try {
			return browser().findElement(By.className("v-tree-node-selected"));
		} catch (NoSuchElementException ex) {
			return null;
		}
	}

	public List<WebElement> allVisibleItems() {
		return browser().findElements(By.className(CLASS_NAME_TREE_NODE));
	}

	public List<WebElement> allVisibleItemsBeyond(WebElement webElement) {
		return webElement.findElements(By.className(CLASS_NAME_TREE_NODE));
	}

	public List<WebElement> allVisibleItemsWith(String name) {
		List<WebElement> itemsWithName = Lists.newArrayList();
		List<WebElement> allVisibleItems = allVisibleItems();
		for (WebElement item : allVisibleItems) {
			String text = extractName(item.getText());
			if (name.equals(text)) {
				itemsWithName.add(item);
			}
		}
		return itemsWithName;
	}

	public String extractName(String text) {
		return Splitter.on("\n").omitEmptyStrings().split(text).iterator()
				.next();
	}

}


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/html; charset=UTF-8" />
<title>ActionCommands xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" />

View Javadoc

1   package net.sourceforge.pmd.util.viewer.gui;
2
3   /**
4    * contains action command constants
5    *
6    * @author Boris Gruschko ( boris at gruschko.org )
7    */
8
9   public final class ActionCommands {
10      public static final String COMPILE_ACTION = "Compile";
11      public static final String EVALUATE_ACTION = "Evaluate";
12  }

This page was automatically generated by Maven


text:
import pickle

# Get the original data
from urllib.request import urlopen
url = 'http://www.pythonchallenge.com/pc/def/banner.p'
text = urlopen(url).read()

# Use pickle to serialize the original data
data = pickle.loads(text)

# Print it
for raw in data:
    print(''.join(pair[0] * pair[1] for pair in raw))


text:
<?php

namespace AppBundle\Repository;

use AppBundle\Entity\Membre;

class PartieRepository extends \Doctrine\ORM\EntityRepository
{

    /**
     * Retourne le nombre de partie jouée du membre
     *
     * @param Membre $membre
     * @return mixed
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
	public function countAllGamesByMembre(Membre $membre)
	{
		return $this->createQueryBuilder('p')
			->select('count(p) nbParties')
			->where('p.joueur = :membre')->setParameter('membre', $membre)
			->andWhere('p.joue = 1')
			->getQuery()->getSingleResult();
	}

	public function getByDayForMembre(Membre $membre)
    {
        $query = $this->createQueryBuilder('p')
            ->select('DATE_FORMAT(p.datePartie, \'%Y-%m-%d\') as date, count(p) as count')
            ->where('p.joueur = :membre')
            ->groupBy('date')
            ->orderBy('date', 'ASC')
            ->setParameter('membre', $membre);

        return $query->getQuery()->getResult();
    }

    /**
     * Retourne un tableau de statistiques de l'entité
     *
     * @return array
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
	public function getStat()
	{
		$array = array();

		$array['total'] = $this->createQueryBuilder('pa')
			                  ->select('count(pa) total')
			                  ->getQuery()->getSingleResult()['total'];

		$dateJ30 = new \DateTime();
		$dateJ30->setTimestamp($dateJ30->getTimestamp() - (3600 * 24 * 30));
		$array['joueJ30'] = $this->createQueryBuilder('pa')
			                    ->select('count(pa) joueJ30')
			                    ->where('pa.datePartie > :j30')->setParameter('j30', $dateJ30)
			                    ->getQuery()->getSingleResult()['joueJ30'];

		$dateJ7 = new \DateTime();
		$dateJ7->setTimestamp($dateJ7->getTimestamp() - (3600 * 24 * 7));
		$array['joueJ7'] = $this->createQueryBuilder('pa')
			                   ->select('count(pa) joueJ7')
			                   ->where('pa.datePartie > :j7')->setParameter('j7', $dateJ7)
			                   ->getQuery()->getSingleResult()['joueJ7'];

		$dateH24 = new \DateTime();
		$dateH24->setTimestamp($dateH24->getTimestamp() - (3600 * 24));
		$array['joueH24'] = $this->createQueryBuilder('pa')
			                    ->select('count(pa) joueH24')
			                    ->where('pa.datePartie > :h24')->setParameter('h24', $dateH24)
			                    ->getQuery()->getSingleResult()['joueH24'];

		$array['moyGain'] = $this->createQueryBuilder('pa')
			                    ->select('avg(pa.gainJoueur) moyGain')
			                    ->getQuery()->getSingleResult()['moyGain'];

		return $array;
	}

}


text:
<?php

namespace Madewithlove\Tactician;

use Mockery;

abstract class TestCase extends \PHPUnit\Framework\TestCase
{
    protected function tearDown(): void
    {
        Mockery::close();
    }
}


text:
module ResourceSectionsHelper
end


text:
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.extensions.restapi;

import java.util.concurrent.TimeUnit;

/** Special return value to mean specific HTTP status codes in a REST API. */
public abstract class Response<T> {
  @SuppressWarnings({"rawtypes"})
  private static final Response NONE = new None();

  /** HTTP 200 OK: pointless wrapper for type safety. */
  public static <T> Response<T> ok(T value) {
    return new Impl<>(200, value);
  }

  public static <T> Response<T> withMustRevalidate(T value) {
    return ok(value).caching(CacheControl.PRIVATE(0, TimeUnit.SECONDS).setMustRevalidate());
  }

  /** HTTP 201 Created: typically used when a new resource is made. */
  public static <T> Response<T> created(T value) {
    return new Impl<>(201, value);
  }

  /** HTTP 202 Accepted: accepted as background task. */
  public static Accepted accepted(String location) {
    return new Accepted(location);
  }

  /** HTTP 204 No Content: typically used when the resource is deleted. */
  @SuppressWarnings("unchecked")
  public static <T> Response<T> none() {
    return NONE;
  }

  /** HTTP 302 Found: temporary redirect to another URL. */
  public static Redirect redirect(String location) {
    return new Redirect(location);
  }

  /** Arbitrary status code with wrapped result. */
  public static <T> Response<T> withStatusCode(int statusCode, T value) {
    return new Impl<>(statusCode, value);
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  public static <T> T unwrap(T obj) {
    while (obj instanceof Response) {
      obj = (T) ((Response) obj).value();
    }
    return obj;
  }

  public abstract boolean isNone();

  public abstract int statusCode();

  public abstract T value();

  public abstract CacheControl caching();

  public abstract Response<T> caching(CacheControl c);

  @Override
  public abstract String toString();

  private static final class Impl<T> extends Response<T> {
    private final int statusCode;
    private final T value;
    private CacheControl caching = CacheControl.NONE;

    private Impl(int sc, T val) {
      statusCode = sc;
      value = val;
    }

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

    @Override
    public int statusCode() {
      return statusCode;
    }

    @Override
    public T value() {
      return value;
    }

    @Override
    public CacheControl caching() {
      return caching;
    }

    @Override
    public Response<T> caching(CacheControl c) {
      caching = c;
      return this;
    }

    @Override
    public String toString() {
      return "[" + statusCode() + "] " + value();
    }
  }

  private static final class None extends Response<Object> {
    private None() {}

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

    @Override
    public int statusCode() {
      return 204;
    }

    @Override
    public Object value() {
      throw new UnsupportedOperationException();
    }

    @Override
    public CacheControl caching() {
      return CacheControl.NONE;
    }

    @Override
    public Response<Object> caching(CacheControl c) {
      throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
      return "[204 No Content] None";
    }
  }

  /** An HTTP redirect to another location. */
  public static final class Redirect {
    private final String location;

    private Redirect(String url) {
      this.location = url;
    }

    public String location() {
      return location;
    }

    @Override
    public int hashCode() {
      return location.hashCode();
    }

    @Override
    public boolean equals(Object o) {
      return o instanceof Redirect && ((Redirect) o).location.equals(location);
    }

    @Override
    public String toString() {
      return String.format("[302 Redirect] %s", location);
    }
  }

  /** Accepted as task for asynchronous execution. */
  public static final class Accepted {
    private final String location;

    private Accepted(String url) {
      this.location = url;
    }

    public String location() {
      return location;
    }

    @Override
    public int hashCode() {
      return location.hashCode();
    }

    @Override
    public boolean equals(Object o) {
      return o instanceof Accepted && ((Accepted) o).location.equals(location);
    }

    @Override
    public String toString() {
      return String.format("[202 Accepted] %s", location);
    }
  }
}


text:
YEAR=$(date +"%Y")
MONTH=$(date +"%m")
cd $TRAVIS_BUILD_DIR

#Remove Remotes Added by TravisCI
git remote rm origin

#Add Remote with Secure Key
git remote add origin https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git

#local remote=origin
#if [[ $GH_TOKEN ]]; then
#	remote=https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git
#fi

#List Remotes ONLY DURING testing - do not do this on live repo / possible key leak
#git remote -v

# Set Git Variables
git config --global user.email "${GIT_EMAIL}"
git config --global user.name "${GIT_NAME}"
git config --global push.default simple

# Make sure we have master branch checked out in Git
git checkout master

# Modify our file and make sure Travis is owner
sudo $TRAVIS_BUILD_DIR/travis-ci/modify-globalblacklist.sh
sudo chown travis:travis $TRAVIS_BUILD_DIR/globalblacklist.conf

# Add the modified file to the and commit it
#git add $TRAVIS_BUILD_DIR/globalblacklist.conf
git add -A
git commit -am "V3.$YEAR.$MONTH.$TRAVIS_BUILD_NUMBER [ci skip]"

# Travis now moves to the before_deploy: section of .travis.yml


text:
> SQL PHP JSON jQuery and a Byte of Scrum #combine

A sample application used to understand the basics behind web 2.0.

Given a database to store citations, a php script deliver a random quote in
the JSON format. In the client a jquery based script shows the quotes in the intervall
set.

With the project zitat.json, self-controlling learners will work out the principles of agile software development.

## Open Source / OER
The tutorial / guidlines combines the acquisition of skills with knowledge of different compulsory modules from the curriculum of computer science (ICT vocational training Switzerland). Self-activity, structured thinking and problem solving is placed in the foreground.

Learning by: strengthening, insight and knowledge, connecting and deciding, experience and interpreting.

Fetch the german open book @ https://fabforge.ch/edu/topic/zitatjson-software-agil-entwickeln

### License
The source code of zitat.json is licensed under the [MIT License](https://opensource.org/licenses/MIT). The open book under [CC-BY-SA](https://creativecommons.org/licenses/by-sa/2.0/) fabforge, Fabian Dennler.


text:
(function($, _, Bacon){

    // Note: I'm not using "asEventStream" in order to allow the widget factory cleanup events and assign it's own namespace and sorcery
    $.widget('ui.fried_eggs', {
        /**
         * Use widget's "_on" event binder to create bacon event streams
         * @param {object} [element] - The object to listen on (base element for event delegation). If not specified, this.element is used.
         * @param {*} [eventSelector] - String/Array of events and selectors to be fed into the stream (i.e. ["click li", "mouseenter a"])
         * @returns {EventStream}
         */
        createEventStream: function(){
            var _this = this,
                eventSelectorArray = _([_(arguments).last()]).flatten(),
                element = arguments.length === 2 ? arguments[0] : this.element;

            return Bacon.fromBinder(function(sink){

                var listener = function(){
                    var argsArray = _.toArray(arguments);
                    sink(new Bacon.Next(function(){ return argsArray.length > 1 ? argsArray: argsArray[0]; }));
                }

                var eventHash = _(eventSelectorArray).reduce(function(hash, eventSelector){
                    hash[eventSelector] = listener;
                    return hash;
                }, {});

                _this._on(false, element, eventHash);

                // Unsubscribe handler (removes event binding)
                var unsubscriber = function(){
                    _(eventSelectorArray)
                        .chain()
                        .map(function(eventSelector){ return eventSelector.split(' ')[0]; })
                        .each(function(eventName){
                            _this._off(element, eventName);
                        });
                }

                // Register unsubscriber
                _this._backonUnsubscribers = (_this._backonUnsubscribers || []).concat([unsubscriber]);
                return unsubscriber;
            });
        },

        destroy: function(){
            _(this._backonUnsubscribers).each(function(unsubscriber){ unsubscriber(); });
            this._backonUnsubscribers = undefined;
            this._super();
        }
    });
})(window.jQuery, window._, window.Bacon);


text:
<?php

class Google_Service_Games_TurnBasedAutoMatchingCriteria extends Google_Model
{
  public $exclusiveBitmask;
  public $kind;
  public $maxAutoMatchingPlayers;
  public $minAutoMatchingPlayers;

  public function setExclusiveBitmask($exclusiveBitmask)
  {
    $this->exclusiveBitmask = $exclusiveBitmask;
  }
  public function getExclusiveBitmask()
  {
    return $this->exclusiveBitmask;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setMaxAutoMatchingPlayers($maxAutoMatchingPlayers)
  {
    $this->maxAutoMatchingPlayers = $maxAutoMatchingPlayers;
  }
  public function getMaxAutoMatchingPlayers()
  {
    return $this->maxAutoMatchingPlayers;
  }
  public function setMinAutoMatchingPlayers($minAutoMatchingPlayers)
  {
    $this->minAutoMatchingPlayers = $minAutoMatchingPlayers;
  }
  public function getMinAutoMatchingPlayers()
  {
    return $this->minAutoMatchingPlayers;
  }
}


text:
<?php

namespace Component\Entity\Achievement;

use Doctrine\Common\Collections\ArrayCollection;

class PersonalActionCollection extends ArrayCollection
{
}


text:
function clean-vagrant {
  "${THIS_DIR}/halt-all-vagrants.sh"
  vagrant destroy --force
}


text:
https://developer.mozilla.org/en-US/docs/Web/CSS/font-synthesis

## none
```css
.selector {
  composes: none from 'hydrogencss/font-synthesis.css'
}
```

or:
```css
.selector {
  composes: none from 'hydrogencss/font-synthesis/none.css'
}
```


text:
package org.zaproxy.zap.extension.alertFilters.automation;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.parosproxy.paros.CommandLine;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.zaproxy.addon.automation.AutomationData;
import org.zaproxy.addon.automation.AutomationEnvironment;
import org.zaproxy.addon.automation.AutomationJob;
import org.zaproxy.addon.automation.AutomationProgress;
import org.zaproxy.addon.automation.jobs.JobData;
import org.zaproxy.addon.automation.jobs.JobUtils;
import org.zaproxy.zap.extension.alertFilters.AlertFilter;
import org.zaproxy.zap.extension.alertFilters.ExtensionAlertFilters;
import org.zaproxy.zap.model.Context;

public class AlertFilterJob extends AutomationJob {

    public enum Risk {
        FALSE_POSITIVE(-1, "alertFilters.panel.newalert.fp") {
            @Override
            public String toString() {
                return "False Positive";
            }
        },
        INFO(0, "alertFilters.panel.newalert.info") {
            @Override
            public String toString() {
                return "Info";
            }
        },
        LOW(1, "alertFilters.panel.newalert.low") {
            @Override
            public String toString() {
                return "Low";
            }
        },
        MEDIUM(2, "alertFilters.panel.newalert.medium") {
            @Override
            public String toString() {
                return "Medium";
            }
        },
        HIGH(3, "alertFilters.panel.newalert.high") {
            @Override
            public String toString() {
                return "High";
            }
        };

        private final int id;
        private final String i18nString;

        private Risk(int id, String i18nString) {
            this.id = id;
            this.i18nString = i18nString;
        };

        public int getId() {
            return this.id;
        }

        public String getI18nString() {
            return Constant.messages.getString(i18nString);
        }

        public static Risk getRisk(String name) {
            for (Risk risk : Risk.values()) {
                if (risk.toString().equalsIgnoreCase(name)) {
                    return risk;
                }
            }
            return null;
        }

        public static Risk getRiskFromI18n(String name) {
            for (Risk risk : Risk.values()) {
                if (risk.getI18nString().equalsIgnoreCase(name)) {
                    return risk;
                }
            }
            return null;
        }

        public static boolean isValidRisk(String name) {
            return getRisk(name) != null;
        }
    }

    private static final String JOB_NAME = "alertFilter";
    private static final String RESOURCES_DIR =
            "/org/zaproxy/zap/extension/alertFilters/resources/";

    private ExtensionAlertFilters extAlertFilters;

    private Data data;

    public AlertFilterJob() {
        data = new Data(this);
    }

    private ExtensionAlertFilters getExtAlertFilters() {
        if (extAlertFilters == null) {
            extAlertFilters =
                    Control.getSingleton()
                            .getExtensionLoader()
                            .getExtension(ExtensionAlertFilters.class);
        }
        return extAlertFilters;
    }

    @Override
    public void verifyParameters(AutomationProgress progress) {
        Map<?, ?> jobData = this.getJobData();
        if (jobData == null) {
            return;
        }
        Object alertFiltersObject = jobData.get("alertFilters");
        if (alertFiltersObject == null) {
            progress.warn(
                    Constant.messages.getString(
                            "alertFilters.automation.error.nofilters", this.getName()));
            return;
        }
        if (!(alertFiltersObject instanceof ArrayList)) {
            progress.error(
                    Constant.messages.getString(
                            "alertFilters.automation.error.badfilters", this.getName()));
            return;
        }
        ArrayList<?> alertFiltersData = (ArrayList<?>) alertFiltersObject;
        for (Object alertFilterObject : alertFiltersData.toArray()) {
            if (!(alertFilterObject instanceof LinkedHashMap)) {
                progress.error(
                        Constant.messages.getString(
                                "alertFilters.automation.error.badfilter",
                                this.getName(),
                                alertFilterObject.toString()));
                return;
            }
            AlertFilterData afd = new AlertFilterData();
            JobUtils.applyParamsToObject(
                    (LinkedHashMap<?, ?>) alertFilterObject, afd, this.getName(), null, progress);
            if (this.isValid(afd, progress)) {
                this.getData().addAlertFilters(afd);
            }
        }
    }

    private boolean isValid(AlertFilterData afd, AutomationProgress progress) {
        boolean result = true;
        if (afd.getRuleId() <= 0) {
            progress.error(
                    Constant.messages.getString(
                            "alertFilters.automation.error.noruleid", this.getName()));
            result = false;
        }
        if (!Risk.isValidRisk(afd.getNewRisk())) {
            progress.error(
                    Constant.messages.getString(
                            "alertFilters.automation.error.badrisk",
                            this.getName(),
                            afd.getNewRisk()));
            result = false;
        }
        if (JobUtils.unBox(afd.getUrlRegex())) {
            try {
                Pattern.compile(afd.getUrl());
            } catch (Exception e) {
                progress.error(
                        Constant.messages.getString(
                                "alertFilters.automation.error.badurlregex",
                                this.getName(),
                                afd.getUrl()));
                result = false;
            }
        }
        if (JobUtils.unBox(afd.getParameterRegex())) {
            try {
                Pattern.compile(afd.getParameter());
            } catch (Exception e) {
                progress.error(
                        Constant.messages.getString(
                                "alertFilters.automation.error.badparamregex",
                                this.getName(),
                                afd.getParameter()));
                result = false;
            }
        }
        if (JobUtils.unBox(afd.getAttackRegex())) {
            try {
                Pattern.compile(afd.getAttack());
            } catch (Exception e) {
                progress.error(
                        Constant.messages.getString(
                                "alertFilters.automation.error.badattackregex",
                                this.getName(),
                                afd.getAttack()));
                result = false;
            }
        }
        if (JobUtils.unBox(afd.getEvidenceRegex())) {
            try {
                Pattern.compile(afd.getEvidence());
            } catch (Exception e) {
                progress.error(
                        Constant.messages.getString(
                                "alertFilters.automation.error.badevidenceregex",
                                this.getName(),
                                afd.getEvidence()));
                result = false;
            }
        }
        return result;
    }

    @Override
    public Map<String, String> getCustomConfigParameters() {
        Map<String, String> map = super.getCustomConfigParameters();
        return map;
    }

    @Override
    public void runJob(AutomationEnvironment env, AutomationProgress progress) {

        if (JobUtils.unBox(this.getData().getParameters().getDeleteGlobalAlerts())) {
            this.getExtAlertFilters().deleteAllGlobalAlertFilters();
            progress.info(
                    Constant.messages.getString(
                            "alertFilters.automation.info.globaldelete", this.getName()));
        }
        List<AlertFilterData> alertFilters = this.getData().getAlertFilters();
        if (alertFilters != null) {
            AlertFilter af;
            for (AlertFilterData afd : alertFilters) {
                String contextName = afd.getContext();
                if (StringUtils.isEmpty(contextName)) {
                    // Its a global filter
                    af = this.dataToAlertFilter(-1, afd, env, progress);
                    if (af != null) {
                        this.getExtAlertFilters().addGlobalAlertFilter(af);
                        progress.info(
                                Constant.messages.getString(
                                        "alertFilters.automation.info.globaladd",
                                        this.getName(),
                                        af.getRuleId(),
                                        af.getNewRiskName()));
                    }
                } else {
                    Context ctx = env.getContext(afd.getContext());
                    if (ctx == null) {
                        progress.error(
                                Constant.messages.getString(
                                        "automation.error.context.unknown", afd.getContext()));

                    } else {
                        af = this.dataToAlertFilter(ctx.getId(), afd, env, progress);
                        if (af != null) {
                            this.getExtAlertFilters()
                                    .getContextAlertFilterManager(ctx.getId())
                                    .addAlertFilter(af);
                            progress.info(
                                    Constant.messages.getString(
                                            "alertFilters.automation.info.contextadd",
                                            this.getName(),
                                            contextName,
                                            af.getRuleId(),
                                            af.getNewRiskName()));
                        }
                    }
                }
            }
        }
    }

    protected AlertFilter dataToAlertFilter(
            int contextId,
            AlertFilterData data,
            AutomationEnvironment env,
            AutomationProgress progress) {
        Risk newRisk = Risk.getRisk(data.getNewRisk());
        if (newRisk == null) {
            return null;
        }

        return new AlertFilter(
                contextId,
                data.getRuleId(),
                newRisk.getId(),
                env.replaceVars(JobUtils.unBox(data.getUrl(), "")),
                JobUtils.unBox(data.getUrlRegex()),
                env.replaceVars(JobUtils.unBox(data.getParameter(), "")),
                JobUtils.unBox(data.getParameterRegex()),
                data.getAttack(),
                JobUtils.unBox(data.getAttackRegex()),
                data.getEvidence(),
                JobUtils.unBox(data.getEvidenceRegex()),
                true);
    }

    @Override
    public String getTemplateDataMin() {
        return getResourceAsString(getName() + "-min.yaml");
    }

    @Override
    public String getTemplateDataMax() {
        return getResourceAsString(getName() + "-max.yaml");
    }

    private String getResourceAsString(String name) {
        try (InputStream in =
                ExtensionAlertFilters.class.getResourceAsStream(RESOURCES_DIR + name)) {
            return new BufferedReader(new InputStreamReader(in))
                            .lines()
                            .collect(Collectors.joining("\n"))
                    + "\n";
        } catch (Exception e) {
            CommandLine.error(
                    Constant.messages.getString("automation.error.nofile", RESOURCES_DIR + name));
        }
        return "";
    }

    @Override
    public Order getOrder() {
        return Order.CONFIGS;
    }

    @Override
    public String getType() {
        return JOB_NAME;
    }

    @Override
    public Object getParamMethodObject() {
        return null;
    }

    @Override
    public String getParamMethodName() {
        return null;
    }

    @Override
    public void showDialog() {
        new AlertFilterJobDialog(this).setVisible(true);
    }

    @Override
    public String getSummary() {
        return Constant.messages.getString(
                "alertFilters.automation.dialog.summary", getAlertFilterCount());
    }

    @Override
    public Data getData() {
        return data;
    }

    @Override
    public Parameters getParameters() {
        return getData().getParameters();
    }

    protected int getAlertFilterCount() {
        if (this.getData().getAlertFilters() == null) {
            return 0;
        }
        return this.getData().getAlertFilters().size();
    }

    public static class Data extends JobData {
        private List<AlertFilterData> alertFilters;
        private Parameters parameters = new Parameters();

        public Data(AutomationJob job) {
            super(job);
        }

        public Parameters getParameters() {
            return parameters;
        }

        public List<AlertFilterData> getAlertFilters() {
            return alertFilters;
        }

        public void setAlertFilters(List<AlertFilterData> alertFilters) {
            this.alertFilters = alertFilters;
        }

        public void addAlertFilters(AlertFilterData alertFilter) {
            if (alertFilters == null) {
                alertFilters = new ArrayList<>();
            }
            this.alertFilters.add(alertFilter);
        }
    }

    public static class Parameters extends AutomationData {
        private Boolean deleteGlobalAlerts;

        public Boolean getDeleteGlobalAlerts() {
            return deleteGlobalAlerts;
        }

        public void setDeleteGlobalAlerts(Boolean deleteGlobalAlerts) {
            this.deleteGlobalAlerts = deleteGlobalAlerts;
        }
    }

    public static class AlertFilterData extends AutomationData {
        private int ruleId;
        private String ruleName;
        private String context;
        private String newRisk;
        private String parameter;
        private Boolean parameterRegex;
        private String url;
        private Boolean urlRegex;
        private String attack;
        private Boolean attackRegex;
        private String evidence;
        private Boolean evidenceRegex;

        public int getRuleId() {
            return ruleId;
        }

        public void setRuleId(int ruleId) {
            this.ruleId = ruleId;
        }

        public String getRuleName() {
            return ruleName;
        }

        public void setRuleName(String ruleName) {
            this.ruleName = ruleName;
        }

        public String getContext() {
            return context;
        }

        public void setContext(String context) {
            this.context = context;
        }

        public String getNewRisk() {
            return newRisk;
        }

        public void setNewRisk(String newRisk) {
            this.newRisk = newRisk;
        }

        public String getParameter() {
            return parameter;
        }

        public void setParameter(String parameter) {
            this.parameter = parameter;
        }

        public Boolean getParameterRegex() {
            return parameterRegex;
        }

        public void setParameterRegex(Boolean isParameterRegex) {
            this.parameterRegex = isParameterRegex;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public Boolean getUrlRegex() {
            return urlRegex;
        }

        public void setUrlRegex(Boolean isUrlRegex) {
            this.urlRegex = isUrlRegex;
        }

        public String getAttack() {
            return attack;
        }

        public void setAttack(String attack) {
            this.attack = attack;
        }

        public Boolean getAttackRegex() {
            return attackRegex;
        }

        public void setAttackRegex(Boolean isAttackRegex) {
            this.attackRegex = isAttackRegex;
        }

        public String getEvidence() {
            return evidence;
        }

        public void setEvidence(String evidence) {
            this.evidence = evidence;
        }

        public Boolean getEvidenceRegex() {
            return evidenceRegex;
        }

        public void setEvidenceRegex(Boolean isEvidenceRegex) {
            this.evidenceRegex = isEvidenceRegex;
        }
    }
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js Test Suite        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */
package org.scalajs.testsuite.javalib.lang

import org.scalajs.jasminetest.JasmineTest
import scala.scalajs.js

import scala.runtime.BoxedUnit

object ClassTest extends JasmineTest {

  describe("java.lang.Class") {

    it("should provide getSimpleName()") {
      expect(classOf[java.lang.Integer].getSimpleName()).toEqual("Integer")
      expect(classOf[java.lang.Class[_]].getSimpleName()).toEqual("Class")
      expect(classOf[scala.collection.Map[_, _]].getSimpleName()).toEqual("Map")
      expect(classOf[ClassTestClass#InnerClass].getSimpleName()).toEqual("InnerClass")
    }

    it("getComponentType()") {
      @noinline
      def testNoInline(clazz: Class[_], componentType: Class[_]): Unit =
        expect(clazz.getComponentType == componentType).toBeTruthy()

      @inline
      def test(clazz: Class[_], componentType: Class[_]): Unit = {
        testNoInline(clazz, componentType)
        expect(clazz.getComponentType == componentType).toBeTruthy()
      }

      test(classOf[Array[Object]], classOf[Object])
      test(classOf[Array[Int]], classOf[Int])
      test(classOf[Array[String]], classOf[String])
      test(classOf[Array[Seq[_]]], classOf[Seq[_]])
      test(classOf[Array[js.Date]], classOf[js.Date])
      test(classOf[Array[js.Dictionary[_]]], classOf[js.Dictionary[_]])
      test(classOf[Array[Unit]], classOf[BoxedUnit]) // not Unit

      test(classOf[Array[Array[Object]]], classOf[Array[Object]])
      test(classOf[Array[Array[Int]]], classOf[Array[Int]])
      test(classOf[Array[Array[String]]], classOf[Array[String]])
      test(classOf[Array[Array[Seq[_]]]], classOf[Array[Seq[_]]])
      test(classOf[Array[Array[js.Date]]], classOf[Array[js.Date]])
      test(classOf[Array[Array[js.Dictionary[_]]]], classOf[Array[js.Dictionary[_]]])
      test(classOf[Array[Array[Unit]]], classOf[Array[Unit]])

      test(classOf[Object], null)
      test(classOf[Int], null)
      test(classOf[String], null)
      test(classOf[Seq[_]], null)
      test(classOf[js.Date], null)
      test(classOf[js.Dictionary[_]], null)
      test(classOf[Unit], null)
    }

  }

}

class ClassTestClass {
  class InnerClass
}


text:
var React = require('react');
var $ = require('jquery');

var Dashboard = React.createClass({
  contextTypes: {
    router: React.PropTypes.object.isRequired
  },

  getInitialState: function() {
    return {
      dashboard: {
        name: 'production',
        turbine: 'localhost:8080'
      }
    };
  },

  componentDidMount: function() {
    var url = '/dashboard';
    $.ajax({
      url: url,
      dataType: 'json',
      cache: false,
      context: this
    })
    .done(function(data) {
      this.setState({dashboard: data});
      this._redirectToDefaultDashboard(this._dashboard());
    })
    .fail(function(xhr, status, err) {
      console.error(url, status, err.toString());
    });
  },

  componentWillReceiveProps: function(nextProps) {
    if (_.isUndefined(nextProps.params.id)) {
      this._redirectToDefaultDashboard(this.state.dashboard.name);
    }
  },

  _redirectToDefaultDashboard: function(name) {
    this.context.router.push('/dashboard/' + name);
  },

  _dashboard: function() {
    return this.props.params.id || this.state.dashboard.name;
  },

  render: function() {
    var style = {
      height: '100%',
      width:  '100%',
      minHeight: '1200px'
    };
    var src = '/assets/monitor/monitor.html?delay=1000&stream=' +
      encodeURIComponent(this.state.dashboard.turbine) +
      '%2Fturbine.stream%3Fcluster%3D' +
      this.props.params.id;
    return (<iframe id="tenacity-dashboard-iframe"
        seamless
        className="col-lg-12"
        style={style}
        src={src}>
        </iframe>);
  }
});

module.exports = Dashboard;


text:
package com.orientechnologies.orient.etl.transformer;

import com.orientechnologies.orient.core.command.OBasicCommandContext;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.etl.OETLPipeline;
import com.orientechnologies.orient.etl.OETLProcessor;
import com.orientechnologies.orient.etl.block.OBlock;

/**
 * Pass-through Transformer that execute a block.
 */
public class OBlockTransformer extends OAbstractTransformer {
  private OBlock block;

  @Override
  public ODocument getConfiguration() {
    return new ODocument().fromJSON("{parameters:[" + getCommonConfigurationParameters() + ","
        + "{block:{optional:false,description:'Block to execute'}}]}");
  }

  @Override
  public void configure(OETLProcessor iProcessor, final ODocument iConfiguration, OBasicCommandContext iContext) {
    super.configure(iProcessor, iConfiguration, iContext);
    final String[] fieldNames = iConfiguration.fieldNames();

    try {
      block = processor.getFactory().getBlock(fieldNames[0]);
      block.configure(processor, (ODocument) iConfiguration.field(fieldNames[0]), context);
    } catch (Exception e) {
      throw new OConfigurationException("[Block transformer] Error on configuring inner block", e);
    }
  }

  @Override
  public String getName() {
    return "block";
  }

  @Override
  public void setPipeline(OETLPipeline iPipeline) {
    super.setPipeline(iPipeline);
    block.setContext( context );
  }

  @Override
  protected Object executeTransform(final Object input) {
    context.setVariable("input", input);
    block.execute();
    return input;
  }
}


text:
namespace vr {

TextInputDelegate::TextInputDelegate() {}

TextInputDelegate::~TextInputDelegate() = default;

void TextInputDelegate::SetRequestFocusCallback(
    const RequestFocusCallback& callback) {
  request_focus_callback_ = callback;
}

void TextInputDelegate::SetRequestUnfocusCallback(
    const RequestUnfocusCallback& callback) {
  request_unfocus_callback_ = callback;
}

void TextInputDelegate::SetUpdateInputCallback(
    const UpdateInputCallback& callback) {
  update_input_callback_ = callback;
}

void TextInputDelegate::RequestFocus(int element_id) {
  if (!request_focus_callback_.is_null())
    request_focus_callback_.Run(element_id);
}

void TextInputDelegate::RequestUnfocus(int element_id) {
  if (!request_unfocus_callback_.is_null())
    request_unfocus_callback_.Run(element_id);
}

void TextInputDelegate::UpdateInput(const vr::TextInputInfo& info) {
  if (!update_input_callback_.is_null())
    update_input_callback_.Run(info);
}

}  // namespace vr


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.beepscore.android.sunshine" >

    <!-- Necessary to perform network access -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- Enables check network state, app can notify user if network is not reachable -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <!-- Permissions required by the sync adapter -->
    <uses-permission
        android:name="android.permission.READ_SYNC_SETTINGS"/>
    <uses-permission
        android:name="android.permission.WRITE_SYNC_SETTINGS"/>
    <uses-permission
        android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>

    <!-- Permissions required by google cloud messaging -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!-- Allow this app to register to receive messages -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- Prevent other apps from registering for and receiving this app's messages -->
    <permission android:name="com.beepscore.android.sunshine.permission.C2D_MESSAGE"
                android:protectionLevel="signature" />
    <uses-permission android:name="com.beepscore.android.sunshine.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:supportsRtl="true" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/ForecastTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".DetailActivity"
            android:label="@string/title_activity_detail"
            android:parentActivityName="com.beepscore.android.sunshine.MainActivity" >
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings"
            android:theme="@style/SettingsTheme"
            android:parentActivityName="com.beepscore.android.sunshine.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <provider
            android:authorities="@string/content_authority"
            android:name=".data.WeatherProvider"
            android:exported="false"
            android:syncable="true" />

        <!-- SyncAdapter's dummy authentication service -->
        <service
            android:name=".sync.SunshineAuthenticatorService"
            >
            <intent-filter>
                <action android:name="android.accounts.AccountAuthenticator" />
            </intent-filter>
            <meta-data
                android:name="android.accounts.AccountAuthenticator"
                android:resource="@xml/authenticator" />
        </service>

        <!-- The SyncAdapter service -->
        <service
            android:name=".sync.SunshineSyncService"
            android:exported="true"
            >
            <intent-filter>
                <action android:name="android.content.SyncAdapter" />
            </intent-filter>
            <meta-data
                android:name="android.content.SyncAdapter"
                android:resource="@xml/syncadapter" />
        </service>

        <!-- Google Cloud Messaging receiver and services -->
        <!-- For security, require anything attempting to send to this receiver must provide SEND permission -->
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <!-- REGISTRATION needed to support Android pre KitKat 4.4 -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.beepscore.android.sunshine.app" />
            </intent-filter>
        </receiver>

        <service
            android:name=".gcm.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <!-- MyInstanceIDListenerService handles registration tokens -->
        <service
            android:name=".gcm.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>

        <service
            android:name=".gcm.RegistrationIntentService"
            android:exported="false">
        </service>

    </application>

</manifest>


text:
package org.elasticsearch.xpack.core.security.authz.privilege;

import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Collection;

/**
 * A ConfigurableClusterPrivilege is a form of {@link ClusterPrivilege} that can be configured by an Elasticsearch security administrator
 * within a {@link org.elasticsearch.xpack.core.security.authz.RoleDescriptor}.
 */
public interface ConfigurableClusterPrivilege extends NamedWriteable, ToXContentFragment, ClusterPrivilege {

    /**
     * The category under which this privilege should be rendered when output as XContent.
     */
    Category getCategory();

    /**
     * A {@link ConfigurableClusterPrivilege} should generate a fragment of {@code XContent}, which consists of
     * a single field name, followed by its value (which may be an object, an array, or a simple value).
     */
    @Override
    XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException;

    /**
     * Categories exist for to segment privileges for the purposes of rendering to XContent.
     * {@link ConfigurableClusterPrivileges#toXContent(XContentBuilder, Params, Collection)} builds one XContent
     * object for a collection of {@link ConfigurableClusterPrivilege} instances, with the top level fields built
     * from the categories.
     */
    enum Category {
        APPLICATION(new ParseField("application"));

        public final ParseField field;

        Category(ParseField field) {
            this.field = field;
        }
    }
}


text:
Service components in ngTouch

        Name
        Description

        $swipe

The $swipe service is a service that abstracts the messier details of hold-and-drag swipe
behavior, to make implementing swipe-related directives more convenient.

        $touch

Provides the ngClickOverrideEnabled method.


text:
using Plugin.Settings;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Kalam.Portable
{
    public class ChatPage : BasePage<ChatViewModel>
    {
        public ChatPage()
        {
            SetupChat();
        }

        private void SetupChat()
        {
            //Init Message Entry
            var sendButton = new Button();
            sendButton.Text = " Send ";
            sendButton.VerticalOptions = LayoutOptions.EndAndExpand;
            sendButton.SetBinding(Button.CommandProperty, new Binding("SendMessageCommand"));

            var inputMessage = new Entry();
            inputMessage.HorizontalOptions = LayoutOptions.FillAndExpand;
            inputMessage.Keyboard = Keyboard.Chat;
            inputMessage.Placeholder = "Send lovely messages...";
            inputMessage.HeightRequest = 30;
            inputMessage.SetBinding(Entry.TextProperty, "ChatMessage.Message");

            var messageListView = new ChatListView();
            messageListView.VerticalOptions = LayoutOptions.FillAndExpand;
            messageListView.SetBinding(ChatListView.ItemsSourceProperty, new Binding("Messages"));
            messageListView.ItemTemplate = new DataTemplate(CreateMessageCell);

            Content = new StackLayout
            {
                Padding = Device.OnPlatform(new Thickness(6, 20, 6, 6), new Thickness(0), new Thickness(0)),
                Children =
                        {
                            new StackLayout
                                {
                                    Children = {inputMessage, sendButton},
                                    Orientation = StackOrientation.Horizontal,
                                    Padding = new Thickness(0, Device.OnPlatform(0, 20, 0),0,0),
                                },
                            messageListView,
                        }
            };
        }

        private Cell CreateMessageCell()
        {
            var timestampLabel = new Label();
            timestampLabel.SetBinding(Label.TextProperty, new Binding("Timestamp", stringFormat: "[{0:HH:mm}]"));
            timestampLabel.TextColor = Color.Silver;
            timestampLabel.Font = Font.SystemFontOfSize(14);

            var authorLabel = new Label();
            authorLabel.SetBinding(Label.TextProperty, new Binding("ChatMessage.Name", stringFormat: "{0}: "));
            authorLabel.TextColor = Device.OnPlatform(Color.Blue, Color.Yellow, Color.Yellow);
            authorLabel.Font = Font.SystemFontOfSize(14);

            var messageLabel = new Label();
            messageLabel.SetBinding(Label.TextProperty, new Binding("ChatMessage.Message"));
            messageLabel.Font = Font.SystemFontOfSize(14);

            var stack = new StackLayout
            {
                Orientation = StackOrientation.Horizontal,
                Children = { authorLabel, messageLabel }
            };

            if (Device.Idiom == TargetIdiom.Tablet)
            {
                stack.Children.Insert(0, timestampLabel);
            }

            var view = new MessageViewCell
            {
                View = stack
            };
            return view;
        }
    }
}


text:
.question-group   {
  margin-bottom:20px;
  background:#EEE;
  padding:20px;
}
.question-group label   {
  font-size:18px;
}


text:
// minimal component
interface Component<P = {}, S = {}> { }
declare class Component<P, S> {
    constructor(props: P, context?: any);
    render(): {};
    props: Readonly<{ children?: {} }> & Readonly<P>;
}

declare global {
    namespace JSX {
        interface Element  { }
        interface ElementClass  {
            render(): {};
        }
        interface ElementAttributesProperty { props: {}; }
        interface ElementChildrenAttribute { children: {}; }
        interface IntrinsicAttributes  { }
        interface IntrinsicClassAttributes<T> { }
    }
}

export interface RouteProps {
    children?: (props: { x: number }) => any;
}
export class MyComponent<T extends RouteProps = RouteProps> extends Component<T> { }
<MyComponent children={({ x }) => {}}/>


text: Fork