text:
define(function (require, exports) {
    "use strict";

    var PlayObject = require("../playObject"),
        referenceBy = require("./reference").wrapper("document"),
        referenceOf = require("./reference").refersTo,
        unitsIn = require("./unit"),
        assert = require("../util").assert,
        _ = require("lodash");

    /**
     * Open a document (psd, png, jpg, ai, gif)
     *
     * @param {ActionDescriptor} sourceRef document reference
     * @param {string} settings.pdfSelection "page" or "image"
     * @param {number} settings.pageNumber The number of the page
     * @param {boolean} settings.suppressWarnings true or false
     * @param {string} settings.name The name of the Document.
     * @param {number} settings.bitDepth The bit depth. 8 or 16
     * @param {string} settings.box Box to crop to. See openDocument.cropTo vals
     * @param {boolean} settings.bAntiAlias true or false
     * @param {boolean} settings.bConstrainProportions true or false
     * @param {number} settings.width The width of the image size.
     * @param {number} settings.height The height of the image size
     * @param {string} settings.colorSpace The color space of the image mode.  See openDocument.mode vals
     * @param {number} settings.resolution The resolution value
     *
     * @return {PlayObject}
     *
     */
    var openDocument = function (sourceRef, settings) {
        var params = {
                pdfSelection: settings.pdfSelection || "page",
                pageNumber: settings.pageNumber || 1,
                suppressWarnings: settings.suppressWarnings || false,
                name: settings.name || sourceRef.name,
                bitDepth: settings.bitDepth || 8,
                box: settings.box || "boundingBox",
                bAntiAlias: settings.bAntiAlias || true,
                bConstrainProportions: settings.bConstrainProportions || true,
                width: settings.width || sourceRef.width,
                height: settings.height || sourceRef.height,
                colorSpace: settings.colorSpace || "RGBColorMode",
                resolution: settings.resolution
            },
            fileType,
            strIndex = sourceRef._path.lastIndexOf(".");

        if (strIndex !== -1) {
            strIndex++;
            fileType = sourceRef._path.substring(strIndex);
        }

        var desc = {
            "null": sourceRef
        };

        if (fileType === "ai") {
            desc.as._obj = "PDFGenericFormat";
            desc.as._value.selection = {
                "_enum": "pdfSelection",
                "_value": params.pdfSelection
            };
            desc.as._value.suppressWarnings = params.suppressWarnings;
            desc.as._value.pageNumber = params.pageNumber;
            if (params.pdfSelection === "page") {
                desc.as._value = {
                    "antiAlias": params.bAntiAlias,
                    "constrainProportions": params.bConstrainProportions,
                    "crop": {
                        "_enum": "cropTo",
                        "_value": openDocument.cropTo[params.box]
                    },
                    "depth": params.bitDepth,
                    "width": unitsIn.pixels(params.width),
                    "height": unitsIn.pixels(params.height),
                    "mode": {
                        "_enum": "colorSpace",
                        "_value": openDocument.mode[params.colorSpace]
                    },
                    "name": params.name,
                    "resolution": unitsIn.density(params.resolution)
                };
            }
        }

        return new PlayObject(
            "open",
            desc
        );
    };

    openDocument.cropTo = {
        bounding: "boundingBox",
        media: "mediaBox",
        crop: "cropBox",
        bleed: "bleedBox",
        trim: "trimBox",
        art: "artBox"
    };

    openDocument.mode = {
        rgb: "RGBColorMode",
        gray: "grayscaleMode",
        cmyk: "CMYKColorMode",
        lab: "labColorMode"
    };

    /**
     * Close a document without saving
     *
     * @param {number} documentID
     * @param {string=} save Whether the document should be saved. "yes", "no"
     * @return {PlayObject}
     *
     * Preconditions:
     * The document should be saved previously and have fileReference path value for saving.
     */
    var closeDocument = function (documentID, save) {
        var desc = {
            documentID: documentID
        };

        if (save) {
            desc.saving = {
                "_enum": "yesNo",
                "_value": save
            };
        }

        return new PlayObject(
            "close",
            desc
        );
    };

    /**
     * Save a document
     *
     * @param {string} path The full path to save a file.
     * @param {!Object} settings An object with params
     * @param {string} settings.gifColorPalette GIF color palette. See saveDocument.gifColorPalette
     * @param {string} settings.gifForcedColors GIF forced color. See saveDocument.gifForcedColors
     * @param {boolean} settings.gitTransparency GIF Transparency
     * @param {string} settings.gifRowOrder GIF Format Option.  normal or interlaced
     * @param {number} settings.jpgExtendedQuality JPG Quality. 0 to 10
     * @param {string} settings.jpgFormatOptions JPG Format Option. standard, optimized, or progressive
     * @param {number} settings.jpgProgressiveScans The number of Scans. 3 to 5
     * @param {number} settings.pngCompression PNG compression. none or smallest
     * @param {number} settings.pngInterlace PNG interlace. none or interlaced

     * @param {boolean} settings.embedProfiles Whether embed color profile
     *
     * @return {PlayObject}
     */
    var saveDocument = function (path, settings) {
        var strIndex = path.lastIndexOf("."),
            pathIndex = path.lastIndexOf("/"),
            fileType,
            fileName,
            filePath,
            desc,
            saveAs = {},
            saveTo = {},
            params = {
                gifColorPalette: settings.gifColorPalette || "exact",
                gifRowOrder: settings.gifRowOrder || "normal",
                gifForcedColors: settings.gifForcedColors || "blackAndWhite",
                gitTransparency: settings.gitTransparency || true,
                jpgExtendedQuality: settings.jpgExtendedQuality || 8,
                jpgFormatOptions: settings.jpgFormatOptions || "standard",
                jpgProgressiveScans: settings.jpgProgressiveScans || 3,
                pngCompression: settings.pngCompression,
                pngInterlace: settings.pngInterlace,
                embedProfiles: settings.embedProfiles || false
            };
        if (strIndex !== -1) {
            strIndex++;
            fileType = path.substring(strIndex);
        }
        if (pathIndex !== -1) {
            pathIndex++;
            fileName = path.substring(pathIndex);
        }
        filePath = path.replace(fileName, "");

        if (fileType === "gif") {
            saveAs = {
                "_obj": "GIFFormat",
                "_value": {
                    "interfaceIconFrameDimmed": saveDocument.gifRowOrder[params.gifRowOrder]
                }
            };
            saveTo = {
                "_obj": "indexedColorMode",
                "_value": {
                    "palette": {
                        "_enum": "colorPalette",
                        "_value": saveDocument.gifColorPalette[params.gifColorPalette]
                    },
                    "forcedColors": {
                        "_enum": "forcedColors",
                        "_value": saveDocument.gifForcedColors[params.gifForcedColors]
                    },
                    "transparency": params.gitTransparency
                }
            };
        } else if (fileType === "psd") {
            saveAs = {
                "_obj": "photoshop35Format",
                "_value": {}
            };
        } else if (fileType === "jpg") {
            saveAs = {
                "_obj": "JPEG",
                "_value": {
                    "extendedQuality": params.jpgExtendedQuality,
                    "matteColor": {
                        "_enum": "matteColor",
                        "_value": "none"
                    }
                }
            };
        } else if (fileType === "png") {
            saveAs = {
                "_obj": "PNGFormat",
                "_value": {
                    "PNGInterlaceType": {
                        "_enum": "PNGInterlaceType",
                        "_value": saveDocument.pngInterlace[params.pngInterlace]
                    },
                    "compression": saveDocument.pngCompression[params.pngCompression]
                }
            };
        }
        desc = {
            "as": saveAs,
            "in": {
                "_path": path
            }
        };
        if (fileType === "gif") {
            desc.to = saveTo;
            desc.copy = true;
        } else {
            desc.embedProfiles = params.embedProfiles;
        }
        return new PlayObject(
            "make",
            desc
        );
    };
    saveDocument.pngCompression = {
        none: 0,
        smallest: 9
    };
    saveDocument.pngInterlace = {
        none: "PNGInterlaceNone",
        interlaced: "PNGInterlaceAdam7"
    };
    saveDocument.gifColorPalette = {
        exact: "exact",
        mac: "macintoshSystem",
        window: "windowsSystem",
        web: "web",
        localPerceptual: "perceptual",
        localSelective: "selective",
        localAdaptive: "adaptive",
        previous: "previous"
    };
    saveDocument.gifRowOrder = {
        normal: false,
        interlaced: true
    };
    saveDocument.gifForcedColors = {
        none: "none",
        blackAndWhite: "blackAndWhite",
        primaries: "primaries",
        web: "web"
    };

    /**
     * Select a document
     *
     * @param {ActionDescriptor} sourceRef document reference
     *
     * @return {PlayObject}
     *
     */
    var selectDocument = function (sourceRef) {
        assert(referenceOf(sourceRef) === "document", "selectDocument is passed a non-document reference");

        var desc = {
            "null": sourceRef
        };
        return new PlayObject(
            "select",
            desc
        );
    };

    /**
     * Return a document path to be used for opening or saving a document.
     *
     * @param {string} path document path
     *
     * @return {PlayObject}
     *
     */
    referenceBy.path = function (path) {
        return {
            descriptor: {
                "null": path
            }
        };
    };

    /**
     * Create a document
     *
     * @param {number} settings.width The document width.
     * @param {number} settings.height The document height.
     * @param {number} settings.resolution The document resolution.
     * @param {string} settings.fill The document fill. "white", "backgroundColor", "transparency"
     * @param {string} settings.colorMode The document color mode. "RGBColorMode", "bitmapMode", "grayscaleMode"
                        "CMYKColorMode", "labColorMode"
     * @param {number} settings.depth The color mode depth
     * @param {string} settings.colorProfile The document color profile. "sRGB IEC61966-2.1", "Adobe RGB (1998)",
     *  default: "none"
     * @param {string} settings.pixelAspectRatio The document pixel aspect ratio.
     *
     * @return {PlayObject}
     *
     */
    var createDocument = function (settings) {
        var params = {
            width: settings.width || 7,
            height: settings.width || 5,
            resolution: settings.resolution || 72,
            fill: settings.fill || "white",
            colorMode: settings.colorMode || "RGBColorMode",
            depth: settings.depth || 8,
            colorProfile: settings.colorProfile || "none",
            pixelAspectRatio: settings.pixelAspectRatio || 1
        };

        var newObj = {
            "_obj": "document",
            "_value": {
                "width": unitsIn.distance(params.width),
                "height": unitsIn.distance(params.height),
                "resolution": unitsIn.density(params.resolution),
                "fill": {
                    "_enum": "fill",
                    "_value": params.fill
                },
                "mode": {
                    "_class": params.colorMode
                },
                "depth": params.depth,
                "profile": params.colorProfile,
                "pixelScaleFactor": params.pixelAspectRatio
            }
        };

        var desc = {
            "new": newObj
        };

        return new PlayObject(
            "make",
            desc
        );
    };

    /**
     * Create a document using a simple preset string identifier
     *
     * @param {string} presetName identifier of the preset
     * @return {PlayObject}
     */
    var createWithPreset = function (presetName) {
        var desc = {
                "new": {
                    "_obj": "document",
                    "_value": {
                        preset: presetName
                    }
                }
            };
        return new PlayObject(
            "make",
            desc
        );
    };

    /**
     * Resizes the canvas of current document
     *
     * @param {Unit} width Width in units
     * @param {Unit} height Height in units
     * @param {string} horizontalExtension option to stretch the canvas horizontally, default center
     * @param {string} verticalExtension option to strecth canvas vertically, default center
     *
     * @returns {PlayObject}
     */
    var resizeDocument = function (width, height, horizontalExtension, verticalExtension) {
        horizontalExtension = horizontalExtension || "center";
        verticalExtension = verticalExtension || "center";

        return new PlayObject(
            "canvasSize",
            {
                "canvasExtensionColorType": {
                    "_enum": "canvasExtensionColorType",
                    "_value": "backgroundColor"
                },
                "height": height,
                "width": width,
                "horizontal": {
                    "_enum": "horizontalLocation",
                    "_value": horizontalExtension
                },
                "vertical": {
                    "_enum": "verticalLocation",
                    "_value": verticalExtension
                }
            }
        );
    };

    /**
     * Set the Target Path property of the document. This is available in
     * the classic UI menu as View > Extras..Show > Target Path
     *
     * @param {object} sourceRef
     * @param {boolean} enabled
     * @return {PlayObject}
     */
    var setTargetPathVisible = function (sourceRef, enabled) {
        assert(referenceOf(sourceRef) === "document", "setTargetPathVisible is passed a non-document reference");

        var reference = {
            "_ref": [
                {
                    "_ref": "property",
                    "_property": "targetPathVisibility"
                },
                sourceRef
            ]
        };

        var descriptor = {
            null: reference,
            to: enabled
        };

        return new PlayObject("set", descriptor);
    };

    /**
     * Creates a guide in the given position with given orientation in the document
     *
     * @param {object} sourceRef
     * @param {"horizontal"|"vertical"} orientation Guide orientation
     * @param {number} position Position of guide in pixels
     * @param {boolean} isArtboardGuide If true, the guide will be created as an artboard guide
     * @return {PlayObject}
     */
    var insertGuide = function (sourceRef, orientation, position, isArtboardGuide) {
        assert(referenceOf(sourceRef) === "document", "insertGuide is passed a non-document reference");

        var reference = {
                "_ref": "guide"
            },
            guideReference = {
                "_ref": [
                    sourceRef,
                    { "_class": "guide" }
                ]
            };

        var descriptor = {
            null: reference,
            new: {
                "_obj": "guide",
                "null": guideReference,
                "orientation": {
                    "_enum": "orientation",
                    "_value": orientation
                },
                "position": unitsIn.pixels(position)
            },
            "guideTarget": {
                "_enum": "guideTarget",
                "_value": isArtboardGuide ? "guideTargetSelectedArtboard" : "guideTargetDocument"
            }
        };

        return new PlayObject("newGuide", descriptor);
    };

    /**
     * Deletes the guide in the given position in the document
     *
     * @param {object} sourceRef
     * @param {number} guideIndex Index of guide in the document
     * @return {PlayObject}
     */
    var removeGuide = function (sourceRef, guideIndex) {
        assert(referenceOf(sourceRef) === "document", "removeGuide is passed a non-document reference");

        var descriptor = {
            null: {
                "_ref": [
                    {
                        "_ref": "guide",
                        "_index": guideIndex
                    },
                    sourceRef
                ]
            }
        };

        return new PlayObject("delete", descriptor);
    };

    /**
     * Sets the artboard auto properties, given they're provided
     * This is available in the classic UI when artboard tool is selected under the gear icon.
     *
     * @param {object} sourceRef
     * @param {object} attributes
     * @param {?boolean} attributes.autoNestEnabled When layers are moved, they will be automatically nested
     *                                              into the artboard they're over
     * @param {?boolean} attributes.autoPositionEnabled When a layer being reordered into an artboard
     *                                                  will be moved to be inside the artboard
     * @param {?boolean} attributes.autoExpandEnabled When artboards are moved, if they go outside the canvas
     *                                                it will be automatically expanded to fit everything
     * @return {PlayObject}
     */
    var setArtboardAutoAttributes = function (sourceRef, attributes) {
        assert(referenceOf(sourceRef) === "document", "setArtboardAutoAttributes is passed a non-document reference");
        assert(attributes !== {}, "setArtboardAutoAttributes requires at least one attribute");

        var reference = {
            "_ref": [
                {
                    "_ref": "property",
                    "_property": "artboards"
                },
                sourceRef
            ]
        };

        var descriptor = {
            null: reference,
            to: attributes
        };

        return new PlayObject("set", descriptor);
    };

    /**
     * Build the base descriptor for guide visibility
     *
     * @private
     * @param {string} guideType either "guidesVisibility" or "smartGuidesVisibility"
     * @return {PlayObject}
     */
    var _buildGuidesDescriptor = function (guideType) {
        return {
            "null": {
                "_ref": [{
                    "_ref": "property",
                    "_property": guideType
                }, {
                    "_ref": "document",
                    "_enum": "ordinal",
                    "_value": "targetEnum"
                }]
            }
        };
    };

    /**
     * Guide Visibility descriptors (regular and smart)
     *
     * @private
     * @type {PlayObject}
     */
    var _guidesDescriptor = _buildGuidesDescriptor("guidesVisibility"),
        _smartGuidesDescriptor = _buildGuidesDescriptor("smartGuidesVisibility");

    /**
     * Generate a PlayObject to get the visibility of Guides for the current document
     *
     * @return {PlayObject}
     */
    var getGuidesVisibility = function () {
        return new PlayObject("get", _guidesDescriptor);
    };

    /**
     * Generate a PlayObject to get the visibility of Smart Guides for the current document
     *
     * @return {PlayObject}
     */
    var getSmartGuidesVisibility = function () {
        return new PlayObject("get", _smartGuidesDescriptor);
    };

    /**
     * Generate a PlayObject to set the visibility of Guides for the current document
     *
     * @param {boolean} enabled
     * @return {PlayObject}
     */
    var setGuidesVisibility = function (enabled) {
        var setter = _.clone(_guidesDescriptor);
        setter.to = enabled;
        return new PlayObject("set", setter);
    };

    /**
     * Generate a PlayObject to set the visibility of Smart Guides for the current document
     *
     * @param {boolean} enabled
     * @return {PlayObject}
     */
    var setSmartGuidesVisibility = function (enabled) {
        var setter = _.clone(_smartGuidesDescriptor);
        setter.to = enabled;
        return new PlayObject("set", setter);
    };

    /**
     * build a reference for documentExtensionData
     *
     * @private
     * @param {number|object} docRef either a document ID or a document reference
     * @param {string} namespace top-level property within the documentExtensionData object
     * @return {object}
     */
    var _extensionDataReference = function (docRef, namespace) {
        var _docRef;

        if (Number.isFinite(docRef)) {
            _docRef = referenceBy.id(docRef);
        } else {
            _docRef = docRef;
        }

        return {
            _ref: [
                {
                    _ref: null,
                    _property: namespace
                },
                {
                    _ref: null,
                    _property: "documentExtensionData"
                },
                _docRef
            ]
        };
    };

    /**
     * Build a PlayObject to get all extension data within a namespace (top-level property)
     *
     * @param {number|object} docRef either a document ID or a document reference
     * @param {string} namespace top-level property within the documentExtensionData Object
     * @return {PlayObject}
     */
    var getExtensionData = function (docRef, namespace) {
        return new PlayObject("get", { "null": _extensionDataReference(docRef, namespace) });
    };

    /**
     * Build a PlayObject to set a single key/value pair within the given Extension Data namespace
     *
     * @param {number|object} docRef either a document ID or a document reference
     * @param {string} namespace top-level property within the documentExtensionData object
     * @param {string} key sub-property name
     * @param {string} value
     * @return {PlayObject}
     */
    var setExtensionData = function (docRef, namespace, key, value) {
        var to = {};
        to[key] = value;

        return new PlayObject("set", {
            "null": _extensionDataReference(docRef, namespace),
            "to": to
        });
    };

    exports.referenceBy = referenceBy;

    exports.open = openDocument;
    exports.close = closeDocument;
    exports.save = saveDocument;
    exports.select = selectDocument;
    exports.create = createDocument;
    exports.createWithPreset = createWithPreset;
    exports.resize = resizeDocument;
    exports.insertGuide = insertGuide;
    exports.removeGuide = removeGuide;
    exports.setArtboardAutoAttributes = setArtboardAutoAttributes;
    exports.setTargetPathVisible = setTargetPathVisible;
    exports.getGuidesVisibility = getGuidesVisibility;
    exports.getSmartGuidesVisibility = getSmartGuidesVisibility;
    exports.setGuidesVisibility = setGuidesVisibility;
    exports.setSmartGuidesVisibility = setSmartGuidesVisibility;
    exports.getExtensionData = getExtensionData;
    exports.setExtensionData = setExtensionData;
});


text:
<?php

/**
 * Admin selectlist list manager.
 */
class oxAdminList extends oxAdminView
{

    /**
     * Name of chosen object class (default null).
     *
     * @var string
     */
    protected $_sListClass = null;

    /**
     * Type of list.
     *
     * @var string
     */
    protected $_sListType = 'oxlist';

    /**
     * List of objects (default null).
     *
     * @var object
     */
    protected $_oList = null;

    /**
     * Position in list of objects (default 0).
     *
     * @var integer
     */
    protected $_iCurrListPos = 0;

    /**
     * Size of object list (default 0).
     *
     * @var integer
     */
    protected $_iListSize = 0;

    /**
     * Array of SQL query conditions (default null).
     *
     * @var array
     */
    protected $_aWhere = null;

    /**
     * Enable/disable sorting by DESC (SQL) (default false - disable).
     *
     * @var bool
     */
    protected $_blDesc = false;

    /**
     * Set to true to enable multi language
     *
     * @var object
     */
    protected $_blEmployMultilanguage = null;

    /**
     * (default null).
     *
     * @var integer
     */
    protected $_iOverPos = null;

    /**
     * Viewable list size
     *
     * @var int
     */
    protected $_iViewListSize = 0;

    /**
     * Viewable default list size (used in list_*.php views)
     *
     * @var int
     */
    protected $_iDefViewListSize = 50;

    /**
     * List sorting array
     *
     * @var array
     */
    protected $_aCurrSorting = null;

    /**
     * Default sorting field
     *
     * @var string
     */
    protected $_sDefSortField = null;

    /**
     * List filter array
     *
     * @var array
     */
    protected $_aListFilter = null;

    /**
     * Returns sorting fields array
     *
     * @return array
     */
    public function getListSorting()
    {
        if ($this->_aCurrSorting === null) {
            $this->_aCurrSorting = oxRegistry::getConfig()->getRequestParameter('sort');

            if (!$this->_aCurrSorting && $this->_sDefSortField && ($oBaseObject = $this->getItemListBaseObject())) {
                $this->_aCurrSorting[$oBaseObject->getCoreTableName()] = array($this->_sDefSortField => "asc");
            }
        }

        return $this->_aCurrSorting;
    }

    /**
     * Returns list filter array
     *
     * @return array
     */
    public function getListFilter()
    {
        if ($this->_aListFilter === null) {
            $this->_aListFilter = oxRegistry::getConfig()->getRequestParameter("where");
        }

        return $this->_aListFilter;
    }

    /**
     * Viewable list size getter
     *
     * @return int
     */
    protected function _getViewListSize()
    {
        if (!$this->_iViewListSize) {
            $myConfig = $this->getConfig();
            if ($aProfile = oxRegistry::getSession()->getVariable('profile')) {
                if (isset($aProfile[1])) {
                    $myConfig->setConfigParam('iAdminListSize', (int) $aProfile[1]);
                }
            }

            $this->_iViewListSize = (int) $myConfig->getConfigParam('iAdminListSize');
            if (!$this->_iViewListSize) {
                $this->_iViewListSize = 10;
                $myConfig->setConfigParam('iAdminListSize', $this->_iViewListSize);
            }
        }

        return $this->_iViewListSize;
    }

    /**
     * Returns view list size
     *
     * @return int
     */
    public function getViewListSize()
    {
        return $this->_getViewListSize();
    }

    /**
     * Viewable list size getter (used in list_*.php views)
     *
     * @return int
     */
    protected function _getUserDefListSize()
    {
        if (!$this->_iViewListSize) {
            if (!($iViewListSize = (int) oxRegistry::getConfig()->getRequestParameter('viewListSize'))) {
                $iViewListSize = $this->_iDefViewListSize;
            }
            $this->_iViewListSize = $iViewListSize;
        }

        return $this->_iViewListSize;
    }

    /**
     * Executes parent::render(), sets back search keys to view, sets navigation params
     *
     * @return null
     */
    public function render()
    {
        $sReturn = parent::render();

        // assign our list
        $this->_aViewData['mylist'] = $this->getItemList();

        // set navigation parameters
        $this->_setListNavigationParams();

        return $sReturn;
    }

    /**
     * Deletes this entry from the database
     *
     * @return null
     */
    public function deleteEntry()
    {
        $oDelete = oxNew($this->_sListClass);

        $blDelete = $oDelete->delete($this->getEditObjectId());

        // #A - we must reset object ID
        if ($blDelete && isset($_POST['oxid'])) {
            $_POST['oxid'] = -1;
        }

        $this->resetContentCache();

        $this->init();
    }

    /**
     * Calculates list items count
     *
     * @param string $sSql SQL query used co select list items
     */
    protected function _calcListItemsCount($sSql)
    {
        $oStr = getStr();

        // count SQL
        $sSql = $oStr->preg_replace('/select .* from/i', 'select count(*) from ', $sSql);

        // removing order by
        $sSql = $oStr->preg_replace('/order by .*$/i', '', $sSql);

        // con of list items which fits current search conditions
        $this->_iListSize = oxDb::getDb()->getOne($sSql, false, false);

        // set it into session that other frames know about size of DB
        oxRegistry::getSession()->setVariable('iArtCnt', $this->_iListSize);
    }

    /**
     * Set current list position
     *
     * @param string $sPage jump page string
     */
    protected function _setCurrentListPosition($sPage = null)
    {
        $iAdminListSize = $this->_getViewListSize();

        $iJumpTo = $sPage ? ((int) $sPage) : ((int) ((int) oxRegistry::getConfig()->getRequestParameter('lstrt')) / $iAdminListSize);
        $iJumpTo = ($sPage && $iJumpTo) ? ($iJumpTo - 1) : $iJumpTo;

        $iJumpTo = $iJumpTo * $iAdminListSize;
        if ($iJumpTo < 1) {
            $iJumpTo = 0;
        } elseif ($iJumpTo >= $this->_iListSize) {
            $iJumpTo = floor($this->_iListSize / $iAdminListSize - 1) * $iAdminListSize;
        }

        $this->_iCurrListPos = $this->_iOverPos = (int) $iJumpTo;
    }

    /**
     * Adds order by to SQL query string.
     *
     * @param string $sSql sql string
     *
     * @return string
     */
    protected function _prepareOrderByQuery($sSql = null)
    {
        // sorting
        $aSortFields = $this->getListSorting();

        if (is_array($aSortFields) && count($aSortFields)) {

            // only add order by at full sql not for count(*)
            $sSql .= ' order by ';
            $blSep = false;

            $oListItem = $this->getItemListBaseObject();
            $iLangId = $oListItem->isMultilang() ? $oListItem->getLanguage() : oxRegistry::getLang()->getBaseLanguage();

            $blSortDesc = oxRegistry::getConfig()->getRequestParameter('adminorder');
            $blSortDesc = $blSortDesc !== null ? (bool) $blSortDesc : $this->_blDesc;

            foreach ($aSortFields as $sTable => $aFieldData) {

                $sTable = $sTable ? (getViewName($sTable, $iLangId) . '.') : '';
                foreach ($aFieldData as $sColumn => $sSortDir) {

                    $sField = $sTable . $sColumn;

                    //add table name to column name if no table name found attached to column name
                    $sSql .= ((($blSep) ? ', ' : '')) . oxDb::getInstance()->escapeString($sField);

                    //V oxActive field search always DESC
                    if ($blSortDesc || $sColumn == "oxactive" || strcasecmp($sSortDir, 'desc') == 0) {
                        $sSql .= ' desc ';
                    }

                    $blSep = true;
                }
            }
        }

        return $sSql;
    }

    /**
     * Builds and returns SQL query string.
     *
     * @param object $oListObject list main object
     *
     * @return string
     */
    protected function _buildSelectString($oListObject = null)
    {
        return $oListObject !== null ? $oListObject->buildSelectString(null) : "";
    }

    /**
     * Prepares SQL where query according SQL condition array and attaches it to SQL end.
     * For each search value if german umlauts exist, adds them
     * and replaced by spec. char to query
     *
     * @param string $sFieldValue Filters
     *
     * @return string
     */
    protected function _processFilter($sFieldValue)
    {
        $oStr = getStr();

        //removing % symbols
        $sFieldValue = $oStr->preg_replace("/^%|%$/", "", trim($sFieldValue));

        return $oStr->preg_replace("/\s+/", " ", $sFieldValue);
    }

    /**
     * Builds part of SQL query
     *
     * @param string $sVal            filter value
     * @param bool   $blIsSearchValue filter value type, true means surrount search key with '%'
     *
     * @return string
     */
    protected function _buildFilter($sVal, $blIsSearchValue)
    {
        if ($blIsSearchValue) {
            //is search string, using LIKE
            $sQ = " like " . oxDb::getDb()->quote('%' . $sVal . '%') . " ";
        } else {
            //not search string, values must be equal
            $sQ = " = " . oxDb::getDb()->quote($sVal) . " ";
        }

        return $sQ;
    }

    /**
     * Checks if filter contains wildcards like %
     *
     * @param string $sFieldValue filter value
     *
     * @return bool
     */
    protected function _isSearchValue($sFieldValue)
    {
        //check if this is search string (contains % sign at beginning and end of string)
        $blIsSearchValue = false;
        $oStr = getStr();
        if ($oStr->preg_match('/^%/', $sFieldValue) && $oStr->preg_match('/%$/', $sFieldValue)) {
            $blIsSearchValue = true;
        }

        //removing % symbols
        return $blIsSearchValue;
    }

    /**
     * Prepares SQL where query according SQL condition array and attaches it to SQL end.
     * For each search value if german umlauts exist, adds them
     * and replaced by spec. char to query
     *
     * @param array  $aWhere  SQL condition array
     * @param string $sqlFull SQL query string
     *
     * @return string
     */
    protected function _prepareWhereQuery($aWhere, $sqlFull)
    {
        if (count($aWhere)) {
            $myUtilsString = oxRegistry::get("oxUtilsString");
            while (list($sFieldName, $sFieldValue) = each($aWhere)) {
                $sFieldValue = trim($sFieldValue);

                //check if this is search string (contains % sign at beginning and end of string)
                $blIsSearchValue = $this->_isSearchValue($sFieldValue);

                //removing % symbols
                $sFieldValue = $this->_processFilter($sFieldValue);

                if (strlen($sFieldValue)) {
                    $aVal = explode(' ', $sFieldValue);

                    //for each search field using AND action
                    $sSqlBoolAction = ' and (';

                    foreach ($aVal as $sVal) {
                        // trying to search spec chars in search value
                        // if found, add cleaned search value to search sql
                        $sUml = $myUtilsString->prepareStrForSearch($sVal);
                        if ($sUml) {
                            $sSqlBoolAction .= '(';
                        }

                        $sFieldName = oxDb::getInstance()->escapeString($sFieldName);
                        $sqlFull .= " {$sSqlBoolAction} {$sFieldName} ";

                        //for search in same field for different values using AND
                        $sSqlBoolAction = ' and ';

                        $sqlFull .= $this->_buildFilter($sVal, $blIsSearchValue);

                        if ($sUml) {
                            $sqlFull .= " or {$sFieldName} ";

                            $sqlFull .= $this->_buildFilter($sUml, $blIsSearchValue);
                            $sqlFull .= ')'; // end of OR section
                        }
                    }

                    // end for AND action
                    $sqlFull .= ' ) ';
                }
            }
        }

        return $sqlFull;
    }

    /**
     * Override this for individual search in admin.
     *
     * @param string $sSql SQL select to change
     *
     * @return string
     */
    protected function _changeselect($sSql)
    {
        return $sSql;
    }

    /**
     * Builds and returns array of SQL WHERE conditions.
     *
     * @return array
     */
    public function buildWhere()
    {
        if ($this->_aWhere === null && ($oList = $this->getItemList())) {

            $this->_aWhere = array();
            $aFilter = $this->getListFilter();
            if (is_array($aFilter)) {

                $oListItem = $this->getItemListBaseObject();
                $iLangId = $oListItem->isMultilang() ? $oListItem->getLanguage() : oxRegistry::getLang()->getBaseLanguage();
                $sLocalDateFormat = $this->getConfig()->getConfigParam('sLocalDateFormat');

                foreach ($aFilter as $sTable => $aFilterData) {
                    foreach ($aFilterData as $sName => $sValue) {
                        if ($sValue || '0' === ( string ) $sValue) {

                            $sField = "{$sTable}__{$sName}";

                            // if no table name attached to field name, add it
                            $sName = $sTable ? getViewName($sTable, $iLangId) . ".{$sName}" : $sName;

                            // #M1260: if field is date
                            if ($sLocalDateFormat && $sLocalDateFormat != 'ISO' && isset($oListItem->$sField)) {
                                $sFldType = $oListItem->{$sField}->fldtype;
                                if ("datetime" == $sFldType || "date" == $sFldType) {
                                    $sValue = $this->_convertToDBDate($sValue, $sFldType);
                                }
                            }

                            $this->_aWhere[$sName] = "%{$sValue}%";
                        }
                    }
                }
            }
        }

        return $this->_aWhere;
    }

    /**
     * Converts date/datetime values to DB scheme (#M1260)
     *
     * @param string $sValue   field value
     * @param string $sFldType field type
     *
     * @return string
     */
    protected function _convertToDBDate($sValue, $sFldType)
    {
        $oConvObject = new oxField();
        $oConvObject->setValue($sValue);
        if ($sFldType == "datetime") {
            if (strlen($sValue) == 10 || strlen($sValue) == 22 || (strlen($sValue) == 19 && !stripos($sValue, "m"))) {
                oxRegistry::get("oxUtilsDate")->convertDBDateTime($oConvObject, true);
            } else {
                if (strlen($sValue) > 10) {
                    return $this->_convertTime($sValue);
                } else {
                    return $this->_convertDate($sValue);
                }
            }
        } elseif ($sFldType == "date") {
            if (strlen($sValue) == 10) {
                oxRegistry::get("oxUtilsDate")->convertDBDate($oConvObject, true);
            } else {
                return $this->_convertDate($sValue);
            }
        }

        return $oConvObject->value;
    }

    /**
     * Converter for date field search. If not full date will be searched.
     *
     * @param string $sDate searched date
     *
     * @return string
     */
    protected function _convertDate($sDate)
    {
        // regexps to validate input
        $aDatePatterns = array("/^([0-9]{2})\.([0-9]{4})/" => "EUR2", // MM.YYYY
                               "/^([0-9]{2})\.([0-9]{2})/" => "EUR1", // DD.MM
                               "/^([0-9]{2})\/([0-9]{4})/" => "USA2", // MM.YYYY
                               "/^([0-9]{2})\/([0-9]{2})/" => "USA1" // DD.MM
        );

        // date/time formatting rules
        $aDFormats = array("EUR1" => array(2, 1),
                           "EUR2" => array(2, 1),
                           "USA1" => array(1, 2),
                           "USA2" => array(2, 1)
        );

        // looking for date field
        $aDateMatches = array();
        $oStr = getStr();
        foreach ($aDatePatterns as $sPattern => $sType) {
            if ($oStr->preg_match($sPattern, $sDate, $aDateMatches)) {
                $sDate = $aDateMatches[$aDFormats[$sType][0]] . "-" . $aDateMatches[$aDFormats[$sType][1]];
                break;
            }
        }

        return $sDate;
    }

    /**
     * Converter for datetime field search. If not full time will be searched.
     *
     * @param string $sFullDate searched date
     *
     * @return string
     */
    protected function _convertTime($sFullDate)
    {
        $sDate = substr($sFullDate, 0, 10);
        $oConvObject = new oxField();
        $oConvObject->setValue($sDate);
        oxRegistry::get("oxUtilsDate")->convertDBDate($oConvObject, true);
        $oStr = getStr();

        // looking for time field
        $sTime = substr($sFullDate, 11);
        if ($oStr->preg_match("/([0-9]{2}):([0-9]{2}) ([AP]{1}[M]{1})$/", $sTime, $aTimeMatches)) {
            if ($aTimeMatches[3] == "PM") {
                $iIntVal = (int) $aTimeMatches[1];
                if ($iIntVal < 13) {
                    $sTime = ($iIntVal + 12) . ":" . $aTimeMatches[2];
                }
            } else {
                $sTime = $aTimeMatches[1] . ":" . $aTimeMatches[2];
            }
        } elseif ($oStr->preg_match("/([0-9]{2}) ([AP]{1}[M]{1})$/", $sTime, $aTimeMatches)) {
            if ($aTimeMatches[2] == "PM") {
                $iIntVal = (int) $aTimeMatches[1];
                if ($iIntVal < 13) {
                    $sTime = ($iIntVal + 12);
                }
            } else {
                $sTime = $aTimeMatches[1];
            }
        } else {
            $sTime = str_replace(".", ":", $sTime);
        }

        return $oConvObject->value . " " . $sTime;
    }

    /**
     * Set parameters needed for list navigation
     */
    protected function _setListNavigationParams()
    {
        $myConfig = $this->getConfig();

        // list navigation
        $blShowNavigation = false;
        $iAdminListSize = $this->_getViewListSize();
        if ($this->_iListSize > $iAdminListSize) {
            // yes, we need to build the navigation object
            $pageNavigation = new stdClass();
            $pageNavigation->pages = round((($this->_iListSize - 1) / $iAdminListSize) + 0.5, 0);
            $pageNavigation->actpage = ($pageNavigation->actpage > $pageNavigation->pages) ? $pageNavigation->pages : round(($this->_iCurrListPos / $iAdminListSize) + 0.5, 0);
            $pageNavigation->lastlink = ($pageNavigation->pages - 1) * $iAdminListSize;
            $pageNavigation->nextlink = null;
            $pageNavigation->backlink = null;

            $iPos = $this->_iCurrListPos + $iAdminListSize;
            if ($iPos < $this->_iListSize) {
                $pageNavigation->nextlink = $iPos = $this->_iCurrListPos + $iAdminListSize;
            }

            if (($this->_iCurrListPos - $iAdminListSize) >= 0) {
                $pageNavigation->backlink = $iPos = $this->_iCurrListPos - $iAdminListSize;
            }

            // calculating list start position
            $iStart = $pageNavigation->actpage - 5;
            $iStart = ($iStart <= 0) ? 1 : $iStart;

            // calculating list end position
            $iEnd = $pageNavigation->actpage + 5;
            $iEnd = ($iEnd < $iStart + 10) ? $iStart + 10 : $iEnd;
            $iEnd = ($iEnd > $pageNavigation->pages) ? $pageNavigation->pages : $iEnd;

            // once again adjusting start pos ..
            $iStart = ($iEnd - 10 > 0) ? $iEnd - 10 : $iStart;
            $iStart = ($pageNavigation->pages <= 11) ? 1 : $iStart;

            // navigation urls
            for ($i = $iStart; $i <= $iEnd; $i++) {
                $page = new stdclass();
                $page->selected = 0;
                if ($i == $pageNavigation->actpage) {
                    $page->selected = 1;
                }
                $pageNavigation->changePage[$i] = $page;
            }

            $this->_aViewData['pagenavi'] = $pageNavigation;

            if (isset($this->_iOverPos)) {
                $iPos = $this->_iOverPos;
                $this->_iOverPos = null;
            } else {
                $iPos = oxRegistry::getConfig()->getRequestParameter('lstrt');
            }

            if (!$iPos) {
                $iPos = 0;
            }

            $this->_aViewData['lstrt'] = $iPos;
            $this->_aViewData['listsize'] = $this->_iListSize;
            $blShowNavigation = true;
        }

        // determine not used space in List
        $iShowListSize = $this->_iListSize - $this->_iCurrListPos;
        $iAdminListSize = $this->_getViewListSize();
        $iNotUsed = $iAdminListSize - min($iShowListSize, $iAdminListSize);
        $iSpace = $iNotUsed * 15;

        if (!$blShowNavigation) {
            $iSpace += 20;
        }

        $this->_aViewData['iListFillsize'] = $iSpace;
    }

    /**
     * Sets-up navigation parameters
     *
     * @param string $sNode active view id
     */
    protected function _setupNavigation($sNode)
    {
        // navigation according to class
        if ($sNode) {

            $myAdminNavigation = $this->getNavigation();

            $sOxId = $this->getEditObjectId();

            if ($sOxId == -1) {
                //on first call or when pressed creating new item button, reseting active tab
                $iActTab = $this->_iDefEdit;
            } else {
                // active tab
                $iActTab = oxRegistry::getConfig()->getRequestParameter('actedit');
                $iActTab = $iActTab ? $iActTab : $this->_iDefEdit;
            }

            // tabs
            $this->_aViewData['editnavi'] = $myAdminNavigation->getTabs($sNode, $iActTab);

            // active tab
            $this->_aViewData['actlocation'] = $myAdminNavigation->getActiveTab($sNode, $iActTab);

            // default tab
            $this->_aViewData['default_edit'] = $myAdminNavigation->getActiveTab($sNode, $this->_iDefEdit);

            // assign active tab number
            $this->_aViewData['actedit'] = $iActTab;
        }
    }

    /**
     * Returns items list
     *
     * @return oxList
     */
    public function getItemList()
    {
        if ($this->_oList === null && $this->_sListClass) {

            $this->_oList = oxNew($this->_sListType);
            $this->_oList->clear();
            $this->_oList->init($this->_sListClass);

            $aWhere = $this->buildWhere();

            $oListObject = $this->_oList->getBaseObject();

            oxRegistry::getSession()->setVariable('tabelle', $this->_sListClass);
            $this->_aViewData['listTable'] = getViewName($oListObject->getCoreTableName());
            $this->getConfig()->setGlobalParameter('ListCoreTable', $oListObject->getCoreTableName());

            if ($oListObject->isMultilang()) {
                // is the object multilingual?
                $oListObject->setLanguage(oxRegistry::getLang()->getBaseLanguage());

                if (isset($this->_blEmployMultilanguage)) {
                    $oListObject->setEnableMultilang($this->_blEmployMultilanguage);
                }
            }

            $sSql = $this->_buildSelectString($oListObject);
            $sSql = $this->_prepareWhereQuery($aWhere, $sSql);
            $sSql = $this->_prepareOrderByQuery($sSql);
            $sSql = $this->_changeselect($sSql);

            // calculates count of list items
            $this->_calcListItemsCount($sSql);

            // setting current list position (page)
            $this->_setCurrentListPosition(oxRegistry::getConfig()->getRequestParameter('jumppage'));

            // setting addition params for list: current list size
            $this->_oList->setSqlLimit($this->_iCurrListPos, $this->_getViewListSize());

            $this->_oList->selectString($sSql);
        }

        return $this->_oList;
    }

    /**
     * Clear items list
     */
    public function clearItemList()
    {
        $this->_oList = null;
    }

    /**
     * Returns item list base object
     *
     * @return oxBase
     */
    public function getItemListBaseObject()
    {
        if (($oList = $this->getItemList())) {
            return $oList->getBaseObject();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
A simple GTK+ client to browse MEGA cloud drive

![Screenshot](http://i.imgur.com/vOFgfM4l.jpg "MEGABrowser")


text:
If you liked this post, you can

  share it with your followers
or

  follow me on Twitter!


text:
package org.apache.spark.storage

import java.util.concurrent.Semaphore

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._

import org.apache.spark.{LocalSparkContext, SparkConf, SparkContext, SparkFunSuite, Success}
import org.apache.spark.internal.config
import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd, SparkListenerTaskStart}
import org.apache.spark.scheduler.cluster.StandaloneSchedulerBackend
import org.apache.spark.util.{ResetSystemProperties, ThreadUtils}

class BlockManagerDecommissionSuite extends SparkFunSuite with LocalSparkContext
    with ResetSystemProperties {

  override def beforeEach(): Unit = {
    val conf = new SparkConf().setAppName("test")
      .set(config.Worker.WORKER_DECOMMISSION_ENABLED, true)
      .set(config.STORAGE_DECOMMISSION_ENABLED, true)

    sc = new SparkContext("local-cluster[2, 1, 1024]", "test", conf)
  }

  test(s"verify that an already running task which is going to cache data succeeds " +
    s"on a decommissioned executor") {
    // Create input RDD with 10 partitions
    val input = sc.parallelize(1 to 10, 10)
    val accum = sc.longAccumulator("mapperRunAccumulator")
    // Do a count to wait for the executors to be registered.
    input.count()

    // Create a new RDD where we have sleep in each partition, we are also increasing
    // the value of accumulator in each partition
    val sleepyRdd = input.mapPartitions { x =>
      Thread.sleep(500)
      accum.add(1)
      x
    }

    // Listen for the job
    val sem = new Semaphore(0)
    val taskEndEvents = ArrayBuffer.empty[SparkListenerTaskEnd]
    sc.addSparkListener(new SparkListener {
      override def onTaskStart(taskStart: SparkListenerTaskStart): Unit = {
       sem.release()
      }

      override def onTaskEnd(taskEnd: SparkListenerTaskEnd): Unit = {
        taskEndEvents.append(taskEnd)
      }
    })

    // Cache the RDD lazily
    sleepyRdd.persist()

    // Start the computation of RDD - this step will also cache the RDD
    val asyncCount = sleepyRdd.countAsync()

    // Wait for the job to have started
    sem.acquire(1)

    // Give Spark a tiny bit to start the tasks after the listener says hello
    Thread.sleep(100)
    // Decommission one of the executor
    val sched = sc.schedulerBackend.asInstanceOf[StandaloneSchedulerBackend]
    val execs = sched.getExecutorIds()
    assert(execs.size == 2, s"Expected 2 executors but found ${execs.size}")
    val execToDecommission = execs.head
    sched.decommissionExecutor(execToDecommission)

    // Wait for job to finish
    val asyncCountResult = ThreadUtils.awaitResult(asyncCount, 6.seconds)
    assert(asyncCountResult === 10)
    // All 10 tasks finished, so accum should have been increased 10 times
    assert(accum.value === 10)

    // All tasks should be successful, nothing should have failed
    sc.listenerBus.waitUntilEmpty()
    assert(taskEndEvents.size === 10) // 10 mappers
    assert(taskEndEvents.map(_.reason).toSet === Set(Success))

    // Since the RDD is cached, so further usage of same RDD should use the
    // cached data. Original RDD partitions should not be recomputed i.e. accum
    // should have same value like before
    assert(sleepyRdd.count() === 10)
    assert(accum.value === 10)
  }
}


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.cmd.function;

import ghidra.framework.cmd.Command;
import ghidra.framework.model.DomainObject;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
import ghidra.program.model.symbol.SourceType;

/**
 * Command to set the name of a function.
 */
public class SetFunctionNameCmd implements Command {
    private Address entry;
    private String  name;
	private String msg;
	private SourceType source;
    /**
     * Constructs a new command for setting the name of a function.
     * @param entry the address of the function to be renamed.
     * @param newName the new name for the function.
	 * @param source the source of this function name
     */
    public SetFunctionNameCmd(Address entry, String newName, SourceType source) {
        this.entry = entry;
		this.name = newName;
		this.source = source;
    }
	/**
	 *
	 * @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject)
	 */
	public boolean applyTo(DomainObject obj) {
		Program program = (Program)obj;

        if (name.length() <= 0) {
            name = null;
        }

        Function f = program.getListing().getFunctionAt(entry);
        if (f == null) {
            return true;
        }
		try {
			f.setName(name, source);
		}
		catch (Exception e) {
			msg = e.getMessage();
			return false;
		}
		return true;

    }

	/**
	 *
	 * @see ghidra.framework.cmd.Command#getName()
	 */
    public String getName() {
        return "Rename Function";
    }

	/**
	 * @see ghidra.framework.cmd.Command#getStatusMsg()
	 */
	public String getStatusMsg() {
		return msg;
	}

}


text:
namespace Microsoft.Azure.Management.BatchAI.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// SSH configuration.
    /// </summary>
    public partial class SshConfiguration
    {
        /// <summary>
        /// Initializes a new instance of the SshConfiguration class.
        /// </summary>
        public SshConfiguration()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SshConfiguration class.
        /// </summary>
        /// <param name="userAccountSettings">User account settings.</param>
        /// <param name="publicIPsToAllow">Allowed public IPs.</param>
        public SshConfiguration(UserAccountSettings userAccountSettings, IList<string> publicIPsToAllow = default(IList<string>))
        {
            PublicIPsToAllow = publicIPsToAllow;
            UserAccountSettings = userAccountSettings;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets allowed public IPs.
        /// </summary>
        /// <remarks>
        /// List of source IP ranges to allow SSH connection from. The default
        /// value is '*' (all source IPs are allowed). Maximum number of IP
        /// ranges that can be specified is 400.
        /// </remarks>
        [JsonProperty(PropertyName = "publicIPsToAllow")]
        public IList<string> PublicIPsToAllow { get; set; }

        /// <summary>
        /// Gets or sets user account settings.
        /// </summary>
        /// <remarks>
        /// Settings for administrator user account to be created on a node.
        /// The account can be used to establish SSH connection to the node.
        /// </remarks>
        [JsonProperty(PropertyName = "userAccountSettings")]
        public UserAccountSettings UserAccountSettings { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (UserAccountSettings == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "UserAccountSettings");
            }
            if (UserAccountSettings != null)
            {
                UserAccountSettings.Validate();
            }
        }
    }
}


text:
package com.xiaoleilu.hutool.lang;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;

import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.getter.BasicTypeGetter;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;

/**
 * 1、字典对象,扩充了HashMap中的方法
 * @author loolly
 *
 */
public class Dict extends HashMap<String, Object> implements BasicTypeGetter<String>{
	private static final long serialVersionUID = 6135423866861206530L;

	//--------------------------------------------------------------- Static method start
	/**
	 * 创建Dict
	 * @return Dict
	 */
	public static Dict create() {
		return new Dict();
	}

	/**
	 * 将PO对象转为Dict
	 * @param <T>
	 * @param bean Bean对象
	 * @return Vo
	 */
	public static <T> Dict parse(T bean) {
		return create().parseBean(bean);
	}
	//--------------------------------------------------------------- Static method end

	//--------------------------------------------------------------- Constructor start
	public Dict() {
	}
	//--------------------------------------------------------------- Constructor end

	/**
	 * 转换为Bean对象
	 * @param <T>
	 * @param bean Bean
	 * @return Bean
	 */
	public <T> T toBean(T bean) {
		return toBean(bean, false);
	}

	/**
	 * 转换为Bean对象
	 * @param <T>
	 * @param bean Bean
	 * @param isToCamelCase 是否转换为驼峰模式
	 * @return Bean
	 */
	public <T> T toBean(T bean, boolean isToCamelCase) {
		BeanUtil.fillBeanWithMap(this, bean, isToCamelCase);
		return bean;
	}

	/**
	 * 填充Value Object对象
	 * @param clazz Value Object(或者POJO)的类
	 * @return vo
	 */
	public <T> T toBean(Class<T> clazz) {
		return BeanUtil.mapToBean(this, clazz, false);
	}

	/**
	 * 填充Value Object对象,忽略大小写
	 * @param clazz Value Object(或者POJO)的类
	 * @return vo
	 */
	public <T> T toBeanIgnoreCase(Class<T> clazz) {
		return BeanUtil.mapToBeanIgnoreCase(this, clazz, false);
	}

	/**
	 * 将值对象转换为Dict

	 * 类名会被当作表名,小写第一个字母
	 * @param <T>
	 * @param bean 值对象
	 * @return 自己
	 */
	public <T> Dict parseBean(T bean) {
		this.putAll(BeanUtil.beanToMap(bean));
		return this;
	}

	/**
	 * 与给定实体对比并去除相同的部分

	 * 此方法用于在更新操作时避免所有字段被更新,跳过不需要更新的字段
	 * version from 2.0.0
	 * @param dict
	 * @param withoutNames 不需要去除的字段名
	 */
	public <T extends Dict> void removeEqual(T dict, String... withoutNames) {
		HashSet<String> withoutSet = CollectionUtil.newHashSet(withoutNames);
		for(Entry<String, Object> entry : dict.entrySet()) {
			if(withoutSet.contains(entry.getKey())) {
				continue;
			}

			final Object value = this.get(entry.getKey());
			if(null != value && value.equals(entry.getValue())) {
				this.remove(entry.getKey());
			}
		}
	}

	//-------------------------------------------------------------------- Set start
	/**
	 * 设置列
	 * @param attr 属性
	 * @param value 值
	 * @return 本身
	 */
	public Dict set(String attr, Object value) {
		this.put(attr, value);
		return this;
	}

	/**
	 * 设置列,当键或值为null时忽略
	 * @param attr 属性
	 * @param value 值
	 * @return 本身
	 */
	public Dict setIgnoreNull(String attr, Object value) {
		if(null != attr && null != value) {
			set(attr, value);
		}
		return this;
	}
	//-------------------------------------------------------------------- Set end

	//-------------------------------------------------------------------- Get start

	@Override
	public Object getObj(String key) {
		return super.get(key);
	}

	/**
	 * 获得特定类型值
	 * @param attr 字段名
	 * @param defaultValue 默认值
	 * @return 字段值
	 */
	@SuppressWarnings("unchecked")
	public <T> T get(String attr, T defaultValue) {
		final Object result = get(attr);
		return (T)(result != null ? result : defaultValue);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public String getStr(String attr) {
		return Convert.toStr(get(attr), null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public Integer getInt(String attr) {
		return Convert.toInt(get(attr), null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public Long getLong(String attr) {
		return Convert.toLong(get(attr), null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public Float getFloat(String attr) {
		return Convert.toFloat(get(attr), null);
	}

	@Override
	public Short getShort(String attr) {
		return Convert.toShort(get(attr), null);
	}

	@Override
	public Character getChar(String attr) {
		return Convert.toChar(get(attr), null);
	}

	@Override
	public Double getDouble(String attr) {
		return Convert.toDouble(get(attr), null);
	}

	@Override
	public Byte getByte(String attr) {
		return Convert.toByte(get(attr), null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public Boolean getBool(String attr) {
		return Convert.toBool(get(attr), null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public BigDecimal getBigDecimal(String attr) {
		return Convert.toBigDecimal(get(attr));
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	@Override
	public BigInteger getBigInteger(String attr) {
		return Convert.toBigInteger(get(attr));
	}

	@Override
	public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) {
		return Convert.toEnum(clazz, get(key));
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	public byte[] getBytes(String attr) {
		return get(attr, null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	public Date getDate(String attr) {
		return get(attr, null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	public Time getTime(String attr) {
		return get(attr, null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	public Timestamp getTimestamp(String attr) {
		return get(attr, null);
	}

	/**
	 * @param attr 字段名
	 * @return 字段值
	 */
	public Number getNumber(String attr) {
		return get(attr, null);
	}
	//-------------------------------------------------------------------- Get end

	@Override
	public Dict clone() {
		return (Dict) super.clone();
	}
}


text:
import * as ffi from 'ffi'
import * as os from 'os'
import * as path from 'path'

import { FFIConfiguration, IFFIEntryPoint } from './rustlib'

export interface IVCXRuntimeConfig {
  basepath?: string
}

// VCXRuntime is the object that interfaces with the vcx sdk functions
// FFIConfiguration will contain all the sdk api functions
// VCXRuntimeConfg is a class that currently only contains a chosen basepath for the .so file
// I made it a class just in case we think of more needed configs

const extension = {"darwin": ".dylib", "linux": ".so", "win32": ".dll"}
const libPath = {"darwin": "/usr/local/lib/", "linux": '/usr/lib/', "win32": 'c:\\windows\\system32\\'}

export class VCXRuntime {
  public readonly ffi: IFFIEntryPoint
  private _config: IVCXRuntimeConfig

  constructor (config: IVCXRuntimeConfig = {}) {
    this._config = config
    // initialize FFI
    const libraryPath = this._initializeBasepath()
    this.ffi = ffi.Library(libraryPath, FFIConfiguration)
  }

  private _initializeBasepath = (): string => {
    const platform = os.platform()
    // @ts-ignore
    const postfix = extension[platform.toLowerCase()] || extension['linux']
    // @ts-ignore
    const libDir = libPath[platform.toLowerCase()] || libPath['linux']
    const library = `libvcx${postfix}`
    const customPath = process.env.LIBVCX_PATH ? process.env.LIBVCX_PATH + library : undefined
    return customPath || this._config.basepath || path.resolve(__dirname, `${libDir}${library}`)
  }
}


text: extern void RunVoxelcutSimulation();


text:
slimta.base64
=============

.. module:: slimta.base64

Module containing encoding and decoding functions for the standard base64 codec,
as provided by the OpenSSL crypto library.

.. function:: encode(data)

   Encodes the string with the base64 algorithm. This operation will increase
   the size of the data by about 33%, but will make it transferable on
   traditionally 7-bit streams such as SMTP.

   :param data: string of data to encode.
   :return: string of base64 encoded data.

.. function:: decode(data)

   Decodes the string with the base64 algorithm. The following operation should
   always be true: ``decode(encode(X)) == X``

   :param data: string of base64 data to decode.
   :return: string of potentially binary, decoded data.


text:
package com.njlabs.guide.android.dev;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

public class ImagePicker extends SherlockActivity {
	private static final int REQUEST_CODE = 1;
	private Bitmap bitmap;
	private ImageView imageView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_picker);
		ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        imageView = (ImageView) findViewById(R.id.photo_holder);
        WebView webView = (WebView) findViewById(R.id.webViewJava);
        webView.setWebViewClient(new WebViewClient(){
        	@TargetApi(11)
        	@Override
        	public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        	    Log.d("shouldInterceptRequest", url);

        	    InputStream stream = inputStreamForAndroidResource(url);
        	    if (stream != null) {
        	        return new WebResourceResponse("text/javascript", "utf-8", stream);
        	    }
        	    return super.shouldInterceptRequest(view, url);
        	}

        	private InputStream inputStreamForAndroidResource(String url) {
        	    final String ANDROID_ASSET = "file:///android_asset/";

        	    if (url.contains(ANDROID_ASSET)) {
        	        url = url.replaceFirst(ANDROID_ASSET, "");
        	        try {
        	            AssetManager assets = getAssets();
        	            Uri uri = Uri.parse(url);
        	            return assets.open(uri.getPath(), AssetManager.ACCESS_STREAMING);
        	        } catch (IOException e) {
        	            e.printStackTrace();
        	        }
        	    }
        	    return null;
        	}

        });
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("file:///android_asset/code_snippets/image_picker_java.html");
	}

	public void PickImage(View View)
	{
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		startActivityForResult(intent, REQUEST_CODE);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		InputStream stream = null;
		if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
		{
			try
			{
				// We need to recyle unused bitmaps
				if (bitmap != null)
				{
					bitmap.recycle();
				}
				stream = getContentResolver().openInputStream(data.getData());
				bitmap = BitmapFactory.decodeStream(stream);

				imageView.setImageBitmap(bitmap);
				int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());

				imageView.getLayoutParams().height = height;
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			if (stream != null)
			{
				try
				{
					stream.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
    private Menu mainMenu;
    private SubMenu subMenu1;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        mainMenu = menu;

        subMenu1 = menu.addSubMenu("Options");
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.main, subMenu1);

        MenuItem subMenu1Item = subMenu1.getItem();
        subMenu1Item.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
        subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
            	finish();
                overridePendingTransition(R.anim.fadein,R.anim.fadeout);
                return true;
            case R.id.AboutAppOption:
                Intent intent1 = new Intent(this, AboutApp.class);
                startActivity(intent1);
                overridePendingTransition(R.anim.fadein,R.anim.fadeout);
                return true;
            case R.id.BugReportOption:
                Intent intent2 = new Intent(this, BugReport.class);
                startActivity(intent2);
                overridePendingTransition(R.anim.fadein,R.anim.fadeout);
                return true;
            default:
                return super.onOptionsItemSelected(item);

        }

    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
                mainMenu.performIdentifierAction(subMenu1.getItem().getItemId(), 0);
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<title>BSF Bean Scripting Framework</title>

Home
Back

Contents
Next

BSF Bean Scripting Framework

BSF is the Apache "Bean Scripting Framework".
It is generic framework that allows
many scripting languages to be plugged into an application.  It shields
the application from knowledge of how to invoke the scripting languages and
their APIs, via adapter "engines".

BeanShell supports the BSF API by providing the necessary adapter.
This means that BeanShell can be used as a scripting language for any BSF
2.3 capable application simply by dropping the bsh JAR file into the classpath.

Prior to version 2.3, BSF was maintained by IBM.
To get BeanShell to work with older versions of BSF you must use the
older bsh-bsf-1.2x.jar file which includes the adapter class for the previous
ibm packaged BSF API.
You must also explicitly register the BeanShell adapter with older versions
of BSF.  Here is an example of how to do that:

import com.ibm.bsf.*;

// register beanshell with the BSF framework
String [] extensions = { "bsh" };
BSFManager.registerScriptingEngine(
    "beanshell", "bsh.util.BeanShellBSFEngine", extensions );

See
http://jakarta.apache.org/bsf/
and

http://oss.software.ibm.com/developerworks/projects/bsf

for more information about BSF.

Ant

This section needs to be updated.  I'm not sure what versionf of Ant use
the new and which use the old BSF API.

Ant 1.5+ has explicit support for BeanShell as a BSF scripting language.
The BeanShell JAR file includes the necessary BSF adapter.  You must
simply specify language="beanshell" in your script tags.

Installation

To use BeanShell within Ant you must do two things:

Add the

BSF bsf.jar file
to ANT_HOME/lib or the classpath.

Add the

BeanShell bsh.jar file
to ANT_HOME/lib or the classpath.

You can then run scripts from a file, or in-line like so:

<project name="testbsh" default="runscript" basedir=".">
    <target name="runscript">

        <!-- Run script from a file -->
        <script language="beanshell" src="myscript.bsh"/>

        <!-- Run script in-line -->
        <script language="beanshell">&lt;![CDATA[
            for(int i=0; i<10; i++ )
                print( "i="+i );
        ]]&gt;</script>

    </target>
</project>

Home
Back

Contents
Next


text:
\documentclass[class=scrbook,crop=false]{standalone}

\input{./preamble}

\begin{document}

    \section*{Projektsitzung 2. Mai 2016}

    \begin{tabular}{ll}
        \textbf{Datum} & 2.5.2016 \\
        \textbf{Zeit} & 13:10 \textendash 13:55 Uhr \\
        \textbf{Ort} & \acs{hsr} \\
        \textbf{Anwesende} & \proff \\ & \ubos \\ & \pchr
    \end{tabular}

    \subsection*{Traktanden}

    \begin{itemize}
        \item Review Sprint 3
        \item Preview Sprint 4
        \item Anpassungen aufgrund Feedback der Zwischenpräsentation
        \begin{itemize}
            \item Kleine Anpassung Domainmodel/API
        \end{itemize}
        \item Handhabung von Prozessen (Daemonize, Hintergrundprozesse) / Asynchrone Verarbeitung
        \item Angepasste Generators zum generieren von GUIs
        \item Umfang und Inhalt der Dokumentation
    \end{itemize}

    \subsection*{Protokoll}

	\begin{itemize}
        \item Sprint 3 besprochen
        \begin{itemize}
            \item Ziel-Use-Case erreicht (Updates auslösen im UI, an Agent schicken und installieren)
            \item Weniger Zeit, mehr Arbeit --> noch nicht fertig mit einigen Punkten
        \end{itemize}
        \item Vorschau Sprint 4
        \begin{itemize}
            \item Sicherheits-Aspekte
            \item User-Authentisierung
            \item Überbleibsel Sprint 3
        \end{itemize}
        \item Doku:
        \begin{itemize}
            \item Produkt-Dokumentation eher wichtiger
            \begin{itemize}
                \item Probleme
                \item Risiken? Wie beseitigt?
                \item Benutzerhandbuch
                \item Time-Tracking, Verbesserung bei den Estimates
            \end{itemize}
            \item Wichtig bei Teil Projekt-Doku: Milestones und Zeitplanung
            \item Gutes Example: Smartphone Applikation Grossküchen
        \end{itemize}
        \item Nächstes Meeting: 18.5. wenn möglich, sonst 23.5.
    \end{itemize}

\end{document}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>

    <predicate lemma="snuffle">

        <roleset framnet="" id="snuffle.01" name="Snort mucus back up nose" vncls="40.1.1">
            <roles>
                <role descr="Person with a runny nose" f="" n="0"/>

                <role descr="mucus" f="" n="1"/>
                <note/>
            </roles>

            <example name="Intransative example" src="Intransative example" type="Intransative example">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>The cold air made him snuffle.</text>

                <arg f="" n="0">him</arg>
                <rel f="">snuffle.</rel>
                <note/>
            </example>
            <example name="Example with location" src="Example with location" type="Example with location">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>She could heat him snuffling behind her and gave him a tissue.</text>

                <arg f="" n="0">him</arg>
                <rel f="">snuffling</rel>
                <arg f="loc" n="m">behind her</arg>
                <note/>
            </example>
            <note>Roleset based on internet search. Added due to parallel expansion of verbnet, propbank, and sense groupings. Verbnet class hiccup-40.1.1. No framenet mapping. Framed by Katie.</note>
        </roleset>
        <roleset framnet="" id="snuffle.02" name="Sniff at inquiringly" vncls="">
            <roles>
                <role descr="Sniffer" f="" n="0"/>

                <role descr="Thing smelled" f="" n="1"/>
                <note/>
            </roles>

            <example name="Transative example" src="Transative example" type="Transative example">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>Ferdinand snuffled the flowers.</text>

                <arg f="" n="0">Ferdinand</arg>
                <rel f="">snuffled</rel>
                <arg f="" n="1">the flowers.</arg>
                <note/>
            </example>
            <example name="Example with location" src="Example with location" type="Example with location">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>The puppy snuffled the roses in the garden.</text>

                <arg f="" n="0">The puppy</arg>
                <rel f="">snuffled</rel>
                <arg f="" n="">the roses</arg>
                <arg f="loc" n="m">in the garden.</arg>
                <note/>
            </example>
            <note>Roleset based on internet search. Added due to parallel expansion of verbnet, propbank, and sense groupings. No verbnet mapping. No framenet mapping. Framed by Katie.</note>
        </roleset>
        <roleset framnet="" id="snuffle.03" name="Snivel, cry, or whine with sniffling" vncls="37.3">
            <roles>
                <role descr="Crier" f="" n="0"/>

                <note/>
            </roles>

            <example name="Example with location" src="Example with location" type="Example with location">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>The child was snuffling in his room.</text>

                <arg f="" n="0">The child</arg>
                <rel f="">snuffling</rel>
                <arg f="loc" n="m">in his room.</arg>
                <note/>
            </example>
            <example name="Imparative example" src="Imparative example" type="Imparative example">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>Stop [PRO] snuffling and fix the problem!</text>

                <arg f="" n="0">[Pro]</arg>
                <rel f="">snuffling</rel>
                <note/>
            </example>
            <note>Roleset based on internet search. Added due to parallel expansion of verbnet, propbank, and sense groupings. Verbnet class manner_speaking-37.3. No framenet mapping. Framed by Katie.</note>
        </roleset>
        <note/>
    </predicate>
    <note/>
</frameset>


text:
import {WorkflowContext} from "../Workflow/WorkflowContext";

export class ScreenProps<S> {
    messageContext: WorkflowContext;
    store: S;
}


text:
travis sync &&
travis enable  --no-interactive


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>TreeView</title>

    <style>
      body {
        margin: 0;
      }
    </style>

    <link rel="import" href="example_element.html">
    <script type="application/dart">export 'package:polymer/init.dart';</script>
  </head>
  <body>
    <example-element></example-element>
  </body>
</html>


text:
// Generated by CoffeeScript 1.10.0

/*
## Stdlib
 */
var Stdlib;

Stdlib = (function() {
  function Stdlib() {}

  Stdlib.Math = Math;

  Stdlib.Int8Array = Int8Array;

  Stdlib.Int16Array = Int16Array;

  Stdlib.Int32Array = Int32Array;

  Stdlib.Uint8Array = Uint8Array;

  Stdlib.Uint16Array = Uint16Array;

  Stdlib.Uint32Array = Uint32Array;

  Stdlib.Float32Array = Float32Array;

  Stdlib.Float64Array = Float64Array;

  Stdlib.NaN = NaN;

  Stdlib.Infinity = Infinity;

  return Stdlib;

})();

export default Stdlib;


text:
typedef  void(^didRemoveImage)(void);

@interface YMShowImageView : UIView<UIScrollViewDelegate>
{
    UIImageView *showImage;
}
@property (nonatomic,copy) didRemoveImage removeImg;

- (void)show:(UIView *)bgView didFinish:(didRemoveImage)tempBlock;

- (id)initWithFrame:(CGRect)frame byClick:(NSInteger)clickTag appendArray:(NSArray *)appendArray;

@end


text:
"""
Neural sheet objects.

$Id$
"""
__version__='$Revision: 8986 $'

# Imported here so that all Sheets will be in the same package
from topo.base.sheet import Sheet
from topo.base.projection import ProjectionSheet
from topo.base.cf import CFSheet
from topo.misc.generatorsheet import GeneratorSheet

# Imported here for ease of access by users
from topo.base.boundingregion import BoundingBox
from topo.base.sheet import activity_type # CEBALERT: ...is it?

import numpy

import topo

import param

from topo.base.cf import MaskedCFIter
from topo.base.projection import Projection
from topo.base.simulation import FunctionEvent, PeriodicEventSequence

class ActivityCopy(Sheet):
    """
    Copies incoming Activity patterns to its activity matrix and output port.

    Trivial Sheet class that is useful primarily as a placeholder for
    data that is computed elsewhere but that you want to appear as a
    Sheet, e.g. when wrapping an external simulation.
    """

    dest_ports=['Activity']
    src_ports=['Activity']

    def input_event(self,conn,data):
        self.input_data=data

    def process_current_time(self):
        if hasattr(self, 'input_data'):
            self.activity*=0
            self.activity+=self.input_data
            self.send_output(src_port='Activity',data=self.activity)
            del self.input_data

class SequenceGeneratorSheet(GeneratorSheet):
    """
    Sheet that generates a timed sequence of patterns.

    This sheet will repeatedly generate the input_sequence, with the
    given onsets.  The sequence is repeated every self.period time
    units.  If the total length of the sequence is longer than
    self.period, a warning is issued and the sequence repeats
    immediately after completion.
    """

    input_sequence = param.List(default=[],
          doc="""The sequence of patterns to generate.  Must be a list of
          (onset,generator) tuples. An empty list defaults to the
          single tuple: (0,self.input_generator), resulting in
          identical behavior to an ordinary GeneratorSheet.""")

    def __init__(self,**params):
        super(SequenceGeneratorSheet,self).__init__(**params)
        if not self.input_sequence:
            self.input_sequence = [(0,self.input_generator)]

    def start(self):
        assert self.simulation

        event_seq = []
        for delay,gen in self.input_sequence:
            event_seq.append(FunctionEvent(self.simulation._convert_to_time_type(delay),self.set_input_generator,gen))
            event_seq.append(FunctionEvent(0,self.generate))
        now = self.simulation.time()
        self.event = PeriodicEventSequence(now+self.simulation._convert_to_time_type(self.phase),self.simulation._convert_to_time_type(self.period),event_seq)
        self.simulation.enqueue_event(self.event)

#KK: commented out and replaced with another version
#    to make the MPI code work

"""
def compute_joint_norm_totals(projlist,active_units_mask=True):

    Compute norm_total for each CF in each projection from a group to
    be normalized jointly.

    # Assumes that all Projections in the list have the same r,c size
    assert len(projlist)>=1
    iterator = MaskedCFIter(projlist[0],active_units_mask=active_units_mask)

    for junk,i in iterator():
        sums = [p.flatcfs[i].norm_total for p in projlist]
        joint_sum = numpy.add.reduce(sums)
        for p in projlist:
            p.flatcfs[i].norm_total=joint_sum
"""

def compute_joint_norm_totals(projlist,active_units_mask=True):
    """
    Compute norm_total for each CF in each projection from a group to
    be normalized jointly.
    """
    # Assumes that all Projections in the list have the same r,c size
    # AND that all have the same mask
    assert len(projlist)>=1

    norm_totals_data = []
    norm_totals = []

    for p in projlist:
        norm_totals_data.append(p.get_masked_norm_totals(active_units_mask=active_units_mask))

    for i in range(0,len(norm_totals_data[0])):
        norm_totals.append([n[i] for n in norm_totals_data])

    new_norm_totals = []

    for n in norm_totals:
        joint_sum = numpy.add.reduce(n)
        new_norm_totals.append(joint_sum)

    for p in projlist:
        p.set_masked_norm_totals(new_norm_totals)

class JointNormalizingCFSheet(CFSheet):
    """
    A type of CFSheet extended to support joint sum-based normalization.

    For L1 normalization, joint normalization means normalizing the
    sum of (the absolute values of) all weights in a set of
    corresponding CFs in different Projections, rather than only
    considering weights in the same CF.

    This class provides a mechanism for grouping Projections (see
    _port_match and _grouped_in_projections) and a learn() function
    that computes the joint sums.  Joint normalization also requires
    having ConnectionField store and return a norm_total for each
    neuron, and having an TransferFn that will respect this norm_total
    rather than the strict total of the ConnectionField's weights.  At
    present, CFPOF_DivisiveNormalizeL1 and
    CFPOF_DivisiveNormalizeL1_opt do use norm_total; others can be
    extended to do something similar if necessary.

    To enable joint normalization, you can declare that all the
    incoming connections that should be normalized together each
    have a dest_port of:

    dest_port=('Activity','JointNormalize', 'AfferentGroup1'),

    Then all those that have this dest_port will be normalized
    together, as long as an appropriate TransferFn is being used.
    """

    joint_norm_fn = param.Callable(default=compute_joint_norm_totals,doc="""
        Function to use to compute the norm_total for each CF in each
        projection from a group to be normalized jointly.""")

    # JABALERT: Should check that whenever a connection is added to a
    # group, it has the same no of cfs as the existing connections.
    def start(self):
        self._normalize_weights(active_units_mask=False)

    # CEBALERT: rename active_units_mask and default to False
    def _normalize_weights(self,active_units_mask=True):
        """
        Apply the weights_output_fns for every group of Projections.

        If active_units_mask is True, only active units will have
        their weights normalized.
        """
        for key,projlist in self._grouped_in_projections('JointNormalize'):
            if key == None:
                normtype='Individually'
            else:
                normtype='Jointly'
                self.joint_norm_fn(projlist,active_units_mask)

            self.debug(normtype + " normalizing:")

            for p in projlist:
                p.apply_learn_output_fns(active_units_mask=active_units_mask)
                self.debug('  ',p.name)

    def learn(self):
        """
        Call the learn() method on every Projection to the Sheet, and
        call the output functions (jointly if necessary).
        """
        # Ask all projections to learn independently
        for proj in self.in_connections:
            if not isinstance(proj,Projection):
                self.debug("Skipping non-Projection "+proj.name)
            else:
                proj.learn()

        # Apply output function in groups determined by dest_port
        self._normalize_weights()

class JointNormalizingCFSheet_Continuous(JointNormalizingCFSheet):
    """
    CFSheet that runs continuously, with no 'resting' periods between pattern presentations.

    Note that learning occurs only when the time is a whole number.
    """
    def process_current_time(self):
        if self.new_input:
           self.new_input = False
           if(float(topo.sim.time()) % 1.0 == 0.0):
               #self.activate()
               if (self.plastic):
                   self.learn()
           #else:
           self.activate()

__all__ = list(set([k for k,v in locals().items() if isinstance(v,type) and issubclass(v,Sheet)]))


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Boletín de la Academia Nacional de Ciencias de Córdoba 27(4): 357 (1924)

#### Original name
Eurotium herbariorum var. fuegianum Speg.

### Remarks
null


text:
brushes.eraser = {
    stroke: function (canvas, points, color, opacity) {
        var radius = 1; // XXX: use brush size for radius! note that painter uses it context init! -> add flag for this case?

        // XXX: use points instead!
        //pointsInsideRadius = canvas.getPointsInside(radius, points.current);

        //if(pointsInsideRadius.length > 0) {
            //console.log(pointsInsideRadius);

            // TODO!
            //canvas.remove(pointsInsideRadius); // this should handle redraw automagically!
            // redraw -> take point neighbours in count when calculating bbox for redraw!

            // 1. get points and their neigbors
            // 2. calculate bbox
            // 3. get rid of removable points
            // 4. redraw all points remaining in the bbox and their neighbors outside
        //}
    }
};


text:
PKG_NAME = pinentry
PKG_VERS = 0.9.7
PKG_EXT = tar.bz2
PKG_DIST_NAME = $(PKG_NAME)-$(PKG_VERS).$(PKG_EXT)
PKG_DIST_SITE = ftp://ftp.gnupg.org/gcrypt/$(PKG_NAME)
PKG_DIR = $(PKG_NAME)-$(PKG_VERS)

HOMEPAGE = https://www.gnupg.org/related_software/pinentry/
COMMENT  = pinentry is a small collection of dialog programs that allow GnuPG to read passphrases and PIN numbers in a secure manner. There are versions for the common GTK and Qt toolkits as well as for the text terminal (Curses).
LICENSE  = LGPL

DEPENDS = cross/libassuan cross/libgpg-error cross/ncurses

GNU_CONFIGURE = 1
CONFIGURE_ARGS  = --enable-pinentry-curses --disable-pinentry-gtk2 --disable-pinentry-qt --without-x --with-gpg-error-prefix=$(STAGING_INSTALL_PREFIX)
CONFIGURE_ARGS += --with-libassuan-prefix=$(STAGING_INSTALL_PREFIX) --with-ncurses-include-dir=$(STAGING_INSTALL_PREFIX)

include ../../mk/spksrc.cross-cc.mk


text:
import {APPEND_POSTS,} from '../types';

export default posts => ({
    type: APPEND_POSTS,
    posts,
});


text:
import { IPromise } from 'angular';
import { $q } from 'ngimport';
import { flatten } from 'lodash';
import { API } from 'core/api/ApiService';
import { IPipeline } from 'core/domain/IPipeline';
import { IPipelineTemplateV2Collections } from 'core/domain/IPipelineTemplateV2';
import { IPipelineTemplateConfigV2 } from 'core/domain';
import { PipelineTemplateV2Service } from './v2/pipelineTemplateV2.service';

export interface IPipelineTemplate {
  id: string;
  selfLink?: string;
  metadata: ITemplateMetadata;
  protect: boolean;
  schema: string;
  source: string;
  stages: ITemplateStage[];
  variables: IVariableMetadata[];
}

export interface ITemplateMetadata {
  description: string;
  name: string;
  owner: string;
}

export interface IVariableMetadata {
  defaultValue?: any;
  description?: string;
  example?: string;
  group?: string;
  name: string;
  type: VariableType;
}

export type VariableType = 'int' | 'float' | 'list' | 'object' | 'string' | 'boolean';

export interface ITemplateStage {
  dependsOn: string[];
  id: string;
  name: string;
  type: string;
}

export interface IPipelineTemplateConfig extends Partial<IPipeline> {
  type: string;
  plan?: boolean;
  config?: {
    schema: string;
    pipeline: {
      name: string;
      application: string;
      pipelineConfigId?: string;
      template: {
        source: string;
      };
      variables?: { [key: string]: any };
    };
    configuration?: {
      inherit?: string[];
    };
  };
}

export interface IPipelineTemplatePlanResponse {
  errors: IPipelineTemplatePlanError[];
  message: string;
  status: string;
}

export interface IPipelineTemplatePlanError {
  severity: string;
  message: string;
  location: string;
  cause: string;
  suggestion: string;
  details: { [key: string]: string };
  nestedErrors: IPipelineTemplatePlanError[];
}

export class PipelineTemplateReader {
  public static getPipelineTemplateFromSourceUrl(
    source: string,
    executionId?: string,
    pipelineConfigId?: string,
  ): IPromise<IPipelineTemplate> {
    return API.one('pipelineTemplates')
      .one('resolve')
      .withParams({ source, executionId, pipelineConfigId })
      .get()
      .then((template: IPipelineTemplate) => {
        template.selfLink = source;
        return template;
      });
  }

  public static getPipelinePlan(
    config: IPipelineTemplateConfig | IPipelineTemplateConfigV2,
    executionId?: string,
  ): IPromise<IPipeline> {
    const urls = PipelineTemplateV2Service.isV2PipelineConfig(config)
      ? ['v2', 'pipelineTemplates', 'plan']
      : ['pipelines', 'start'];

    return API.one(...urls).post({ ...config, plan: true, executionId });
  }

  public static getPipelineTemplatesByScope = (scope: string): IPromise<IPipelineTemplate[]> => {
    return API.one('pipelineTemplates')
      .withParams({ scope })
      .get();
  };

  public static getPipelineTemplatesByScopes(scopes: string[]): IPromise<IPipelineTemplate[]> {
    return $q
      .all(scopes.map(this.getPipelineTemplatesByScope))
      .then(templates => flatten(templates))
      .then(templates => {
        templates.forEach(template => (template.selfLink = `spinnaker://${template.id}`));
        return templates;
      });
  }

  public static getPipelineTemplateConfig({
    name,
    application,
    source,
  }: {
    name: string;
    application: string;
    source: string;
  }): Partial<IPipelineTemplateConfig> {
    return {
      config: {
        schema: '1',
        pipeline: {
          name,
          application,
          template: { source },
        },
      },
    };
  }

  public static getV2PipelineTemplateList(): IPromise<IPipelineTemplateV2Collections> {
    return API.one('v2', 'pipelineTemplates', 'versions').get();
  }
}


text:
<?php

namespace OpenClassrooms\Bundle\CacheBundle\Tests\Cache;

use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\Cache\RedisCache;
use OpenClassrooms\Bundle\CacheBundle\Tests\Cache\CacheServer\RedisSpy;
use OpenClassrooms\Cache\CacheProvider\CacheProviderBuilder;
use OpenClassrooms\Cache\CacheProvider\CacheProviderBuilderImpl;
use OpenClassrooms\Cache\CacheProvider\CacheProviderType;
use OpenClassrooms\Cache\CacheProvider\Exception\InvalidCacheProviderTypeException;

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
class CacheProviderBuilderMock extends CacheProviderBuilderImpl
{
    /**
     * @return CacheProviderBuilder
     */
    public function create($cacheProviderType)
    {
        $this->cacheProviderType = $cacheProviderType;
        switch ($this->cacheProviderType) {

            case CacheProviderType::REDIS:
                $this->cacheProvider = new RedisCache();
                $this->server = new RedisSpy();
                break;
            case CacheProviderType::ARRAY_CACHE:
                $this->cacheProvider = new ArrayCache();
                break;
            default:
                throw new InvalidCacheProviderTypeException();
        }

        return $this;
    }
}