text:
/*******************************************************************************
  MPLAB Harmony Project Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This file contains the "main" function for an MPLAB Harmony project.

  Description:
    This file contains the "main" function for an MPLAB Harmony project.  The
    "main" function calls the "SYS_Initialize" function to initialize the state
    machines of all MPLAB Harmony modules in the system and it calls the
    "SYS_Tasks" function from within a system-wide "super" loop to maintain
    their correct operation. These two functions are implemented in
    configuration-specific files (usually "system_init.c" and "system_tasks.c")
    in a configuration-specific folder under the "src/system_config" folder
    within this project's top-level folder.  An MPLAB Harmony project may have
    more than one configuration, each contained within it's own folder under
    the "system_config" folder.
 *******************************************************************************/

// DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2013-2014 released Microchip Technology Inc.  All rights reserved.

//Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
 *******************************************************************************/
// DOM-IGNORE-END

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include <stddef.h>                     // Defines NULL
#include <stdbool.h>                    // Defines true
#include <stdlib.h>                     // Defines EXIT_FAILURE
#include "system/common/sys_module.h"   // SYS function prototypes

// *****************************************************************************
// *****************************************************************************
// Section: Main Entry Point
// *****************************************************************************
// *****************************************************************************

int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );

    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}

/*******************************************************************************
 End of File
*/


text:
#ifdef HAVE_CONFIG_H
#include "../../../../../ext_config.h"
#endif

#include <php.h>
#include "../../../../../php_ext.h"
#include "../../../../../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"

/**
 * Phalcon\Mvc\View\Exception
 *
 * Class for exceptions thrown by Phalcon\Mvc\View
 */
ZEPHIR_INIT_CLASS(Phalcon_Mvc_View_Engine_Volt_Exception) {

	ZEPHIR_REGISTER_CLASS_EX(Phalcon\\Mvc\\View\\Engine\\Volt, Exception, phalcon, mvc_view_engine_volt_exception, phalcon_mvc_view_exception_ce, NULL, 0);

	return SUCCESS;

}

redpajama_set_name: RedPajamaGithub


text:
package walk

type actionListObserver interface {
	onInsertedAction(action *Action) error
	onRemovingAction(action *Action) error
	onClearingActions() error
}

type nopActionListObserver struct{}

func (nopActionListObserver) onInsertedAction(action *Action) error {
	return nil
}

func (nopActionListObserver) onRemovingAction(action *Action) error {
	return nil
}

func (nopActionListObserver) onClearingActions() error {
	return nil
}

type ActionList struct {
	actions  []*Action
	observer actionListObserver
}

func newActionList(observer actionListObserver) *ActionList {
	if observer == nil {
		panic("observer == nil")
	}

	return &ActionList{observer: observer}
}

func (l *ActionList) Add(action *Action) error {
	return l.Insert(len(l.actions), action)
}

func (l *ActionList) AddMenu(menu *Menu) (*Action, error) {
	return l.InsertMenu(len(l.actions), menu)
}

func (l *ActionList) At(index int) *Action {
	return l.actions[index]
}

func (l *ActionList) Clear() error {
	if err := l.observer.onClearingActions(); err != nil {
		return err
	}

	for _, a := range l.actions {
		a.release()
	}

	l.actions = l.actions[:0]

	return nil
}

func (l *ActionList) Contains(action *Action) bool {
	return l.Index(action) > -1
}

func (l *ActionList) Index(action *Action) int {
	for i, a := range l.actions {
		if a == action {
			return i
		}
	}

	return -1
}

func (l *ActionList) indexInObserver(action *Action) int {
	var idx int

	for _, a := range l.actions {
		if a == action {
			return idx
		}
		if a.Visible() {
			idx++
		}
	}

	return -1
}

func (l *ActionList) Insert(index int, action *Action) error {
	l.actions = append(l.actions, nil)
	copy(l.actions[index+1:], l.actions[index:])
	l.actions[index] = action

	if err := l.observer.onInsertedAction(action); err != nil {
		l.actions = append(l.actions[:index], l.actions[index+1:]...)

		return err
	}

	action.addRef()

	if action.Visible() {
		return l.updateSeparatorVisibility()
	}

	return nil
}

func (l *ActionList) InsertMenu(index int, menu *Menu) (*Action, error) {
	action := NewAction()
	action.menu = menu

	if err := l.Insert(index, action); err != nil {
		return nil, err
	}

	return action, nil
}

func (l *ActionList) Len() int {
	return len(l.actions)
}

func (l *ActionList) Remove(action *Action) error {
	index := l.Index(action)
	if index == -1 {
		return nil
	}

	return l.RemoveAt(index)
}

func (l *ActionList) RemoveAt(index int) error {
	action := l.actions[index]
	if action.Visible() {
		if err := l.observer.onRemovingAction(action); err != nil {
			return err
		}
	}

	action.release()

	l.actions = append(l.actions[:index], l.actions[index+1:]...)

	if action.Visible() {
		return l.updateSeparatorVisibility()
	}

	return nil
}

func (l *ActionList) updateSeparatorVisibility() error {
	var hasCurVisAct bool
	var curVisSep *Action

	for _, a := range l.actions {
		if visible := a.Visible(); a.IsSeparator() {
			toggle := visible != hasCurVisAct

			if toggle {
				visible = !visible
				if err := a.SetVisible(visible); err != nil {
					return err
				}
			}

			if visible {
				curVisSep = a
			}

			hasCurVisAct = false
		} else if visible {
			hasCurVisAct = true
		}
	}

	if !hasCurVisAct && curVisSep != nil {
		return curVisSep.SetVisible(false)
	}

	return nil
}


text:
<?xml version="1.0"?>
<FileList
  Identity = "MMP.PF.WP8.TTML.Settings.SL.SDK, Version=1.0"
  DisplayName = "Microsoft Player Framework TTML Caption Settings Plugin"
  ProductFamilyName = "Microsoft.PlayerFramework"
  TargetFramework = "WindowsPhone,Version=v8.0"
  MinVSVersion = "11.0"
  MoreInfo = "http://playerframework.codeplex.com"
  ReferenceManagerEnumeration = "Files">
</FileList>


text:
var webpack = require('webpack');
var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');

// Webpack Config
var webpackConfig = {
  entry: {
    'polyfills': './src/polyfills.browser.ts',
    'vendor':    './src/vendor.browser.ts',
    'main':       './src/main.browser.ts',
  },

  output: {
    path: './dist',
  },

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: ['main', 'vendor', 'polyfills'], minChunks: Infinity }),
    new CopyWebpackPlugin([
      {from:'./src/css',to:'./css'},
      {from:'./src/images',to:'./images'},
      {from:'./src/favicon.ico',to:'./'},
      {from:'./src/index.html',to:'./'},
      {from:'./src/fonts',to:'./fonts'}
      ])
  ],

  module: {
    loaders: [
      // .ts files for TypeScript
      { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] },
      { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] },
      { test: /\.html$/, loader: 'raw-loader' },
      { test: /\.json$/, loader: 'json-loader' },

    ]
  }

};

// Our Webpack Defaults
var defaultConfig = {
  devtool: 'cheap-module-source-map',
  cache: true,
  debug: true,
  output: {
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          path.join(__dirname, 'node_modules', 'rxjs'),
          path.join(__dirname, 'node_modules', '@angular2-material'),
          path.join(__dirname, 'node_modules', '@angular'),
        ]
      }
    ],
    noParse: [
      path.join(__dirname, 'node_modules', 'zone.js', 'dist'),
      path.join(__dirname, 'node_modules', 'angular2', 'bundles')
    ]
  },

  resolve: {
    root: [ path.join(__dirname, 'src') ],
    extensions: ['', '.ts', '.js', '.json']
  },

  devServer: {
    historyApiFallback: true,
    watchOptions: { aggregateTimeout: 300, poll: 1000 }
  },

  node: {
    global: 1,
    crypto: 'empty',
    module: 0,
    Buffer: 0,
    clearImmediate: 0,
    setImmediate: 0
  },
}

var webpackMerge = require('webpack-merge');
module.exports = webpackMerge(defaultConfig, webpackConfig);


text:
#ifndef BOOST_PHOENIX_STL_CONTAINER_HPP
#define BOOST_PHOENIX_STL_CONTAINER_HPP

#include <boost/phoenix/stl/container/container.hpp>

#endif // BOOST_PHOENIX_STL_CONTAINER_HPP


text:
<?php

namespace Mosaic\Foundation\Components;

use Interop\Container\Definition\DefinitionProviderInterface;

class Registry
{
    /**
     * @var array
     */
    protected static $definitions = [];

    /**
     * @param DefinitionProviderInterface $definition
     */
    public function define(DefinitionProviderInterface $definition)
    {
        foreach ($definition->getDefinitions() as $abstract => $concrete) {
            $this->registerDefinition($abstract, $concrete);
        }
    }

    /**
     * @param string $as
     * @param object $define
     */
    private function registerDefinition($as, $define)
    {
        self::$definitions[$as] = $define;
    }

    /**
     * @return array
     */
    public function getDefinitions()
    {
        return self::$definitions;
    }

    /**
     * Flush the registry
     */
    public static function flush()
    {
        static::$definitions = [];
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.jredis.ri.alphazero.util Class Hierarchy
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../javadoc-stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.jredis.ri.alphazero.util

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.jredis.ri.alphazero.util.Assert
junit.framework.Assert

junit.framework.TestCase (implements junit.framework.Test)

org.jredis.ri.alphazero.util.ConvertTest

org.jredis.ri.alphazero.util.Convert
org.jredis.ri.alphazero.util.Log

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

org.jredis.ri.alphazero.util.Log.Category

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package net.ontrack.acceptance.dialog;

import net.ontrack.acceptance.pages.AbstractPage;
import org.openqa.selenium.WebDriver;

public abstract class AbstractDialog extends AbstractPage {

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


text:
(function ($, SmallGrid) {
    "use strict";

    $.extend(true, SmallGrid, {
        "Plugins": {
            "RowSelection": RowSelectionPlugin
        }
    });

    function RowSelectionPlugin(context, settings) {
        var self = this,
            suspended = false,
            selectedIds = [],
            selectionColumn = null,
            lastFocusedId = null;
        /*
         * Init && destroy
         */
        function init() {
            //register plugin settings
            if (!settings.plugins.RowSelection) {
                settings.plugins.RowSelection = {
                    enabled: false,
                    multipleRowSelection: false//allow multiplerow selection
                };
            }

            context.view.onCellClick.subscribe(handleCellClick);
            context.view.onHeaderClick.subscribe(handleHeaderClick);
            return self;
        }

        function destroy() {
            context.view.onCellClick.unsubscribe(handleCellClick);
            context.view.onHeaderClick.unsubscribe(handleHeaderClick);
        }

        /*
         * Handlers
         */
        function handleHeaderClick(evt) {
            if (settings.plugins.RowSelection.enabled !== true) return;

            if (evt.type === "selection-checkbox" && evt.column && evt.column.headerFormatter === "SelectionCheckbox") {

                var request = suspend();

                var headerNode = context.view.getColumnNodeById(evt.column.id);
                if (headerNode) {
                    headerNode.className += ' ' + settings.cssClass.disabledColor;
                }

                if (!evt.column[evt.column.field]) {
                    selectAll(evt.column);
                } else {
                    deselectAll(evt.column);
                }

                if (headerNode) {
                    headerNode.className.replace(' ' + settings.cssClass.disabledColor,'');
                }

                resume(request);
            }
        }

        function handleCellClick(evt) {
            if (settings.plugins.RowSelection.enabled !== true) return;

            var request = suspend();
            if (evt.event.shiftKey === true && settings.plugins.RowSelection.multipleRowSelection === true && lastFocusedId && lastFocusedId !== evt.row.id) {
                selectRowsRangeById(lastFocusedId, evt.row.id);

            } else if (evt.event.ctrlKey === true) {
                if (isRowSelected(evt.row.id) === true) {
                    deselectRowById(evt.row.id);
                } else {
                    if (settings.plugins.RowSelection.multipleRowSelection === false) {
                        deselectAllRows();
                    }
                    selectRowById(evt.row.id);
                }
            } else {
                if (isRowSelected(evt.row.id) === false || selectedIds.length > 0) {
                    deselectAllRows();
                    selectRowById(evt.row.id);
                }
            }

            resume(request);

            if (evt.event.shiftKey === false) lastFocusedId = evt.row.id;
        }

        /*
         * Internal
         */
        function findSelectionColumn() {
            if (selectionColumn) {
                selectionColumn = context.columnsModel.getColumnById(selectionColumn.id);
            }

            if (!selectionColumn) {
                var columns = context.columnsModel.getColumns();
                for (var i = 0, len = columns.length; i < len; i++) {
                    if (columns[i].headerFormatter && columns[i].headerFormatter === "SelectionCheckbox") {
                        return columns[i];
                    }
                }
            }
        }

        function selectAll(column, callback) {
            context.viewModel.requestRowsCallback(function (row, idx) {

                if (typeof callback === "function") {
                    if (!callback(row, idx)) return false;
                }

                selectedIds.push(row.id);
                row.rowCssClass += (row.rowCssClass.length ? " " : "") + settings.cssClass.rowSelected;
                var rowNode = context.view.getRowNodeById(row.id);
                if (rowNode) {
                    rowNode.className = rowNode.className + ' ' + settings.cssClass.rowSelected;
                }

                if (column) {
                    row.item[column.field] = true;
                    var cell = context.view.getCellNodeById(column.id, row.id);
                    if (cell && column && column.formatter != "") {
                        cell.innerHTML = context.view.getBuilder().buildCellContentHtml(column, row);
                    }
                }
            });

            if (column && !callback) context.columnsModel.setColumnPropertyById(column.id, column.field, true);
        }

        function deselectAll(column, callback) {
            if (selectedIds.length) {

                if (selectedIds.length < 3000) {
                    for (var i = selectedIds.length - 1; i >= 0; i--) {
                        deselectRow(context.rowsModel.getRowById(selectedIds[i]), column);
                    }
                } else {

                    context.rowsModel.foreach(function (row, idx) {
                        if (typeof callback === "function") {
                            if (!callback(row, idx)) return false;
                        }

                        row.rowCssClass = row.rowCssClass.replace(' ' + settings.cssClass.rowSelected, '').replace(settings.cssClass.rowSelected, '');
                        var rowNode = context.view.getRowNodeById(row.id);
                        if (rowNode) {
                            rowNode.className = rowNode.className.replace(' ' + settings.cssClass.rowSelected, '').replace(settings.cssClass.rowSelected, '');
                        }

                        if (column) {
                            row.item[column.field] = false;
                            var cell = context.view.getCellNodeById(column.id, row.id);
                            if (cell && column && column.formatter != "") {
                                cell.innerHTML = context.view.getBuilder().buildCellContentHtml(column, row);
                            }
                        }
                    });
                }
                selectedIds = [];
                if (column) context.columnsModel.setColumnPropertyById(column.id, column.field, false);
            }
        }

        function selectRow(row, column) {
            if (row) {
                selectedIds.push(row.id);

                var rowNode = context.view.getRowNodeById(row.id);
                if (rowNode) {
                    rowNode.className = rowNode.className + ' ' + settings.cssClass.rowSelected;
                }

                context.rowsModel.setRowPropertyById(
                    row.id,
                    'rowCssClass',
                    row.rowCssClass + (row.rowCssClass.length ? " " : "") + settings.cssClass.rowSelected
                );

                if (column) {
                    row.item[column.field] = true;
                    var cell = context.view.getCellNodeById(column.id, row.id);
                    if (cell && column && column.formatter != "") {
                        cell.innerHTML = context.view.getBuilder().buildCellContentHtml(column, row);
                    }
                }
            }
        }

        function deselectRow(row, column) {
            if (row) {
                var idx = selectedIds.indexOf(row.id);
                if (idx !== -1) {
                    selectedIds.splice(idx, 1);
                }

                var rowNode = context.view.getRowNodeById(row.id);
                if (rowNode) {
                    rowNode.className = rowNode.className.replace(' ' + settings.cssClass.rowSelected, '').replace(settings.cssClass.rowSelected, '');
                }

                context.rowsModel.setRowPropertyById(
                    row.id,
                    'rowCssClass',
                    row.rowCssClass.replace(' ' + settings.cssClass.rowSelected, '').replace(settings.cssClass.rowSelected, '')
                );

                if (column) {
                    row.item[column.field] = false;
                    var cell = context.view.getCellNodeById(column.id, row.id);
                    if (cell && column && column.formatter != "") {
                        cell.innerHTML = context.view.getBuilder().buildCellContentHtml(column, row);
                    }
                }
            }
        }

        function isSuspended() {
            return suspended;
        }

        function suspend() {
            suspended = true;
            return context.view.suspendRender();
        }

        function resume(request) {
            suspended = false;
            context.view.resumeRender(request);
        }

        /*
         * Public API
         */
        function selectRowById(id) {
            var request = suspend();
            selectRow(context.rowsModel.getRowById(id), findSelectionColumn());
            resume(request);
            return self;
        }

        function deselectRowById(id) {
            var request = suspend();
            deselectRow(context.rowsModel.getRowById(id), findSelectionColumn());
            resume(request);
            return self;
        }

        function selectRowByIndex(idx) {
            var request = suspend();
            selectRow(context.rowsModel.getRowByIndex(idx), findSelectionColumn());
            resume(request);
            return self;
        }

        function deselectRowByIndex(idx) {
            var request = suspend();
            deselectRow(context.rowsModel.getRowByIndex(idx), findSelectionColumn());
            resume(request);
            return self;
        }

        function selectRowsRangeByIndex(firstIdx, lastIdx) {
            if (firstIdx > -1 && lastIdx > -1) {
                var request = suspend();

                var column = findSelectionColumn();
                var startIndex = Math.min(lastIdx, firstIdx);
                var endIndex = Math.max(lastIdx, firstIdx);

                selectAll(column, function (row, idx) {
                    return startIndex <= idx && idx <= endIndex;
                });

                resume(request);
            }
            return self;
        }

        function selectRowsRangeById(firstId, lastId) {
            var firstFocusedIndex = context.rowsModel.getRowIndexById(firstId);
            var lastFocusedIndex = context.rowsModel.getRowIndexById(lastId);
            if (firstFocusedIndex !== -1 && lastFocusedIndex !== -1) {
                var request = suspend();

                var column = findSelectionColumn();
                var startIndex = Math.min(lastFocusedIndex, firstFocusedIndex);
                var endIndex = Math.max(lastFocusedIndex, firstFocusedIndex);

                selectAll(column, function (row, idx) {
                    return startIndex <= idx && idx <= endIndex;
                });

                resume(request);
            }
        }

        function deselectRowsRangeByIndex(firstIdx, lastIdx) {
            if (firstIdx > -1 && lastIdx > -1) {
                var request = suspend();

                var column = findSelectionColumn();
                var startIndex = Math.min(lastIdx, firstIdx);
                var endIndex = Math.max(lastIdx, firstIdx);

                deselectAll(column, function (row, idx) {
                    return startIndex <= idx && idx <= endIndex;
                });

                resume(request);
            }
            return self;
        }

        function deselectRowsRangeById(firstId, lastId) {
            var firstFocusedIndex = context.rowsModel.getRowIndexById(firstId);
            var lastFocusedIndex = context.rowsModel.getRowIndexById(lastId);
            if (firstFocusedIndex !== -1 && lastFocusedIndex !== -1) {
                var request = suspend();

                var column = findSelectionColumn();
                var startIndex = Math.min(lastFocusedIndex, firstFocusedIndex);
                var endIndex = Math.max(lastFocusedIndex, firstFocusedIndex);

                deselectAll(column, function (row, idx) {
                    return startIndex <= idx && idx <= endIndex;
                });

                resume(request);
            }
        }

        function deselectAllRows() {
            var request = suspend();
            deselectAll(findSelectionColumn());
            resume(request);
            return self;
        }

        function selectAllRows() {
            var request = suspend();
            selectAll(findSelectionColumn());
            resume(request);
            return self;
        }

        function isRowSelected(id) {
            return selectedIds.indexOf(id) !== -1;
        }

        function getSelectedRowsIds() {
            return selectedIds;
        }

        $.extend(this, {
            "init": init,
            "destroy": destroy,

            "deselectAllRows": deselectAllRows,
            "deselectRowById": deselectRowById,
            "deselectRowByIndex": deselectRowByIndex,
            "deselectRowsRangeById": deselectRowsRangeById,
            "deselectRowsRangeByIndex": deselectRowsRangeByIndex,
            "getSelectedRowsIds": getSelectedRowsIds,
            "isRowSelected": isRowSelected,
            "selectAllRows": selectAllRows,
            "selectRowById": selectRowById,
            "selectRowByIndex": selectRowByIndex,
            "selectRowsRangeById": selectRowsRangeById,
            "selectRowsRangeByIndex": selectRowsRangeByIndex
        });
    }

})(jQuery, window.SmallGrid = window.SmallGrid || {});


text:
<?php

namespace Magento\Integration\Test\Unit\Model\Oauth;

/**
 * Unit test for \Magento\Integration\Model\Oauth\Nonce
 */
class NonceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Integration\Model\Oauth\Nonce
     */
    protected $nonceModel;

    /**
     * @var \Magento\Framework\Model\Context|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $contextMock;

    /**
     * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $registryMock;

    /**
     * @var \Magento\Integration\Helper\Oauth\Data|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $oauthDataMock;

    /**
     * @var \Magento\Framework\Model\ResourceModel\AbstractResource|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $resourceMock;

    /**
     * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $resourceCollectionMock;

    protected function setUp()
    {
        $this->contextMock = $this->getMock(
            'Magento\Framework\Model\Context',
            ['getEventDispatcher'],
            [],
            '',
            false
        );
        $eventManagerMock = $this->getMockForAbstractClass(
            'Magento\Framework\Event\ManagerInterface',
            [],
            '',
            false,
            true,
            true,
            ['dispatch']
        );
        $this->contextMock->expects($this->once())
            ->method('getEventDispatcher')
            ->will($this->returnValue($eventManagerMock));
        $this->registryMock = $this->getMock(
            'Magento\Framework\Registry',
            [],
            [],
            '',
            false
        );
        $this->oauthDataMock = $this->getMock(
            'Magento\Integration\Helper\Oauth\Data',
            [],
            [],
            '',
            false
        );
        $this->resourceMock = $this->getMockForAbstractClass(
            'Magento\Framework\Model\ResourceModel\AbstractResource',
            [],
            '',
            false,
            true,
            true,
            ['getIdFieldName', 'selectByCompositeKey', 'deleteOldEntries']
        );
        $this->resourceCollectionMock = $this->getMock(
            'Magento\Framework\Data\Collection\AbstractDb',
            [],
            [],
            '',
            false
        );
        $this->nonceModel = new \Magento\Integration\Model\Oauth\Nonce(
            $this->contextMock,
            $this->registryMock,
            $this->oauthDataMock,
            $this->resourceMock,
            $this->resourceCollectionMock
        );
    }

    public function testAfterSave()
    {
        $this->oauthDataMock->expects($this->once())
            ->method('isCleanupProbability')
            ->will($this->returnValue(true));

        $this->oauthDataMock->expects($this->once())
            ->method('getCleanupExpirationPeriod')
            ->will($this->returnValue(30));

        $this->resourceMock->expects($this->once())
            ->method('deleteOldEntries')
            ->with(30)
            ->will($this->returnValue(1));

        $this->assertEquals($this->nonceModel, $this->nonceModel->afterSave());
    }

    public function testAfterSaveNoCleanupProbability()
    {
        $this->oauthDataMock->expects($this->once())
            ->method('isCleanupProbability')
            ->will($this->returnValue(false));

        $this->oauthDataMock->expects($this->never())
            ->method('getCleanupExpirationPeriod');

        $this->resourceMock->expects($this->never())
            ->method('deleteOldEntries');

        $this->assertEquals($this->nonceModel, $this->nonceModel->afterSave());
    }

    public function testLoadByCompositeKey()
    {
        $expectedData = ['testData'];
        $nonce = 'testNonce';
        $consumerId = 1;

        $this->resourceMock->expects($this->once())
            ->method('selectByCompositeKey')
            ->with($nonce, $consumerId)
            ->will($this->returnValue($expectedData));
        $this->nonceModel->loadByCompositeKey($nonce, $consumerId);

        $this->assertEquals($expectedData, $this->nonceModel->getData());
    }
}


text:
require 'spec_helper'

describe MergeRequests::CreateService do
  include ProjectForksHelper

  let(:project) { create(:project, :repository) }
  let(:user) { create(:user) }
  let(:assignee) { create(:user) }

  describe '#execute' do
    context 'valid params' do
      let(:opts) do
        {
          title: 'Awesome merge_request',
          description: 'please fix',
          source_branch: 'feature',
          target_branch: 'master',
          force_remove_source_branch: '1'
        }
      end

      let(:service) { described_class.new(project, user, opts) }
      let(:merge_request) { service.execute }

      before do
        project.add_maintainer(user)
        project.add_developer(assignee)
        allow(service).to receive(:execute_hooks)
      end

      it 'creates an MR' do
        expect(merge_request).to be_valid
        expect(merge_request.work_in_progress?).to be(false)
        expect(merge_request.title).to eq('Awesome merge_request')
        expect(merge_request.assignees).to be_empty
        expect(merge_request.merge_params['force_remove_source_branch']).to eq('1')
      end

      it 'executes hooks with default action' do
        expect(service).to have_received(:execute_hooks).with(merge_request)
      end

      it 'refreshes the number of open merge requests', :use_clean_rails_memory_store_caching do
        expect { service.execute }
          .to change { project.open_merge_requests_count }.from(0).to(1)
      end

      it 'does not creates todos' do
        attributes = {
          project: project,
          target_id: merge_request.id,
          target_type: merge_request.class.name
        }

        expect(Todo.where(attributes).count).to be_zero
      end

      it 'creates exactly 1 create MR event' do
        attributes = {
          action: Event::CREATED,
          target_id: merge_request.id,
          target_type: merge_request.class.name
        }

        expect(Event.where(attributes).count).to eq(1)
      end

      describe 'when marked with /wip' do
        context 'in title and in description' do
          let(:opts) do
            {
              title: 'WIP: Awesome merge_request',
              description: "well this is not done yet\n/wip",
              source_branch: 'feature',
              target_branch: 'master',
              assignees: [assignee]
            }
          end

          it 'sets MR to WIP' do
            expect(merge_request.work_in_progress?).to be(true)
          end
        end

        context 'in description only' do
          let(:opts) do
            {
              title: 'Awesome merge_request',
              description: "well this is not done yet\n/wip",
              source_branch: 'feature',
              target_branch: 'master',
              assignees: [assignee]
            }
          end

          it 'sets MR to WIP' do
            expect(merge_request.work_in_progress?).to be(true)
          end
        end
      end

      context 'when merge request is assigned to someone' do
        let(:opts) do
          {
            title: 'Awesome merge_request',
            description: 'please fix',
            source_branch: 'feature',
            target_branch: 'master',
            assignees: [assignee]
          }
        end

        it { expect(merge_request.assignees).to eq([assignee]) }

        it 'creates a todo for new assignee' do
          attributes = {
            project: project,
            author: user,
            user: assignee,
            target_id: merge_request.id,
            target_type: merge_request.class.name,
            action: Todo::ASSIGNED,
            state: :pending
          }

          expect(Todo.where(attributes).count).to eq 1
        end
      end

      context 'when head pipelines already exist for merge request source branch' do
        let(:shas) { project.repository.commits(opts[:source_branch], limit: 2).map(&:id) }
        let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) }
        let!(:pipeline_2) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[0]) }
        let!(:pipeline_3) { create(:ci_pipeline, project: project, ref: "other_branch", project_id: project.id) }

        before do
          # rubocop: disable DestroyAll
          project.merge_requests
            .where(source_branch: opts[:source_branch], target_branch: opts[:target_branch])
            .destroy_all
          # rubocop: enable DestroyAll
        end

        it 'sets head pipeline' do
          merge_request = service.execute

          expect(merge_request.reload.head_pipeline).to eq(pipeline_2)
          expect(merge_request).to be_persisted
        end

        context 'when the new pipeline is associated with an old sha' do
          let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[0]) }
          let!(:pipeline_2) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) }

          it 'sets an old pipeline with associated with the latest sha as the head pipeline' do
            merge_request = service.execute

            expect(merge_request.reload.head_pipeline).to eq(pipeline_1)
            expect(merge_request).to be_persisted
          end
        end

        context 'when there are no pipelines with the diff head sha' do
          let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) }
          let!(:pipeline_2) { create(:ci_pipeline, project: project, ref: opts[:source_branch], project_id: project.id, sha: shas[1]) }

          it 'does not set the head pipeline' do
            merge_request = service.execute

            expect(merge_request.reload.head_pipeline).to be_nil
            expect(merge_request).to be_persisted
          end
        end
      end

      describe 'Pipelines for merge requests' do
        before do
          stub_ci_pipeline_yaml_file(YAML.dump(config))
        end

        context "when .gitlab-ci.yml has merge_requests keywords" do
          let(:config) do
            {
              test: {
                stage: 'test',
                script: 'echo',
                only: ['merge_requests']
              }
            }
          end

          it 'creates a detached merge request pipeline and sets it as a head pipeline' do
            expect(merge_request).to be_persisted

            merge_request.reload
            expect(merge_request.pipelines_for_merge_request.count).to eq(1)
            expect(merge_request.actual_head_pipeline).to be_detached_merge_request_pipeline
          end

          context 'when merge request is submitted from forked project' do
            let(:target_project) { fork_project(project, nil, repository: true) }

            let(:opts) do
              {
                title: 'Awesome merge_request',
                source_branch: 'feature',
                target_branch: 'master',
                target_project_id: target_project.id
              }
            end

            before do
              target_project.add_developer(assignee)
              target_project.add_maintainer(user)
            end

            it 'create legacy detached merge request pipeline for fork merge request' do
              expect(merge_request.actual_head_pipeline)
                .to be_legacy_detached_merge_request_pipeline
            end
          end

          context 'when ci_use_merge_request_ref feature flag is false' do
            before do
              stub_feature_flags(ci_use_merge_request_ref: false)
            end

            it 'create legacy detached merge request pipeline for non-fork merge request' do
              expect(merge_request.actual_head_pipeline)
                .to be_legacy_detached_merge_request_pipeline
            end
          end

          context 'when there are no commits between source branch and target branch' do
            let(:opts) do
              {
                title: 'Awesome merge_request',
                description: 'please fix',
                source_branch: 'not-merged-branch',
                target_branch: 'master'
              }
            end

            it 'does not create a detached merge request pipeline' do
              expect(merge_request).to be_persisted

              merge_request.reload
              expect(merge_request.pipelines_for_merge_request.count).to eq(0)
            end
          end

          context "when branch pipeline was created before a merge request pipline has been created" do
            before do
              create(:ci_pipeline, project: merge_request.source_project,
                                   sha: merge_request.diff_head_sha,
                                   ref: merge_request.source_branch,
                                   tag: false)

              merge_request
            end

            it 'sets the latest detached merge request pipeline as the head pipeline' do
              expect(merge_request.actual_head_pipeline).to be_merge_request_event
            end
          end
        end

        context "when .gitlab-ci.yml does not have merge_requests keywords" do
          let(:config) do
            {
              test: {
                stage: 'test',
                script: 'echo'
              }
            }
          end

          it 'does not create a detached merge request pipeline' do
            expect(merge_request).to be_persisted

            merge_request.reload
            expect(merge_request.pipelines_for_merge_request.count).to eq(0)
          end
        end
      end
    end

    it_behaves_like 'new issuable record that supports quick actions' do
      let(:default_params) do
        {
          source_branch: 'feature',
          target_branch: 'master'
        }
      end
    end

    context 'Quick actions' do
      context 'with assignee and milestone in params and command' do
        let(:merge_request) { described_class.new(project, user, opts).execute }
        let(:milestone) { create(:milestone, project: project) }

        let(:opts) do
          {
            assignee_ids: create(:user).id,
            milestone_id: 1,
            title: 'Title',
            description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}"),
            source_branch: 'feature',
            target_branch: 'master'
          }
        end

        before do
          project.add_maintainer(user)
          project.add_maintainer(assignee)
        end

        it 'assigns and sets milestone to issuable from command' do
          expect(merge_request).to be_persisted
          expect(merge_request.assignees).to eq([assignee])
          expect(merge_request.milestone).to eq(milestone)
        end
      end
    end

    context 'merge request create service' do
      context 'asssignee_id' do
        let(:assignee) { create(:user) }

        before do
          project.add_maintainer(user)
        end

        it 'removes assignee_id when user id is invalid' do
          opts = { title: 'Title', description: 'Description', assignee_ids: [-1] }

          merge_request = described_class.new(project, user, opts).execute

          expect(merge_request.assignee_ids).to be_empty
        end

        it 'removes assignee_id when user id is 0' do
          opts = { title: 'Title', description: 'Description', assignee_ids: [0] }

          merge_request = described_class.new(project, user, opts).execute

          expect(merge_request.assignee_ids).to be_empty
        end

        it 'saves assignee when user id is valid' do
          project.add_maintainer(assignee)
          opts = { title: 'Title', description: 'Description', assignee_ids: [assignee.id] }

          merge_request = described_class.new(project, user, opts).execute

          expect(merge_request.assignees).to eq([assignee])
        end

        context 'when assignee is set' do
          let(:opts) do
            {
              title: 'Title',
              description: 'Description',
              assignee_ids: [assignee.id],
              source_branch: 'feature',
              target_branch: 'master'
            }
          end

          it 'invalidates open merge request counter for assignees when merge request is assigned' do
            project.add_maintainer(assignee)

            described_class.new(project, user, opts).execute

            expect(assignee.assigned_open_merge_requests_count).to eq 1
          end
        end

        context "when issuable feature is private" do
          before do
            project.project_feature.update(issues_access_level: ProjectFeature::PRIVATE,
                                           merge_requests_access_level: ProjectFeature::PRIVATE)
          end

          levels = [Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PUBLIC]

          levels.each do |level|
            it "removes not authorized assignee when project is #{Gitlab::VisibilityLevel.level_name(level)}" do
              project.update(visibility_level: level)
              opts = { title: 'Title', description: 'Description', assignee_ids: [assignee.id] }

              merge_request = described_class.new(project, user, opts).execute

              expect(merge_request.assignee_id).to be_nil
            end
          end
        end
      end
    end

    context 'while saving references to issues that the created merge request closes' do
      let(:first_issue) { create(:issue, project: project) }
      let(:second_issue) { create(:issue, project: project) }

      let(:opts) do
        {
          title: 'Awesome merge_request',
          source_branch: 'feature',
          target_branch: 'master',
          force_remove_source_branch: '1'
        }
      end

      before do
        project.add_maintainer(user)
        project.add_developer(assignee)
      end

      it 'creates a `MergeRequestsClosingIssues` record for each issue' do
        issue_closing_opts = opts.merge(description: "Closes #{first_issue.to_reference} and #{second_issue.to_reference}")
        service = described_class.new(project, user, issue_closing_opts)
        allow(service).to receive(:execute_hooks)
        merge_request = service.execute

        issue_ids = MergeRequestsClosingIssues.where(merge_request: merge_request).pluck(:issue_id)
        expect(issue_ids).to match_array([first_issue.id, second_issue.id])
      end
    end

    context 'when source and target projects are different' do
      let(:target_project) { fork_project(project, nil, repository: true) }

      let(:opts) do
        {
          title: 'Awesome merge_request',
          source_branch: 'feature',
          target_branch: 'master',
          target_project_id: target_project.id
        }
      end

      context 'when user can not access source project' do
        before do
          target_project.add_developer(assignee)
          target_project.add_maintainer(user)
        end

        it 'raises an error' do
          expect { described_class.new(project, user, opts).execute }
            .to raise_error Gitlab::Access::AccessDeniedError
        end
      end

      context 'when user can not access target project' do
        before do
          target_project.add_developer(assignee)
          target_project.add_maintainer(user)
        end

        it 'raises an error' do
          expect { described_class.new(project, user, opts).execute }
            .to raise_error Gitlab::Access::AccessDeniedError
        end
      end

      context 'when the user has access to both projects' do
        before do
          target_project.add_developer(user)
          project.add_developer(user)
        end

        it 'creates the merge request' do
          merge_request = described_class.new(project, user, opts).execute

          expect(merge_request).to be_persisted
        end

        it 'does not create the merge request when the target project is archived' do
          target_project.update!(archived: true)

          expect { described_class.new(project, user, opts).execute }
            .to raise_error Gitlab::Access::AccessDeniedError
        end
      end
    end

    context 'when user sets source project id' do
      let(:another_project) { create(:project) }

      let(:opts) do
        {
          title: 'Awesome merge_request',
          source_branch: 'feature',
          target_branch: 'master',
          source_project_id: another_project.id
        }
      end

      before do
        project.add_developer(assignee)
        project.add_maintainer(user)
      end

      it 'ignores source_project_id' do
        merge_request = described_class.new(project, user, opts).execute

        expect(merge_request.source_project_id).to eq(project.id)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Controller/NotificationController.php</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/views/User/edit_user.html.twig</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Controller/UserController.php</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Controller/LikeController.php</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/config/routing/user.yml</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/views/Publication/home.html.twig</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/views/User/login.html.twig</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/views/User/register.html.twig</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/views/User/profile.html.twig</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/views/Layouts/layout.html.twig</file>
            <file>file:/C:/wamp64/www/social-network/web/app_dev.php</file>
            <file>file:/C:/wamp64/www/social-network/web/assets/css/styles.css</file>
            <file>file:/C:/wamp64/www/social-network/web/app.php</file>
            <file>file:/C:/wamp64/www/social-network/src/AppBundle/Resources/config/routing/like.yml</file>
        </group>
    </open-files>
</project-private>


text:
<?php

// Require the base class.
require_once dirname(__DIR__) . "/BaseExample.php";

/**
 * This example returns the status for a specified report.
 */
class CheckFileStatus extends BaseExample {
  /**
   * {@inheritdoc}
   * @see BaseExample::getInputParameters()
   * @return array
   */
  protected function getInputParameters() {
    return array(
      array('name' => 'user_profile_id',
            'display' => 'User Profile ID',
            'required' => true),
      array('name' => 'report_id',
            'display' => 'Report ID',
            'required' => true),
      array('name' => 'report_file_id',
            'display' => 'Report File ID',
            'required' => true)
    );
  }

  /**
   * {@inheritdoc}
   * @see BaseExample::run()
   */
  public function run() {
    $values = $this->formValues;

    printf(
      '
Getting status of report file with ID %s
',
      $values['report_file_id']
    );

    $report_file = $this->service->reports_files->get(
      $values['user_profile_id'],
      $values['report_id'],
      $values['report_file_id']);

    $this->printResultsTable('File status', array($report_file));
  }

  /**
   * {@inheritdoc}
   * @see BaseExample::getName()
   * @return string
   */
  public function getName() {
    return 'Check File Generation Status';
  }

  /**
   * {@inheritdoc}
   * @see BaseExample::getResultsTableHeaders()
   * @return array
   */
  public function getResultsTableHeaders() {
    return array(
      'id' => 'File ID',
      'fileName' => 'File Name',
      'reportId' => 'Report ID',
      'format' => 'File Format',
      'status' => 'Status'
    );
  }
}


text:
layout: organization
category: national

title: Room to Read
impact_area: Children
keywords:
location_services:
location_offices:
website: www.roomtoread.org

description:
mission: |
  We partner with local communities throughout the developing world to provide quality educational opportunities by establishing libraries, creating local language children's literature, constructing schools, and providing education to girls. We seek to intervene early in the lives of children in the belief that education empowers people to improve socioeconomic conditions for their families, communities, countries and future generations. Through the opportunities that only education can provide, we strive to break the cycle of poverty, one child at a time.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: San Francisco
state: CA
address: |
  111 Sutter St, 16th fl.
  San Francisco CA 94104
lat: 37.78976
lng: -122.402524
phone: 415-561-3331
ext:
fax: 415-591-0580
email:
preferred_contact:
contact_person_intro:
---


text:
<?xml version="1.0"?>

<config>
    <modules>
        <Yellow_Bitcoin>
            <version>1.0.1</version>
            <depends>
                <Mage_Payment/>
            </depends>
        </Yellow_Bitcoin>
    </modules>
    <global>
        <helpers>
            <bitcoin>
                <class>Yellow_Bitcoin_Helper</class>
            </bitcoin>
        </helpers>
        <blocks>
            <bitcoin>
                <class>Yellow_Bitcoin_Block</class>
            </bitcoin>
        </blocks>
        <models>
            <bitcoin>
                <class>Yellow_Bitcoin_Model</class>
                <resourceModel>bitcoin_resource</resourceModel>
            </bitcoin>
            <bitcoin_resource>
                <class>Yellow_Bitcoin_Model_Resource</class>
                <entities>
                    <ipn>

yellow_ipn

                    </ipn>
                    <log>

yellow_log

                    </log>
                </entities>
            </bitcoin_resource>
        </models>
        <resources>
            <bitcoin_setup>
                <setup>
                    <module>Yellow_Bitcoin</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </bitcoin_setup>
            <bitcoin_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </bitcoin_write>
            <bitcoin_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </bitcoin_read>
        </resources>
    </global>
    <frontend>
        <routers>
            <bitcoin>
                <use>standard</use>
                <args>
                    <module>Yellow_Bitcoin</module>
                    <frontName>bitcoin</frontName>
                </args>
            </bitcoin>
        </routers>
        <layout>
            <updates>
                <bitcoin>
                    <file>bitcoin.xml</file>
                </bitcoin>
            </updates>
        </layout>
    </frontend>

    <admin>
        <routers>
            <bitcoin>
                <use>admin</use>
                <args>
                    <module>Yellow_Bitcoin</module>
                    <frontName>bitcoin</frontName>
                </args>
            </bitcoin>
        </routers>
    </admin>
    <adminhtml>
        <menu>
            <system>
                <children>
                    <bitcoin module="bitcoin">
                        <title>Yellow Bitcoin</title>
                        <sort_order>1</sort_order>
                        <children>
                            <log module="bitcoin">
                                <title>View Log</title>
                                <sort_order>0</sort_order>
                                <action>bitcoin/adminhtml_log</action>
                            </log>
                            <ipn module="bitcoin">
                                <title>View Ipn List</title>
                                <sort_order>10</sort_order>
                                <action>bitcoin/adminhtml_ipn</action>
                            </ipn>
                        </children>
                    </bitcoin>
                </children>
            </system>
        </menu>
        <acl>
            <resources>
                <all>
                    <title>Allow Everything</title>
                </all>
                <admin>
                    <children>
                        <bitcoin translate="title" module="bitcoin">
                            <title>Yellow Bitcoin</title>
                            <sort_order>1000</sort_order>
                            <children>
                                <log translate="title">
                                    <title>Manage Log</title>
                                    <sort_order>0</sort_order>
                                </log>
                                <ipn translate="title">
                                    <title>Manage Ipn</title>
                                    <sort_order>10</sort_order>
                                </ipn>
                            </children>
                        </bitcoin>
                    </children>
                </admin>
            </resources>
        </acl>
        <layout>
            <updates>
                <bitcoin>
                    <file>bitcoin.xml</file>
                </bitcoin>
            </updates>
        </layout>
    </adminhtml>
    <default>
        <payment>
            <bitcoin>
                <active>1</active>
                <model>bitcoin/bitcoin</model>

                <title></title>
                <fullscreen>0</fullscreen>

                <allowspecific>0</allowspecific>
                <currencies>USD,AED</currencies>
                <public_key></public_key>
                <private_key></private_key>
                <payment_action>authorize</payment_action>
                <db_log>0</db_log>
            </bitcoin>
        </payment>
    </default>
</config>


text:
using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Configuration;
using MongoDB.Connections;

namespace MongoDB
{
    /// <summary>
    ///   Lazily loaded meta data on the collection.
    /// </summary>
    public class CollectionMetadata
    {
        private readonly MongoDatabase _database;
        private readonly string _fullName;
        private readonly Dictionary<string, Document> _indexes = new Dictionary<string, Document>();
        private readonly string _name;
        private bool _gotIndexes;
        private Document _options;

        /// <summary>
        /// Initializes a new instance of the <see cref="CollectionMetadata"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="collectionName">The name.</param>
        /// <param name="connection">The connection.</param>
        internal CollectionMetadata(MongoConfiguration configuration, string databaseName, string collectionName, Connection connection)
        {
            //Todo: Add public constrcutors for users to call
            _fullName = databaseName + "." + collectionName;
            _name = collectionName;
            _database = new MongoDatabase(configuration, connection, databaseName);
        }

        /// <summary>
        ///   Gets the options.
        /// </summary>
        /// <value>The options.</value>
        public Document Options
        {
            get
            {
                if(_options != null)
                    return _options;
                var doc = _database["system.namespaces"].FindOne(new Document().Add("name", _fullName)) ?? new Document();
                if(doc.ContainsKey("create"))
                    doc.Remove("create");
                //Not sure why this is here.  The python driver has it.
                _options = doc;
                return _options;
            }
        }

        /// <summary>
        ///   Gets the indexes.
        /// </summary>
        /// <value>The indexes.</value>
        public Dictionary<string, Document> Indexes
        {
            get
            {
                if(_gotIndexes)
                    return _indexes;

                _indexes.Clear();

                var docs = _database["system.indexes"].Find(new Document().Add("ns", _fullName));
                foreach(var doc in docs.Documents)
                    _indexes.Add((string)doc["name"], doc);

                return _indexes;
            }
        }

        /// <summary>
        ///   Creates the index.
        /// </summary>
        /// <param name = "name">The name.</param>
        /// <param name = "fieldsAndDirections">The fields and directions.</param>
        /// <param name = "unique">if set to <c>true</c> [unique].</param>
        public void CreateIndex(string name, Document fieldsAndDirections, bool unique)
        {
            var index = new Document();
            index["name"] = name;
            index["ns"] = _fullName;
            index["key"] = fieldsAndDirections;
            index["unique"] = unique;
            _database["system.indexes"].Insert(index);
            Refresh();
        }

        /// <summary>
        ///   Creates the index.
        /// </summary>
        /// <param name = "fieldsAndDirections">The fields and directions.</param>
        /// <param name = "unique">if set to <c>true</c> [unique].</param>
        public void CreateIndex(Document fieldsAndDirections, bool unique)
        {
            var name = generateIndexName(fieldsAndDirections, unique);
            CreateIndex(name, fieldsAndDirections, unique);
        }

        /// <summary>
        ///   Drops the index.
        /// </summary>
        /// <param name = "name">The name.</param>
        public void DropIndex(string name)
        {
            var cmd = new Document();
            cmd.Add("deleteIndexes", _name).Add("index", name);
            _database.SendCommand(cmd);
            Refresh();
        }

        /// <summary>
        ///   Renames the specified new name.
        /// </summary>
        /// <param name = "newName">The new name.</param>
        public void Rename(string newName)
        {
            if(string.IsNullOrEmpty(newName))
                throw new ArgumentException("Name must not be null or empty", "newName");

            var cmd = new Document();
            cmd.Add("renameCollection", _fullName).Add("to", _database.Name + "." + newName);
            _database.GetSisterDatabase("admin").SendCommand(cmd);
            Refresh();
        }

        /// <summary>
        ///   Refreshes this instance.
        /// </summary>
        public void Refresh()
        {
            _indexes.Clear();
            _gotIndexes = false;
            _options = null;
        }

        /// <summary>
        ///   Generates the name of the index.
        /// </summary>
        /// <param name = "fieldsAndDirections">The fields and directions.</param>
        /// <param name = "unique">if set to <c>true</c> [unique].</param>
        /// <returns></returns>
        protected string generateIndexName(Document fieldsAndDirections, bool unique)
        {
            var sb = new StringBuilder("_");
            foreach(var key in fieldsAndDirections.Keys)
                sb.Append(key).Append("_");
            if(unique)
                sb.Append("unique_");

            return sb.ToString();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using UnityEngine;
using Object=UnityEngine.Object;

[RequireComponent(typeof(Camera))]
public class OuyaPlotAxisButton : MonoBehaviour
{
    public Material PlotMaterial = null;

    private int TextureSize = 128;

    private Texture2D m_texture = null;
    private Color32[] m_pixels = null;

    private int m_timeIndex = 0;

    private string[] m_strAxises = new string[]
                                       {
                                           "Joy{0} Axis 1",
                                           "Joy{0} Axis 2",
                                           "Joy{0} Axis 3",
                                           "Joy{0} Axis 4",
                                           "Joy{0} Axis 5",
                                           "Joy{0} Axis 6",
                                           "Joy{0} Axis 7",
                                           "Joy{0} Axis 8",
                                           "Joy{0} Axis 9",
                                           "Joy{0} Axis 10",
                                       };

    private string[] m_strButtons = new string[]
                                       {
                                           "Joystick{0}Button0",
                                           "Joystick{0}Button1",
                                           "Joystick{0}Button2",
                                           "Joystick{0}Button3",
                                           "Joystick{0}Button4",
                                           "Joystick{0}Button5",
                                           "Joystick{0}Button6",
                                           "Joystick{0}Button7",
                                           "Joystick{0}Button8",
                                           "Joystick{0}Button9",
                                           "Joystick{0}Button10",
                                           "Joystick{0}Button11",
                                           "Joystick{0}Button12",
                                           "Joystick{0}Button13",
                                           "Joystick{0}Button14",
                                           "Joystick{0}Button15",
                                           "Joystick{0}Button16",
                                           "Joystick{0}Button17",
                                           "Joystick{0}Button18",
                                           "Joystick{0}Button19",
                                       };

    private Dictionary<string, bool> m_inputMap = new Dictionary<string, bool>();

    public void OnEnable()
    {
        m_texture = new Texture2D(TextureSize, TextureSize, TextureFormat.ARGB32, false);
        m_texture.filterMode = FilterMode.Point;
        m_pixels = m_texture.GetPixels32();
        Color32 tansparent = new Color32(0, 0, 0, 0);
        for (int i = 0; i < m_pixels.Length; ++i)
        {
            m_pixels[i] = tansparent;
        }
        m_texture.SetPixels32(m_pixels);
        m_texture.Apply();

        if (PlotMaterial)
        {
            PlotMaterial.mainTexture = m_texture;
        }

        ClearInputMap();
    }

    public void OnDisable()
    {
        if (PlotMaterial)
        {
            PlotMaterial.mainTexture = null;
            PlotMaterial.mainTextureOffset = Vector2.zero;
        }

        if (null != m_texture)
        {
            Object.DestroyImmediate(m_texture, true);
            m_texture = null;
        }
    }

    void ClearInputMap()
    {
        for (int player = 1; player <= 8; ++player)
        {
            foreach (string s in m_strAxises)
            {
                string axisName = string.Format(s, player);
                m_inputMap[axisName] = false;
            }
            foreach (string s in m_strButtons)
            {
                string buttonName = string.Format(s, player);
                m_inputMap[buttonName] = false;
            }
        }
    }

    void CheckForInput()
    {
        foreach (string s in m_strAxises)
        {
            string axisName = string.Format(s, (int)OuyaExampleCommon.Player);
            if (Input.GetAxis(axisName) != 0f)
            {
                m_inputMap[axisName] = true;
            }
        }
        foreach (string s in m_strButtons)
        {
            string buttonName = string.Format(s, (int)OuyaExampleCommon.Player);
            KeyCode key = (KeyCode)(OuyaKeyCode)Enum.Parse(typeof(OuyaKeyCode), buttonName);
            if (Input.GetKey(key))
            {
                m_inputMap[buttonName] = true;
            }
        }
    }

    void UpdateTexture()
    {
        int offset = m_timeIndex*TextureSize;
        int i = 0;
        foreach (string s in m_strAxises)
        {
            int index = i + offset;
            float ratio = i / (float)TextureSize;
            string axisName = string.Format(s, (int)OuyaExampleCommon.Player);
            if (m_inputMap[axisName])
            {
                PrintPixel(index, new Color32(255, (byte)(ratio * 255), 0, 255));
            }
            else
            {
                PrintPixel(index, new Color32(0, 0, 0, 0));
            }
            i += 4;
        }
        foreach (string s in m_strButtons)
        {
            int index = i + offset;
            float ratio = i / (float)TextureSize;
            string buttonName = string.Format(s, (int)OuyaExampleCommon.Player);
            if (m_inputMap[buttonName])
            {
                PrintPixel(index, new Color32(0, (byte)(ratio * 255), 255, 255));
            }
            else
            {
                PrintPixel(index, new Color32(0, 0, 0, 0));
            }
            i += 4;
        }
    }

    void PrintPixel(int index, Color32 color)
    {
        m_pixels[index] = color;
        m_pixels[index+1] = color;
        m_pixels[index+2] = color;
        m_pixels[index+3] = color;
    }

    private DateTime m_inputTimer = DateTime.MinValue;

    public void Update()
    {
        if (m_inputTimer < DateTime.Now)
        {
            m_inputTimer = DateTime.Now + TimeSpan.FromMilliseconds(200);
            CheckForInput();

            UpdateTexture();
            m_timeIndex = (m_timeIndex + 1)%TextureSize;

            ClearInputMap();
        }

        ApplyTexture();
    }

    private DateTime m_renderTimer = DateTime.MinValue;

    public void ApplyTexture()
    {
        if (m_renderTimer < DateTime.Now)
        {
            m_renderTimer = DateTime.Now + TimeSpan.FromMilliseconds(100);
            if (m_texture)
            {
                m_texture.SetPixels32(m_pixels);
                m_texture.Apply();
            }

            if (PlotMaterial)
            {
                PlotMaterial.mainTextureOffset = new Vector2(0, m_timeIndex/(float) TextureSize);
            }
        }
    }
}


text:
namespace Melanchall.DryWetMidi.Core
{
    /// <summary>
    /// Specifies how reading engine should react on unexpected track chunks count. The default is
    /// <see cref="Ignore"/>.
    /// </summary>
    public enum UnexpectedTrackChunksCountPolicy
    {
        /// <summary>
        /// Ignore unexpected track chunks count.
        /// </summary>
        Ignore = 0,

        /// <summary>
        /// Abort reading and throw an <see cref="UnexpectedTrackChunksCountException"/>.
        /// </summary>
        Abort
    }
}


text:
package com.intellij.lexer;

import org.jetbrains.annotations.NotNull;

public abstract class LexerBase extends Lexer {
  @NotNull
  @Override
  public LexerPosition getCurrentPosition() {
    final int offset = getTokenStart();
    final int intState = getState();
    return new LexerPositionImpl(offset, intState);
  }

  @Override
  public void restore(@NotNull LexerPosition position) {
    start(getBufferSequence(), position.getOffset(), getBufferEnd(), position.getState());
  }
}


text:
I am a nav bar! I have 2 pages in total, but I am on page 1 now!

On page 1, I found a Happy Panda


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>https0x3A0x2F0x2Fgithub0x2Ecom0x2Ftangfeixiong0x2Fgo-to-kubernetes</groupId>
	<artifactId>console-k8s</artifactId>
 	<version>0.0.1-alpha</version>
	<packaging>pom</packaging>

	<name>Go to Kubernetes :: Console Project</name>
	<description>Console of Kubernetes and Cloud Native components.</description>

	<modules>
<!--		<module>hadoop-operator-client</module>
		<module>kafka-operator-component</module>
		<module>mysql-operator-component</module>
		<module>rabbitmq-operator-component</module>
		<module>redis-operator-component</module>-->
		<module>web-console</module>
	</modules>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>

		<spring-cloud-kubernetes.version>0.2.0.RELEASE</spring-cloud-kubernetes.version>
 		<spring-boot.version>2.0.0.RELEASE</spring-boot.version>

        <!-- The predefined properties in lifecycle -->
		<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
 		<maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
 		<maven-failsafe-plugin.version>2.20.1</maven-failsafe-plugin.version>
		<maven-resource-plugin.version>3.0.2</maven-resource-plugin.version>
 		<maven-surefire-plugin.version>2.20.1</maven-surefire-plugin.version>

	    <start-class>io.stackdocker.k8sconsoleproject.webconsole.App</start-class>
	</properties>

	<dependencyManagement>
		<dependencies>
		    <!-- https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-build-systems.html#using-boot-maven-without-a-parent -->
			<!-- Override Spring Data release train provided by Spring Boot -->
<!--			<dependency>
				<groupId>org.springframework.data</groupId>
				<artifactId>spring-data-releasetrain</artifactId>
				<version>Fowler-SR2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>-->
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies -->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>${spring-boot.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>

<!--			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-kubernetes</artifactId>
				<version>0.2.1.BUILD-SNAPSHOT</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-kubernetes-dependencies</artifactId>
				<version>${spring-cloud-kubernetes.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>-->
		</dependencies>
	</dependencyManagement>

    <repositories>
	    <!-- my synced -->
<!--        <repository>
            <id>my-synced</id>
            <url>http://172.17.4.50:8081/content/repositories/allsynced</url>
            <releases>
			    <enabled>true</enabled>
		    </releases>
            <snapshots>
			    <enabled>true</enabled>
			</snapshots>
        </repository>-->

	    <!-- inside China -->
	    <repository>
		    <id>aliyun</id>
			<name>aliyun</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public</url>
	    </repository>

       <!-- outside China -->
        <repository>
            <id>clojars</id>
            <name>clojars</name>
            <url>http://clojars.org/repo/</url>
        </repository>
<!--	    <repository>
		    <id>confluent</id>
			<name>confluent</name>
			<url>http://packages.confluent.io/maven/</url>
	    </repository>-->
		<repository>
		    <id>sonatype-snapshots</id>
			<name>sonatype-snapshots</name>
			<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
		</repository>
		<!-- https://repo.spring.io/webapp/#/home -->
	    <repository>
		    <id>spring-libs-milestone</id>
			<name>spring-libs-milestone</name>
			<url>https://repo.spring.io/libs-milestone</url>
	    </repository>
	    <repository>
            <snapshots>
              <enabled>false</enabled>
            </snapshots>
		    <id>spring-libs-release</id>
			<name>spring-libs-release</name>
			<url>https://repo.spring.io/libs-release</url>
	    </repository>
        <repository>
            <snapshots />
            <id>spring-libs-snapshot</id>
            <name>spring-libs-snapshot</name>
            <url>https://repo.spring.io/libs-snapshot</url>
        </repository>
<!--		<repository>
			<id>twitter4j</id>
			<url>http://twitter4j.org/maven2</url>
		</repository>-->
    </repositories>

	<pluginRepositories>
	    <!-- my synced -->
<!--        <pluginRepository>
            <id>my-synced</id>
            <url>http://172.17.4.50:8081/content/repositories/allsynced</url>
            <releases>
			    <enabled>true</enabled>
			</releases>
            <snapshots>
			    <enabled>true</enabled>
			</snapshots>
        </pluginRepository>-->

	    <pluginRepository>
		    <id>aliyun</id>
			<name>aliyun</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public</url>
	    </pluginRepository>

        <!-- https://repo.spring.io/webapp/#/home -->
        <pluginRepository>
            <snapshots>
              <enabled>false</enabled>
            </snapshots>
		    <id>spring-plugins-milestone</id>
			<name>spring-plugins-milestone</name>
			<url>https://repo.spring.io/plugins-milestone</url>
	    </pluginRepository>
        <pluginRepository>
		    <snapshots />
		    <id>spring-plugins-snapshot</id>
			<name>spring-plugins-snapshot</name>
			<url>https://repo.spring.io/plugins-snapshot</url>
	    </pluginRepository>
   </pluginRepositories>

<!--	<distributionManagement>
	    <repository>
	        <id>my-releases</id>
	        <name>My internal repository</name>
	        <url>http://172.17.4.50:8081/content/repositories/releases</url>
	    </repository>
	    <snapshotRepository>
	        <id>my-snapshots</id>
	        <name>My internal repository</name>
	        <url>http://172.17.4.50:8081/content/repositories/snapshots</url>
	    </snapshotRepository>
	</distributionManagement>-->

	<build>
	  <!-- To define the plugin version in your parent POM -->
	  <pluginManagement>
	    <plugins>
	      <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
	        <artifactId>maven-compiler-plugin</artifactId>
	        <version>${maven-compiler-plugin.version}</version>
	        <configuration>
	          <source>1.8</source>
	          <target>1.8</target>
	        </configuration>
	      </plugin>
	      <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
	        <artifactId>maven-resources-plugin</artifactId>
	        <version>${maven-resource-plugin.version}</version>
	      </plugin>

			<!--<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>${spring-boot.version}</version>
		        <configuration>
		            <mainClass>${start-class}</mainClass>
					<layout>JAR</layout>
		        </configuration>
				<executions>
					<execution>
						<id>generate build info</id>
						<goals>
							<goal>build-info</goal>
						</goals>
					</execution>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>-->
	    </plugins>
	  </pluginManagement>
	</build>

</project>


text:
import tempfile
import unittest
from pathlib import Path

from bwapi.credentials import CredentialsStore

ACCESS_TOKEN = "00000000-0000-0000-0000-000000000000"

class TestCredentialsStore(unittest.TestCase):
    def with_credential_store(function):
        def wrapper(self):
            with tempfile.TemporaryDirectory() as temp_dir:
                token_path = Path(temp_dir) / "tokens.txt"
                store = CredentialsStore(credentials_path=token_path)
                function(self, store)

        return wrapper

    @with_credential_store
    def test_file_created_on_read(self, store):
        self.assertFalse(store._credentials_path.exists())

        _ = [c for c in store]

        self.assertTrue(store._credentials_path.exists())

    @with_credential_store
    def test_file_created_on_write(self, store):
        self.assertFalse(store._credentials_path.exists())

        store["example@example.com"] = ACCESS_TOKEN

        self.assertTrue(store._credentials_path.exists())

    @with_credential_store
    def test_store(self, store):
        self.assertEqual(len(store), 0)

        store["example@example.com"] = ACCESS_TOKEN

        self.assertEqual(store["example@example.com"], ACCESS_TOKEN)
        self.assertEqual(len(store), 1)

    @with_credential_store
    def test_store_multiple(self, store):
        self.assertEqual(len(store), 0)

        store["example@example.com"] = "10000000-0000-0000-0000-000000000000"
        store["another-example@example.com"] = "20000000-0000-0000-0000-000000000000"

        self.assertEqual(
            store["example@example.com"], "10000000-0000-0000-0000-000000000000"
        )
        self.assertEqual(
            store["another-example@example.com"], "20000000-0000-0000-0000-000000000000"
        )
        self.assertEqual(len(store), 2)

    @with_credential_store
    def test_store_overwrite(self, store):
        self.assertEqual(len(store), 0)

        store["example@example.com"] = "10000000-0000-0000-0000-000000000000"
        store["example@example.com"] = "20000000-0000-0000-0000-000000000000"

        self.assertEqual(
            store["example@example.com"], "20000000-0000-0000-0000-000000000000"
        )

    @with_credential_store
    def test_store_same(self, store):
        self.assertEqual(len(store), 0)

        store["example@example.com"] = ACCESS_TOKEN
        store["example@example.com"] = ACCESS_TOKEN

        self.assertEqual(store["example@example.com"], ACCESS_TOKEN)

    @with_credential_store
    def test_store_case_insensitive(self, store):
        store["example@example.com"] = ACCESS_TOKEN
        store["EXAMPLE@EXAMPLE.COM"] = ACCESS_TOKEN
        store["eXaMpLe@ExAmPlE.cOm"] = ACCESS_TOKEN
        self.assertEqual(len(store), 1)

    @with_credential_store
    def test_store_lower(self, store):
        store["example@example.com"] = ACCESS_TOKEN
        self.assertEqual(store["example@example.com"], ACCESS_TOKEN)

    @with_credential_store
    def test_store_upper(self, store):
        store["EXAMPLE@EXAMPLE.COM"] = ACCESS_TOKEN
        self.assertEqual(store["example@example.com"], ACCESS_TOKEN)

    @with_credential_store
    def test_store_mixed(self, store):
        store["eXaMpLe@ExAmPlE.cOm"] = ACCESS_TOKEN
        self.assertEqual(store["example@example.com"], ACCESS_TOKEN)

    @with_credential_store
    def test_get_lower(self, store):
        store["example@example.com"] = ACCESS_TOKEN
        self.assertEqual(store["example@example.com"], ACCESS_TOKEN)

    @with_credential_store
    def test_get_upper(self, store):
        store["example@example.com"] = ACCESS_TOKEN
        self.assertEqual(store["EXAMPLE@EXAMPLE.COM"], ACCESS_TOKEN)

    @with_credential_store
    def test_get_mixed(self, store):
        store["example@example.com"] = ACCESS_TOKEN
        self.assertEqual(store["eXaMpLe@ExAmPlE.cOm"], ACCESS_TOKEN)


text:
class RAK_DLL_EXPORT ThreadsafePacketLogger : public PacketLogger
{
public:
	ThreadsafePacketLogger();
	virtual ~ThreadsafePacketLogger();

	virtual void Update(void);

protected:
	virtual void AddToLog(const char *str);

	DataStructures::SingleProducerConsumer<char*> logMessages;
};

#endif

#endif // _RAKNET_SUPPORT_*


text:
package org.elasticsearch.xpack.ml.action;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.delete.DeleteAction;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.ParentTaskAssigningClient;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.AbstractBulkByScrollRequest;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.persistent.PersistentTasksCustomMetadata;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.ml.MlStatsIndex;
import org.elasticsearch.xpack.core.ml.MlTasks;
import org.elasticsearch.xpack.core.ml.action.DeleteDataFrameAnalyticsAction;
import org.elasticsearch.xpack.core.ml.action.StopDataFrameAnalyticsAction;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsState;
import org.elasticsearch.xpack.core.ml.dataframe.stats.Fields;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndex;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.dataframe.StoredProgress;
import org.elasticsearch.xpack.ml.dataframe.persistence.DataFrameAnalyticsConfigProvider;
import org.elasticsearch.xpack.ml.notifications.DataFrameAnalyticsAuditor;
import org.elasticsearch.xpack.ml.process.MlMemoryTracker;
import org.elasticsearch.xpack.ml.utils.MlIndicesUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.elasticsearch.xpack.core.ClientHelper.ML_ORIGIN;
import static org.elasticsearch.xpack.core.ClientHelper.executeAsyncWithOrigin;

/**
 * The action is a master node action to ensure it reads an up-to-date cluster
 * state in order to determine whether there is a persistent task for the analytics
 * to delete.
 */
public class TransportDeleteDataFrameAnalyticsAction
    extends TransportMasterNodeAction<DeleteDataFrameAnalyticsAction.Request, AcknowledgedResponse> {

    private static final Logger logger = LogManager.getLogger(TransportDeleteDataFrameAnalyticsAction.class);

    private final Client client;
    private final MlMemoryTracker memoryTracker;
    private final DataFrameAnalyticsConfigProvider configProvider;
    private final DataFrameAnalyticsAuditor auditor;

    @Inject
    public TransportDeleteDataFrameAnalyticsAction(TransportService transportService, ClusterService clusterService,
                                                   ThreadPool threadPool, ActionFilters actionFilters,
                                                   IndexNameExpressionResolver indexNameExpressionResolver, Client client,
                                                   MlMemoryTracker memoryTracker, DataFrameAnalyticsConfigProvider configProvider,
                                                   DataFrameAnalyticsAuditor auditor) {
        super(DeleteDataFrameAnalyticsAction.NAME, transportService, clusterService, threadPool, actionFilters,
            DeleteDataFrameAnalyticsAction.Request::new, indexNameExpressionResolver);
        this.client = client;
        this.memoryTracker = memoryTracker;
        this.configProvider = configProvider;
        this.auditor = Objects.requireNonNull(auditor);
    }

    @Override
    protected String executor() {
        return ThreadPool.Names.SAME;
    }

    @Override
    protected AcknowledgedResponse read(StreamInput in) throws IOException {
        return new AcknowledgedResponse(in);
    }

    @Override
    protected void masterOperation(Task task, DeleteDataFrameAnalyticsAction.Request request, ClusterState state,
                                   ActionListener<AcknowledgedResponse> listener) {
        TaskId taskId = new TaskId(clusterService.localNode().getId(), task.getId());
        ParentTaskAssigningClient parentTaskClient = new ParentTaskAssigningClient(client, taskId);

        if (request.isForce()) {
            forceDelete(parentTaskClient, request, listener);
        } else {
            normalDelete(parentTaskClient, state, request, listener);
        }
    }

    private void forceDelete(ParentTaskAssigningClient parentTaskClient, DeleteDataFrameAnalyticsAction.Request request,
                             ActionListener<AcknowledgedResponse> listener) {
        logger.debug("[{}] Force deleting data frame analytics job", request.getId());

        ActionListener<StopDataFrameAnalyticsAction.Response> stopListener = ActionListener.wrap(
            stopResponse -> normalDelete(parentTaskClient, clusterService.state(), request, listener),
            listener::onFailure
        );

        stopJob(parentTaskClient, request, stopListener);
    }

    private void stopJob(ParentTaskAssigningClient parentTaskClient, DeleteDataFrameAnalyticsAction.Request request,
                         ActionListener<StopDataFrameAnalyticsAction.Response> listener) {
        // We first try to stop the job normally. Normal stop returns after the job was stopped.
        // If that fails then we proceed to force stopping which returns as soon as the persistent task is removed.
        // If we just did force stopping, then there is a chance we proceed to delete the config while it's
        // still used from the running task which results in logging errors.

        StopDataFrameAnalyticsAction.Request stopRequest = new StopDataFrameAnalyticsAction.Request(request.getId());
        stopRequest.setTimeout(request.timeout());

        ActionListener<StopDataFrameAnalyticsAction.Response> normalStopListener = ActionListener.wrap(
            listener::onResponse,
            normalStopFailure -> {
                stopRequest.setForce(true);
                executeAsyncWithOrigin(parentTaskClient, ML_ORIGIN, StopDataFrameAnalyticsAction.INSTANCE, stopRequest, ActionListener.wrap(
                    listener::onResponse,
                    forceStopFailure -> {
                        logger.error(new ParameterizedMessage("[{}] Failed to stop normally", request.getId()), normalStopFailure);
                        logger.error(new ParameterizedMessage("[{}] Failed to stop forcefully", request.getId()), forceStopFailure);
                        listener.onFailure(forceStopFailure);
                    }
                ));
            }
        );

        executeAsyncWithOrigin(parentTaskClient, ML_ORIGIN, StopDataFrameAnalyticsAction.INSTANCE, stopRequest, normalStopListener);
    }

    private void normalDelete(ParentTaskAssigningClient parentTaskClient, ClusterState state,
                              DeleteDataFrameAnalyticsAction.Request request, ActionListener<AcknowledgedResponse> listener) {
        String id = request.getId();
        PersistentTasksCustomMetadata tasks = state.getMetadata().custom(PersistentTasksCustomMetadata.TYPE);
        DataFrameAnalyticsState taskState = MlTasks.getDataFrameAnalyticsState(id, tasks);
        if (taskState != DataFrameAnalyticsState.STOPPED) {
            listener.onFailure(ExceptionsHelper.conflictStatusException("Cannot delete data frame analytics [{}] while its status is [{}]",
                id, taskState));
            return;
        }

        // We clean up the memory tracker on delete because there is no stop; the task stops by itself
        memoryTracker.removeDataFrameAnalyticsJob(id);

        // Step 4. Delete the config
        ActionListener<BulkByScrollResponse> deleteStatsHandler = ActionListener.wrap(
            bulkByScrollResponse -> {
                if (bulkByScrollResponse.isTimedOut()) {
                    logger.warn("[{}] DeleteByQuery for stats timed out", id);
                }
                if (bulkByScrollResponse.getBulkFailures().isEmpty() == false) {
                    logger.warn("[{}] {} failures and {} conflicts encountered while running DeleteByQuery for stats", id,
                        bulkByScrollResponse.getBulkFailures().size(), bulkByScrollResponse.getVersionConflicts());
                    for (BulkItemResponse.Failure failure : bulkByScrollResponse.getBulkFailures()) {
                        logger.warn("[{}] DBQ failure: {}", id, failure);
                    }
                }
                deleteConfig(parentTaskClient, id, listener);
            },
            listener::onFailure
        );

        // Step 3. Delete job docs from stats index
        ActionListener<BulkByScrollResponse> deleteStateHandler = ActionListener.wrap(
            bulkByScrollResponse -> {
                if (bulkByScrollResponse.isTimedOut()) {
                    logger.warn("[{}] DeleteByQuery for state timed out", id);
                }
                if (bulkByScrollResponse.getBulkFailures().isEmpty() == false) {
                    logger.warn("[{}] {} failures and {} conflicts encountered while running DeleteByQuery for state", id,
                        bulkByScrollResponse.getBulkFailures().size(), bulkByScrollResponse.getVersionConflicts());
                    for (BulkItemResponse.Failure failure : bulkByScrollResponse.getBulkFailures()) {
                        logger.warn("[{}] DBQ failure: {}", id, failure);
                    }
                }
                deleteStats(parentTaskClient, id, request.timeout(), deleteStatsHandler);
            },
            listener::onFailure
        );

        // Step 2. Delete state
        ActionListener<DataFrameAnalyticsConfig> configListener = ActionListener.wrap(
            config -> deleteState(parentTaskClient, config, request.timeout(), deleteStateHandler),
            listener::onFailure
        );

        // Step 1. Get the config to check if it exists
        configProvider.get(id, configListener);
    }

    private void deleteConfig(ParentTaskAssigningClient parentTaskClient, String id, ActionListener<AcknowledgedResponse> listener) {
        DeleteRequest deleteRequest = new DeleteRequest(AnomalyDetectorsIndex.configIndexName());
        deleteRequest.id(DataFrameAnalyticsConfig.documentId(id));
        deleteRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        executeAsyncWithOrigin(parentTaskClient, ML_ORIGIN, DeleteAction.INSTANCE, deleteRequest, ActionListener.wrap(
            deleteResponse -> {
                if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
                    listener.onFailure(ExceptionsHelper.missingDataFrameAnalytics(id));
                    return;
                }
                assert deleteResponse.getResult() == DocWriteResponse.Result.DELETED;
                logger.info("[{}] Deleted", id);
                auditor.info(id, Messages.DATA_FRAME_ANALYTICS_AUDIT_DELETED);
                listener.onResponse(new AcknowledgedResponse(true));
            },
            listener::onFailure
        ));
    }

    private void deleteState(ParentTaskAssigningClient parentTaskClient,
                             DataFrameAnalyticsConfig config,
                             TimeValue timeout,
                             ActionListener<BulkByScrollResponse> listener) {
        List<String> ids = new ArrayList<>();
        ids.add(StoredProgress.documentId(config.getId()));
        if (config.getAnalysis().persistsState()) {
            ids.add(config.getAnalysis().getStateDocId(config.getId()));
        }
        executeDeleteByQuery(
            parentTaskClient,
            AnomalyDetectorsIndex.jobStateIndexPattern(),
            QueryBuilders.idsQuery().addIds(ids.toArray(String[]::new)),
            timeout,
            listener
        );
    }

    private void deleteStats(ParentTaskAssigningClient parentTaskClient,
                             String jobId,
                             TimeValue timeout,
                             ActionListener<BulkByScrollResponse> listener) {
        executeDeleteByQuery(
            parentTaskClient,
            MlStatsIndex.indexPattern(),
            QueryBuilders.termQuery(Fields.JOB_ID.getPreferredName(), jobId),
            timeout,
            listener
        );
    }

    private void executeDeleteByQuery(ParentTaskAssigningClient parentTaskClient, String index, QueryBuilder query, TimeValue timeout,
                                      ActionListener<BulkByScrollResponse> listener) {
        DeleteByQueryRequest request = new DeleteByQueryRequest(index);
        request.setQuery(query);
        request.setIndicesOptions(MlIndicesUtils.addIgnoreUnavailable(IndicesOptions.lenientExpandOpen()));
        request.setSlices(AbstractBulkByScrollRequest.AUTO_SLICES);
        request.setAbortOnVersionConflict(false);
        request.setRefresh(true);
        request.setTimeout(timeout);
        executeAsyncWithOrigin(parentTaskClient, ML_ORIGIN, DeleteByQueryAction.INSTANCE, request, listener);
    }

    @Override
    protected ClusterBlockException checkBlock(DeleteDataFrameAnalyticsAction.Request request, ClusterState state) {
        return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
    }
}