text:
Ext.define('Ozone.components.window.MyAppsWindow', {
    extend: 'Ozone.components.window.ModalWindow',
    alias: 'widget.myappswindow',

    closeAction: 'hide',
    modal: true,
    preventHeader: false,
    modalAutoClose: true,
    shadow: false,
    layout: 'auto',
    ui: 'system-window',
    store: null,
    closable: true,
    title: 'My Apps',
    cls: 'system-window',

    resizable: false,
    draggable: false,

    width: 780,
    height: 600,
    expandedHeight: 770,

    dashboardContainer: null,

    //dashboard unit sizes
    dashboardItemHeight: 0,
    dashboardItemWidth: 0,

    //size of switcher in dashboard units
    minDashboardsWidth: 0,
    maxDashboardsWidth: 6,
    maxDashboardsHeight: 3,

    maxStacksPerSlide: 18,
    numDashboardsNeededToExpandModal: 12,

    isAnAppExpanded: false,

    storeLengthChanged: true,

    selectedPageCls: 'dashboard-selected',
    selectedAppCls: 'stack-selected',

    _deletedStackOrDashboards: null,

    DROP_LEFT_CLS: 'x-view-drop-indicator-left',
    DROP_RIGHT_CLS: 'x-view-drop-indicator-right',

    _previouslyFocusedStackOrDashboard: null,
    _previouslyHoveredStackOrDashboard: null,

    dashboardSelectionDeferred: null,

    // flag to indicate whether person is dragging apps or pages
    _dragging: false,

    initComponent: function() {

        var me = this,
            stackOrDashboards = [],
            stacks = {}, dashboards = {},
            dashboard, stack, model;

        for(var i = 0, len = me.dashboardStore.getCount(); i < len; i++) {

            model = me.dashboardStore.getAt(i);

            if(!model.isModifiable() || (me.hideLockedDashboards && model.data.locked)) {
                continue;
            }

            dashboard = Ext.clone(model.data);
            dashboard.model = model;
            dashboards[ dashboard.guid ] = dashboard;

            stack = dashboard.stack;
            //console.log(i, ' => Dashboard name: ', dashboard.name, 'Stack: ', stack ? stack.name : 'none', ' Default: ', dashboard.isdefault);
            if( stack ) {
                if( stacks[ stack.id ] ) {
                    stacks[ stack.id ].dashboards.push( dashboard );
                }
                else {
                    stack = Ext.clone(stack);
                    stack.isStack = true;
                    stack.dashboards = [ dashboard ];

                    stacks[ stack.id ] = stack;
                    stackOrDashboards.push( stack );
                }
            }
            else {
                stackOrDashboards.push( dashboard );
            }

        }

        me.callParent(arguments);

        me.stackOrDashboards = stackOrDashboards;
        me.dashboards = dashboards;
        me.stacks = stacks;
        me._deletedStackOrDashboards = [];

        me.tpl = new Ext.XTemplate(
            '
Click to start an App. To edit or delete, hover over an app and select the information icon.
',
            '
',
                '<tpl for=".">',
                    '
',
                        '
',
                            '{[this.getIcon(values)]}',
                        '
',
                        '
',
                            '{[Ext.htmlEncode(values.name)]}',
                        '
',
                        '{[this.getActions(values)]}',
                    '
',
                '</tpl>',
            '
',
        {
            compiled: true,
            getId: function (values) {
                return values.isStack ? values.id : values.guid;
            },

            getClass: function (values) {
                var name = this.getName(values);
                return values.guid === me.activeDashboard.id ? name + ' ' + me.selectedPageCls: name;
            },

            getName: function (values) {
                return values.isStack ? 'stack' : 'dashboard';
            },

            getIcon: function(values) {
                var url = values.isStack ? values.imageUrl : values.iconImageUrl;

                if (url && !Ext.isEmpty(Ext.String.trim(url))) {
                    return '';
                } else {
                    return '

';
                }
            },

            getActions: function (values) {
                return	'

';

            }
        });

        me.stackDashboardsTpl = '
'+
                                    '

'+
                                    '

'+
                                '
';

        me.on('afterrender', function (cmp) {
            me.tpl.overwrite( cmp.body, stackOrDashboards );

            $('.stack-name').dotdotdot({
                ellipsis: '…'
            });

            Ext.DomHelper.append( cmp.body,
            '
'+
                '
'+
                	'
'+
                        '

'+
                        'Discover More'+
                    '
'+
            		'
'+
                        '

'+
                        'Create New'+
                    '
'+
                '
'+
            '
');

            cmp.actionsEl = cmp.body.select('> .actions').first();

            me.bindEvents(cmp);

            if (me.stackOrDashboards.length > 0) {
                me.slider = $('.all-dashboards').bxSlider({
                    oneItemPerSlide: false,
                    infiniteLoop: true,
                    touchEnabled: false,
                    onSlideNext: Ext.bind(function() {
                        me.onSlideTransition.apply(me, arguments);
                    }, me),
                    onSlidePrev: Ext.bind(function() {
                        me.onSlideTransition.apply(me, arguments);
                    }, me)
                });

                me.slider.disableSelection();
            }
        });

        me.on('beforeclose', me.onClose, me);
        me.on('show', me.verifyDiscoverMoreButton, me);
        me.on('show', me.initCircularFocus, me, {single: true});
        me.on('show', me.goToActiveStackSlide, me);
        me.on('show', me.focusActiveDashboard, me);
        me.mon(me.dashboardContainer, OWF.Events.Dashboard.CHANGED, me.onDashboardChanged, me);
    },

    bindEvents: function () {
        var me = this,
            $ = jQuery,
            $dom = $(me.el.dom),
            $doc = $(document);

        $dom
            .on('click', '.dashboard', $.proxy(me.onDashboardClick, me))
            .on('click', '.stack', $.proxy(me.onStackClick, me))
            .on('click', '.store-link-btn',  $.proxy(me.switchToMarketplace,me))
            .on('click', '.create-link-btn', $.proxy(me.createNewApp, me))
            .on('mouseover', '.stack, .dashboard', $.proxy(me.onMouseOver, me))
            .on('mouseout', '.stack, .dashboard', $.proxy(me.onMouseLeave, me))
            .on('focus', '.stack, .dashboard', $.proxy(me.onMouseOver, me))
            .on('blur', '.stack, .dashboard', $.proxy(me.onMouseLeave, me));

        me.initKeyboardNav();

        // drag and drop
        var $draggedItem,
            $draggedItemParent,
            $dragProxy,
            carousel
            isDraggingStackDashboard = false,
            isDropValid = true;

        // disable selection while dragging
        $dom
            .attr('unselectable', 'on')
            .css('user-select', 'none')
            .on('selectstart.reorder', false);

        // reorder dashboards
        $dom.on('mousedown', '.dashboard, .stack', function (evt) {
            evt.preventDefault();
            me._dragging = true;
            $draggedItem = $(this);
            $draggedItemParent = $draggedItem.parents('.stack-dashboards');

            isDraggingStackDashboard = $draggedItemParent.length === 1;

            $dragProxy = $draggedItem.clone().addClass('x-dd-drag-proxy drag-proxy');
            $('ul, .dashboard-name, .stack-name', $dragProxy).remove();
            $(document.body).append($dragProxy);

            // prevent tooltips from showing while drag n drop
            $dom.on('mouseover.reorder', '.dashboard, .stack', function (evt) {
                evt.preventDefault();
                evt.stopPropagation();
            });

            $doc.on('mousemove.reorder', function (evt) {
                evt.preventDefault();       // required for IE7
                var pageX = evt.pageX,      // The mouse position relative to the left edge of the document.
                    pageY = evt.pageY;      // The mouse position relative to the top edge of the document.

                $dragProxy.css({
                    left: pageX + 15,
                    top: pageY + 15
                });
            });

            $dom.one('mousemove.reorder', '.dashboard, .stack', function (evt) {
                var $el = $(this),
                    $parent;

                me._hideStackDashboardsOnMove($el);

                $parent = $el.parents('.stack-dashboards');

                // dragging pages in an application
                if($parent.length === 1) {
                    carousel = me.appPageCarousel;
                }
                // dragging application
                else {
                    $parent = $dom;
                    carousel = me.slider;
                }

                $parent.on('mousemove.reorder', '.bx-next', function (evt) {
                    carousel.goToNextSlide();
                });

                $parent.on('mousemove.reorder', '.bx-prev', function (evt) {
                    carousel.goToPrevSlide();
                });

                $doc.one('mouseup.reorder', function () {
                    $parent.off('.reorder');
                });
            });

            $dom.on('mousemove.reorder', '.dashboard, .stack', function (evt) {
                var $el = $(this);

                // only allow reordering if parents match and
                // prevent reordering stack dashboards outside of stack and vice versa.
                if(isDraggingStackDashboard && $el.parents('.stack-dashboards').length === 0) {
                    isDropValid = false;
                    return;
                }

                isDropValid = true;

                var pageX = evt.pageX,      // The mouse position relative to the left edge of the document.
                    pageY = evt.pageY,      // The mouse position relative to the top edge of the document.
                    offset = $el.offset(),  // The offset relative to the top left edge of the document.
                    width = $el.outerWidth();

                $el.removeClass(me.DROP_LEFT_CLS + ' ' + me.DROP_RIGHT_CLS);

                if( pageX <= offset.left + (width/2) ) {
                    $el.addClass(me.DROP_LEFT_CLS);
                }
                else {
                    $el.addClass(me.DROP_RIGHT_CLS);
                }
            });

            $dom.on('mouseout.reorder', '.dashboard, .stack', function (evt) {
                $(this).removeClass(me.DROP_LEFT_CLS + ' ' + me.DROP_RIGHT_CLS);
            });

            // drop performed on a dashboard
            $dom.on('mouseup.reorder', '.dashboard', function (evt) {
                isDropValid && me._dropOnDashboard($draggedItem, $(this));
            });

            // drop performed on a stack
            $dom.on('mouseup.reorder', '.stack', function (evt) {
                isDropValid && me._dropOnStack($draggedItem, $(this));
            });

            // cleanup on mouseup
            $doc.on('mouseup.reorder', function (evt) {
                me._dragging = false;
                $draggedItem =  null;
                $draggedItemParent = null;
                $dragProxy.remove();

                $doc.off('.reorder');
                $dom.off('.reorder');
            });
        });
    },

    getActiveStackId: function() {
        var me = this,
            stack = this.activeDashboard.configRecord.get('stack');
            stackId = stack ? stack.id : null;

        return stackId;
    },

    getActiveStackSlideIndex: function() {
        var me = this;

        var stackId = me.getActiveStackId(),
            $stackEl = $("#stack" + stackId, '.bx-slide:not(.bx-clone)'),
            $stackElSlide = $stackEl.parent(),
            slideIndexOfActiveStack = $('.bx-slide:not(.bx-clone)', me.el.dom).index($stackElSlide);

        return slideIndexOfActiveStack;
    },

    getActiveDashboardMiniSlideIndex: function() {
        if (this.getActiveStackId() == null || this.activeDashboard.configRecord.isMarketplaceDashboard()) {
            return;
        }

        var me = this,
            activeDashboardId = this.activeDashboard.id,
            $dashboardEl = $('#dashboard' + activeDashboardId, '.stack-dashboards .bx-slide:not(.bx-clone)'),
            $dashboardElSlide = $dashboardEl.parent(),
            slideIndexOfActiveDashboard = $('.bx-slide:not(.bx-clone)', '.stack-dashboards').index($dashboardElSlide);

        return slideIndexOfActiveDashboard;
    },

    goToActiveStackSlide: function() {
        var me = this;

        if (me.stackOrDashboards.length > 0) {
            if (!me.getActiveStackId() || me.activeDashboard.configRecord.isMarketplaceDashboard()) {
                me.slider.goToSlide(0);
            } else {
                me.slider.goToSlide(me.getActiveStackSlideIndex());
            }
        }
    },

    goToActiveDashboardSlideinMiniSlider: function() {
        var me = this;

        me.appPageCarousel.goToSlide(me.getActiveDashboardMiniSlideIndex());
    },

    onSlideTransition: function($slideElement, oldIndex, newIndex) {
        var me = this,
            stackId = me.getActiveStackId();

        if (stackId && me.slideHasActiveStack(newIndex, stackId) && me._dragging === false) {
            me.focusActiveDashboard();
        } else {
            me.hideStackDashboards();
        }
    },

    slideHasActiveStack: function(slideIndex) {
        return slideIndex === this.getActiveStackSlideIndex();
    },

    _hideStackDashboardsOnMove: function ($el) {
        // hide stack dashboards if moving root stack or dashboard
        if( $el.parents('.stack-dashboards').length === 0 ) {
            this.hideStackDashboards();
        }
    },

    initKeyboardNav: function () {
        var me = this;

        function move ($el, $moveToEl) {
            $moveToEl.hasClass('stack') ? me._dropOnStack($el, $moveToEl) : me._dropOnDashboard($el, $moveToEl);
        }

        function moveLeft () {
            //move item left
            var $this = $(this),
                $prev = $this.prev(),
                promise;

            if($prev.length === 1 && !$prev.hasClass('dashboard') && !$prev.hasClass('stack')) {
                $prev = $prev.prev();
            }

            if($prev.length === 0)
                return;

            $prev.addClass( me.DROP_LEFT_CLS );

            if(promise = me._hideStackDashboardsOnMove($this))
                promise.then(function () {
                    move($this, $prev);
                })
            else
                move($this, $prev);
        }

        function moveRight () {
            //move item right
            var $this = $(this),
                $next = $this.next(),
                promise;

            if($next.length === 1 && !$next.hasClass('dashboard') && !$next.hasClass('stack')) {
                $next = $next.next();
            }

            if($next.length === 0)
                return;

            $next.addClass( me.DROP_RIGHT_CLS );
            if(promise = me._hideStackDashboardsOnMove($this))
                promise.then(function () {
                    move($this, $next);
                })
            else
                move($this, $next);
        }

        $(me.el.dom)
            .on('keyup', '.stack', function (evt) {
                if(evt.which === Ext.EventObject.ENTER) {
                    me.onStackClick(evt);
                }
                //left bracket
                else if (evt.which == 219) {
                    moveLeft.call(this);
                }
                //right bracket
                else if (evt.which == 221) {
                    moveRight.call(this);
                }
            })
            .on('keyup', '.dashboard', function (evt) {
                if(evt.which === Ext.EventObject.ENTER) {
                    me.onDashboardClick(evt);
                }
                //left bracket
                else if (evt.which == 219) {
                    moveLeft.call(this);
                }
                //right bracket
                else if (evt.which == 221) {
                    moveRight.call(this);
                }
            })
            .on('blur', '.dashboard', function (evt) {
                me._previouslyFocusedStackOrDashboard = $(evt.currentTarget).removeClass(me.selectedPageCls);
            })
            .on('focus', '.dashboard-actions li, .stack-actions li', function (evt) {
                $(evt.currentTarget).addClass('hover');
            })
            .on('blur', '.dashboard-actions li, .stack-actions li', function (evt) {
                $(evt.currentTarget).removeClass('hover');
            })
            .on('keyup', '.dashboard-actions .share', function (evt) {
                if(evt.which === Ext.EventObject.ENTER) {
                    me.shareDashboard(evt);
                }
            })
//            .on('keyup', '.dashboard-actions .edit', function (evt) {
//                if(evt.which === Ext.EventObject.ENTER) {
//                    me.editDashboard(evt);
//                }
//            })
//            .on('keyup', '.dashboard-actions .delete', function (evt) {
//                if(evt.which === Ext.EventObject.ENTER) {
//                    me.deleteDashboard(evt);
//                }
//            })
            .on('keyup', '.stack-actions .restore', function (evt) {
                if(evt.which === Ext.EventObject.ENTER) {
                    me.restoreStack(evt);
                }
            })
            .on('keyup', '.stack-actions .delete', function (evt) {
                if(evt.which === Ext.EventObject.ENTER) {
                    me.deleteStack(evt);
                }
            })
            .on('focus', '.create', function (evt) {
                $(evt.currentTarget).addClass('selected');
            })
            .on('blur', '.create', function (evt) {
                $(evt.currentTarget).removeClass('selected');
            })
            .on('keyup', '.create', function (evt) {
                if(evt.which === Ext.EventObject.ENTER) {
                    me.createDashboard(evt);
                }
            });
    },

    _dropOnDashboard: function ($draggedItem, $dashboard) {
        var me = this,
            dashboard = me.getDashboard( $dashboard ),
            draggedItem;

        // dropped on the same element
        if($dashboard[0] === $draggedItem[0]) {
            $dashboard.removeClass(me.DROP_LEFT_CLS + ' ' + me.DROP_RIGHT_CLS);
            return;
        }

        var droppedLeft = $dashboard.hasClass(me.DROP_LEFT_CLS);
        var store = me.dashboardStore, newIndex, oldIndex;

        if ( droppedLeft ) {
            $dashboard.removeClass(me.DROP_LEFT_CLS);
            $draggedItem.insertBefore( $dashboard );
        }
        else {
            $dashboard.removeClass(me.DROP_RIGHT_CLS);
            $draggedItem.insertAfter( $dashboard );
        }

        // dropping dashboard on a dashboard
        if( $draggedItem.hasClass('dashboard') ) {

            draggedItem = me.getDashboard( $draggedItem );

            store.remove(draggedItem.model, true);

            var index = store.indexOf(dashboard.model);

            if ( !droppedLeft ) {
                index++;
            }

            store.insert(index, draggedItem.model);

            // if stack, reorder internal cache as well.
            if(draggedItem.stack) {
                var stack = me.stacks[draggedItem.stack.id];

                oldIndex = _.indexOf(stack.dashboards, draggedItem);
                newIndex = _.indexOf(stack.dashboards, dashboard);

                stack.dashboards.splice(newIndex, 0, stack.dashboards.splice(oldIndex, 1)[0]);

                // refresh carousel
                me.appPageCarousel.reloadSlider();
            }

        }
        else {
            // dropping stack on a dashboard

            draggedItem = me.getStack( $draggedItem );

            var stackDashboards = draggedItem.dashboards,
                stackDashboard;

            for(var i = 0, len = stackDashboards.length; i < len; i++) {
                stackDashboard = stackDashboards[i];
                store.remove(stackDashboard.model, true);
            }

            index = store.indexOf(dashboard.model);

            if ( !droppedLeft ) {
                index++;
            }

            for(var i = 0, len = stackDashboards.length; i < len; i++) {
                stackDashboard = stackDashboards[i];
                store.insert(index++, stackDashboard.model);
            }

        }

        // focusing dragged item breaks carousel in Firefox
        //$draggedItem.focus();

        me.initCircularFocus();
        me.reordered = true;
    },

    _dropOnStack: function ($draggedItem, $stack) {
        var me = this,
            stack = me.getStack( $stack ),
            draggedItem;

        // dropped on the same element
        if($stack[0] === $draggedItem[0]) {
            $stack.removeClass(me.DROP_LEFT_CLS + ' ' + me.DROP_RIGHT_CLS);
            return;
        }

        store = me.dashboardStore;

        var droppedLeft = $stack.hasClass(me.DROP_LEFT_CLS);
        var store = me.dashboardStore;

        // dropping dashboard on a stack
        if( $draggedItem.hasClass('dashboard') ) {

            draggedItem = me.getDashboard( $draggedItem );

            store.remove(draggedItem.model, true);

            var index;
            if ( droppedLeft ) {
                index = store.indexOf(stack.dashboards[0].model);
            }
            else {

                var $next = $stack.next();

                if($next.length === 1 && !$next.hasClass('stack-dashboards') && !$next.hasClass('stack')) {
                    $next = $next.next();
                }

                if( $next.length === 1) {

                    if( $next.hasClass('dashboard') ) {
                        var nextDash = me.getDashboard( $next );
                        index = store.indexOf(nextDash.model);
                    }
                    else {
                        // next item is a stack
                        // get the index of the first dashboard in the stack
                        var nextStack = me.getStack( $next );
                        index = store.indexOf(nextStack.dashboards[0].model);
                    }
                }
                else {
                    var lastStackDash = stack.dashboards[ stack.dashboards.length - 1 ];
                    index = store.indexOf(lastStackDash.model);
                    index++;
                }
            }

            store.insert(index, draggedItem.model);
        }
        else {
            // dropping stack on a stack
            draggedItem = me.getStack( $draggedItem );

            var stackDashboards = draggedItem.dashboards,
                stackDashboard;

            for(var i = 0, len = stackDashboards.length; i < len; i++) {
                stackDashboard = stackDashboards[i];
                store.remove(stackDashboard.model, true);
            }

            if ( droppedLeft ) {
                index = store.indexOf(stack.dashboards[0].model);
            }
            else {
                var $next = $stack.next();

                if( $next.length === 1) {
                    if( $next.hasClass('dashboard') ) {
                        var nextDash = me.getDashboard( $next );
                        index = store.indexOf(nextDash.model);
                    }
                    else {
                        // next item is a stack
                        // get the index of the first dashboard in the stack
                        var nextStack = me.getStack( $next );
                        index = store.indexOf(nextStack.dashboards[0].model);
                    }
                }
                else {
                    var lastStackDash = stack.dashboards[ stack.dashboards.length - 1 ];
                    index = store.indexOf(lastStackDash.model);
                    index++;
                }
            }

            for(var i = 0, len = stackDashboards.length; i < len; i++) {
                stackDashboard = stackDashboards[i];
                store.insert(index++, stackDashboard.model);
            }
        }

        if ( droppedLeft ) {
            $stack.removeClass(me.DROP_LEFT_CLS);
            $draggedItem.insertBefore( $stack );
        }
        else {
            $stack.removeClass(me.DROP_RIGHT_CLS);
            $draggedItem.insertAfter( $stack );
        }

        // focusing dragged item breaks carousel in Firefox
        //$draggedItem.focus();

        me.initCircularFocus();
        me.reordered = true;

        setTimeout(function() {

            me.slider.reloadSlider();

        }, 100);
    },

    initCircularFocus: function () {
        // var firstEl = this.body.down('.all-dashboards').first(),
        //     addBtnEl = this.body.down('.actions').last();

        // this.tearDownCircularFocus();
        // this.setupFocus(firstEl, addBtnEl);
    },

    focusActiveDashboard: function () {
        var me = this,
            activeDashboardId = this.activeDashboard.id,
            selectedEl = $('#dashboard'+activeDashboardId, '.bx-slide:not(.bx-clone)');

        // dashboard item view not found in switcher, active dashboard must be in a stack.
        // expand the stack, then focus the active dashboard
        if(selectedEl.length === 0) {
            var stackId, stack;

            stack = this.activeDashboard.configRecord.get('stack');
            stackId = stack ? stack.id : null;

            if (stack) {
                if (this.stacks[stackId]) {
                    this.toggleStack(this.stacks[stackId], $('#stack'+stackId, '.bx-slide:not(.bx-clone)')).then(function () {
                        me.goToActiveDashboardSlideinMiniSlider();
                        me.focusActiveDashboard();
                    });
                }
            }
            return;
        } else {
            selectedEl.addClass(me.selectedPageCls);
        }
    },

    getDashboard: function ($el) {
        return this.dashboards[ $el.attr('data-dashboard-id') ];
    },

    getStack: function ($el) {
        return this.stacks[ $el.attr('data-stack-id') ];
    },

    getElByClassFromEvent: function (evt, cls) {
        var $dashboard = $(evt.currentTarget || evt.target);
        return $dashboard.hasClass('cls') ? $dashboard : $dashboard.parents('.' + cls);
    },

    onDashboardClick: function (evt) {
        if (evt.type !== 'click' && evt.which !== Ext.EventObject.ENTER)
            return;

        var $clickedDashboard = $(evt.currentTarget),
        dashboard = this.getDashboard( $clickedDashboard );

        if ($(evt.target).hasClass('details-btn')) {
        	Ext.select('.itemTip').destroy();

        	Ext.widget('mypagetip', {
                clickedDashboard:dashboard,
                $dashboard: $clickedDashboard,
                dashboardContainer: this.dashboardContainer,
                appsWindow: this,
        		event:evt
        	}).showAt([evt.clientX,evt.clientY]);

        	return;
        } else {
            this.launchDashboard(evt, dashboard);
        }
    },

    launchDashboard: function(evt, dashboard) {
        var stackContext = dashboard.stack ? dashboard.stack.stackContext : null;

        this.dashboardSelectionDeferred && this.dashboardSelectionDeferred.resolve(evt, dashboard.guid);
        this.dashboardSelectionDeferred = null;

        this.activateDashboard(dashboard.guid, stackContext);
    },

    getDashboardSelectionPromise: function() {
        this.dashboardSelectionDeferred = this.dashboardSelectionDeferred || $.Deferred();
        return this.dashboardSelectionDeferred.promise();
    },

    onDashboardChanged: function() {
        var activeDashboardId = this.dashboardContainer.activeDashboard.id,
            $selectedDashboard = $('#dashboard'+activeDashboardId);

        $selectedDashboard.addClass( this.selectedItemCls );

        if( this._$lastSelectedDashboard ) {
            this._$lastSelectedDashboard.removeClass( this.selectedItemCls );
        }

        this._$lastSelectedDashboard = $selectedDashboard;
    },

    onStackClick: function (evt) {
        // evt.which == 1 => left mousedown
        if(evt.type === 'click' || evt.which === Ext.EventObject.ENTER) {
            var me = this,
                $ = jQuery,
                $clickedStack = $(evt.currentTarget),
                stack = me.getStack( $clickedStack );

            if ($(evt.target).hasClass('details-btn')) {
            	Ext.select('.itemTip').destroy();

            	Ext.widget('myapptip', {
            		clickedStack:stack,
                    dashboardContainer: me.dashboardContainer,
                    appsWindow: me,
            		event:evt
            	}).showAt([evt.clientX,evt.clientY]);

            	return;
            }

            if( stack ) {
                if (stack.dashboards && stack.dashboards.length === 1) {
                    me.launchDashboard(evt, stack.dashboards[0])
                } else {
                    me.toggleStack(stack, $clickedStack);
                }
            }

            evt.preventDefault();
        }
    },

    toggleStack: function (stack, $stack) {
        var me = this,
            dfd = $.Deferred();

        me.removeDeletedDashboard(stack);

        $('.' + me.selectedAppCls).removeClass(me.selectedAppCls);
        $stack.addClass(me.selectedAppCls);

        // don't expand stacks with one page/dashboard
        if (stack && stack.dashboards && stack.dashboards.length === 1) {
            return dfd.promise();
        }

        if( me._lastExpandedStack ) {

            if( me._lastExpandedStack === stack ) {
                return me.hideStackDashboards();
            }
            else {
                me.hideStackDashboards().then(function () {
                    me.showStackDashboards(stack, $stack, dfd);
                });
            }
        } else  {
            me.showStackDashboards(stack, $stack, dfd);
        }

        return dfd.promise();
    },

    removeDeletedDashboard: function(stack) {
        var me = this;
        var removeArrayElement = function(array, element) {
            var loc = array.indexOf(element);
            if (loc >= 0) {
                array.splice(loc, 1);
                return element
            }
            return null
        }

        // Remove just deleted dashboards from the stack
        if (me._deletedStackOrDashboards) {
            var clone = me._deletedStackOrDashboards.slice(0);
            jQuery.each (me._deletedStackOrDashboards, function(index, deletedDashboard) {
                if (removeArrayElement(stack.dashboards, deletedDashboard)) {
                    removeArrayElement(clone, deletedDashboard);
                }
            });
            me._deletedStackOrDashboards = clone;
        }

    },

    showStackDashboards: function (stack, $clickedStack, dfd) {
        var me = this,
            clickedStackElWidth = $clickedStack.outerWidth( true ),
            clickedStackElHeight = $clickedStack.outerHeight( true ),
            parent = $clickedStack.parent(),
            parentWidth = parent.outerWidth( true ),
            lastElInRow;

        $clickedStack.addClass(me.selectedAppCls);

        // get last element in the clikced stack's row
        var numItemsInRow = Math.round( parentWidth / clickedStackElWidth ),
            totalItems = $(parent).children('.dashboard, .stack').length,
            clickedStackIndex = $clickedStack.index() + 1;

        if( clickedStackIndex === totalItems || (clickedStackIndex % numItemsInRow) === 0 ) {
            lastElInRow = $clickedStack;
        }
        else {
            var i = clickedStackIndex;
            while( (i % numItemsInRow) !== 0 ) {
                i++;
                if( i >= totalItems ) {
                    break;
                }
            }
            lastElInRow = parent.children().eq(i-1);
        }

        // compile template and add to dom
        this.$stackDashboards = $( this.stackDashboardsTpl );
        this.$stackDashboards.children('.stack-dashboards').html( this.tpl.applyTemplate( stack.dashboards ) );
        this.$stackDashboards.insertAfter( lastElInRow );

        this.stackDashboardsAnchorTip = $( '.stack-dashboards-anchor-tip' , this.$stackDashboards );

        // cache size of tip
        if( !this.stackDashboardsAnchorTipHeight ) {
            this.stackDashboardsAnchorTipHeight = this.stackDashboardsAnchorTip.outerHeight();
        }
        if( !this.stackDashboardsAnchorTipWidth ) {
            this.stackDashboardsAnchorTipWidth = this.stackDashboardsAnchorTip.outerWidth();
        }

        this.$stackDashboards.hide();

        // calculate top and left value for anchor tip
        var parentPosition = $clickedStack.position(),
            top = parentPosition.top + clickedStackElHeight - (this.stackDashboardsAnchorTipHeight),
            left = parentPosition.left + (clickedStackElWidth / 2) - (this.stackDashboardsAnchorTipWidth / 2);

        this.stackDashboardsAnchorTip.css({
            left: left + 'px'
        });

        if (totalItems > me.numDashboardsNeededToExpandModal) {
            me.expandModal(parent);
        }

        me.isAnAppExpanded = true;

        if(Ext.isIE7 || Ext.isIE8) {
            this.$stackDashboards.show();
            dfd.resolve();
        }
        else {
            this.$stackDashboards.slideDown('fast').promise().then(function () {
                dfd.resolve();
            });
        }

        me.buildAppPageCarousel(me.$stackDashboards);

        this._lastExpandedStack = stack;
    },

    buildAppPageCarousel: function($stackDashboardContainer) {
        var me = this;

        if (me.appPageCarousel) {
            me.appPageCarousel.enableSelection().destroySlider();
        }

        me.appPageCarousel = $('.all-dashboards', $stackDashboardContainer).bxSlider({
            oneItemPerSlide: false,
            infiniteLoop: true,
            touchEnabled: false
        });

        $('.dashboard-name').dotdotdot({
            ellipsis: '…'
        });

        if (me.appPageCarousel.getSlideCount() === 1) {
            $('.bx-pager', '.stack-dashboards').hide();
            $('.stack-dashboards').addClass('one-slide');
        }

        me.appPageCarousel.disableSelection();
    },

    expandModal: function(containerSlide) {
        var me = this;

        me.normalModalHeight = me.height;

        me.setHeight(me.expandedHeight);
        $('.bx-wrapper, .bx-viewport', me.el.dom).addClass('expanded');
    },

    collapseModal: function(containerSlide) {
        var me = this;

        me.setHeight(me.normalModalHeight || me.getHeight());
        $('.bx-wrapper, .bx-viewport', me.el.dom).removeClass('expanded');
    },

    hideStackDashboards: function () {
        var me = this;
        if(!this.$stackDashboards) {
            var dfd = $.Deferred();
            dfd.resolve();
            return dfd.promise();
        }

        me.isAnAppExpanded = false;

        $('.stack-selected', '.bx-slide:not(.bx-clone)').removeClass(me.selectedAppCls);

        if(Ext.isIE7 || Ext.isIE8) {
            var dfd = $.Deferred();
            this.$stackDashboards && this.$stackDashboards.hide();
            dfd.resolve();

            this.$stackDashboards.remove();

            me.collapseModal();
            this._lastExpandedStack = null;

            return dfd.promise();
        }
        else {
            var promise = this.$stackDashboards.slideUp('fast').promise();
            promise.then(function () {
                me.collapseModal();
                me.$stackDashboards.remove();
                me._lastExpandedStack = null;
            });
            return promise;
        }
    },

    onMouseOver: function (evt) {
        var el = $(evt.currentTarget);

        if (this._previouslyHoveredStackOrDashboard != null) {
            $('.details-btn', this._previouslyHoveredStackOrDashboard).addClass('hide');
        }

        $('.details-btn', el).removeClass('hide');

        this._previouslyHoveredStackOrDashboard = el;
    },

    onMouseLeave: function(evt) {
        var el = $(evt.currentTarget);

        if (this._previouslyHoveredStackOrDashboard) {
            $('.details-btn', this._previouslyHoveredStackOrDashboard).addClass('hide');
        }
    },

    updateDashboardEl: function ($dashboard, dashboard) {
        var $el = $(this.tpl.apply([dashboard])).before($dashboard);
        $el.fadeOut();
        $('.dashboard-name', $dashboard).text(dashboard.name)
        $el.fadeIn();
    },

    updateStackDashboardsEl: function (stack) {
    	if(this.$stackDashboards) {
    		this.$stackDashboards.children('.dashboards').html( this.tpl.applyTemplate( stack.dashboards ) )
    	}
    },

    switchToMarketplace: function() {
        var banner = this.dashboardContainer.getBanner()
        banner.getMarketplaceLauncher().gotoMarketplace(banner.marketplaceWidget, null);
        this.close();
    },

    verifyDiscoverMoreButton: function() {
        var discoverMoreButton = $('.store-link-btn');
        var marketBtn = $('.marketBtn');

        if(marketBtn && $(marketBtn).is(':visible')) {
        	discoverMoreButton.show();
        } else {
        	discoverMoreButton.hide();
        }
    },

//    restoreDashboard: function (evt) {
//        evt.stopPropagation();
//        var me = this,
//            $dashboard = this.getElByClassFromEvent(evt, 'dashboard'),
//            dashboard = this.getDashboard($dashboard),
//            dashboardGuid = dashboard.guid;
//
//        this.warn('This action will return the dashboard ' + Ext.htmlEncode(dashboard.name) + ' to its current default state. If an administrator changed the dashboard after it was assigned to you, the default state may differ from the one that originally appeared in your Switcher.', function () {
//            Ext.Ajax.request({
//                url: Ozone.util.contextPath() + '/dashboard/restore',
//                params: {
//                    guid: dashboardGuid,
//                    isdefault: dashboardGuid == me.activeDashboard.guid
//                },
//                success: function(response, opts) {
//                    var json = Ext.decode(response.responseText);
//                    if (json != null && json.data != null && json.data.length > 0) {
//                        me.notify('Restore Dashboard', '' + Ext.htmlEncode(dashboard.name) + ' is restored successfully to its default state!');
//
//                        var name = json.data[0].name,
//                            description = json.data[0].description;
//
//                        dashboard.model.set({
//                            'name': name,
//                            'description': description
//                        });
//                        dashboard.name = name;
//                        dashboard.description = name;
//
//                        me.updateDashboardEl($dashboard, dashboard);
//
//                        me.reloadDashboards = true;
//                    }
//                },
//                failure: function(response, opts) {
//                    Ozone.Msg.alert('Dashboard Manager', "Error restoring dashboard.", function() {
//                        Ext.defer(function() {
//                            $dashboard[0].focus();
//                        }, 200, me);
//                    }, me, null, me.dashboardContainer.modalWindowManager);
//                    return;
//                }
//            });
//        }, function () {
//            evt.currentTarget.focus();
//        });
//    },

    shareDashboard: function (evt) {
        evt.stopPropagation();

        var $dashboard = this.getElByClassFromEvent(evt, 'dashboard'),
            dashboardGuid = this.getDashboard($dashboard).guid,
            dashboardIndex = this.dashboardContainer.dashboardStore.find('guid', dashboardGuid),
            dashboard = this.dashboardContainer.dashboardStore.getAt(dashboardIndex).data,
            dashboardModel = dashboard.model;

        //If exporting the current dashboard, regenerate the json to ensure changes
        //not yet pushed to the server are in the exported json
        if(this.dashboardContainer.activeDashboard.configRecord.data.guid === dashboard.guid) {
            dashboard = this.dashboardContainer.activeDashboard.getJson();
        }

        // delete model before cloning to remove circular refs
        delete dashboard.model;
        var cloneDashboard = Ozone.util.cloneDashboard(dashboard, false, true);

        // reset dashboard model
        dashboard.model = dashboardModel;

        // Stop unload event from firing long enough to submit form.
        // Have to do this because the form submit triggers the window's unload event
        // which causes competing requests.  (SEE OWF-4280)
        Ext.EventManager.un(window, 'beforeunload', this.dashboardContainer.onBeforeUnload);

        var elForm = document.createElement('form');
        var elInput = document.createElement('input');
        elInput.id = 'json';
        elInput.name = 'json';
        elInput.type = 'hidden';
        elInput.value = Ext.JSON.encode(cloneDashboard);
        elForm.appendChild(elInput);
        elForm.action = Ozone.util.contextPath() + '/servlet/ExportServlet';
        elForm.method = 'POST';
        elForm.enctype = elForm.encoding = 'multipart/form-data';
        document.body.appendChild(elForm);
        elForm.submit();
        document.body.removeChild(elForm);
        elForm = null;
        elInput = null;
        var dmScope = this;
        setTimeout(function() {
            Ext.EventManager.on(window, 'beforeunload', dmScope.dashboardContainer.onBeforeUnload, dmScope.dashboardContainer);
        }, 100);
    },

    createNewApp: function (evt) {
        var me = this,
            createDashWindow = Ext.widget('createdashboardwindow', {
                stackId: null,
                title: Ozone.ux.DashboardMgmtString.createNewAppTitle,
                headerText: Ozone.ux.DashboardMgmtString.createNewAppHeader,
                itemId: 'createDashWindow',
                dashboardContainer: me.dashboardContainer,
                ownerCt: me.dashboardContainer
            });

        createDashWindow.show();
        me.close();
    },

    createDashboard: function (evt) {
        var me = this,
            createDashWindow = Ext.widget('createdashboardwindow', {
                createNewApp: false,
                title: Ozone.ux.DashboardMgmtString.createNewPageTitle,
                headerText: Ozone.ux.DashboardMgmtString.createNewPageHeader,
                itemId: 'createDashWindow',
                dashboardContainer: me.dashboardContainer,
                ownerCt: me.dashboardContainer
            });

        createDashWindow.show();
        me.close();
    },

    restoreStack: function (evt) {
        evt.stopPropagation();
        var me = this,
            $stack = this.getElByClassFromEvent(evt, 'stack'),
            stack = this.getStack($stack);

        this.warn('This action will return the application ' + Ext.htmlEncode(stack.name) + ' to its current default state. If an administrator changed any page in the application after it was assigned to you, the default state may differ from the one that originally appeared in your Switcher.', function () {
            Ext.Ajax.request({
                url: Ozone.util.contextPath() + '/stack/restore',
                params: {
                    id: stack.id
                },
                success: function(response, opts) {
                    var json = Ext.decode(response.responseText);

                    if (json != null && json.updatedDashboards != null && json.updatedDashboards.length > 0) {
                        me.notify('Restore Application', '' + Ext.htmlEncode(stack.name) + ' is restored successfully to its default state!');

                        var dashboards = stack.dashboards;
                        for(var i = 0; i < dashboards.length; i++) {
                        	for(var j = 0; j < json.updatedDashboards.length; j++) {
                        		var dash = json.updatedDashboards[j];
                        		if(dash.guid == dashboards[i].guid) {
                        			dashboards[i].model.set({
                                        'name': dash.name,
                                        'description': dash.description
                                    });
                                    dashboards[i].name = dash.name;
                                    dashboards[i].description = dash.description;
                        		}
                        	}
                        }

                        me.updateStackDashboardsEl(stack);
                        me.reloadDashboards = true;
                        $stack.focus();
                    }
                },
                failure: function(response, opts) {
                    Ozone.Msg.alert('Page Manager', "Error restoring application.", function() {
                        Ext.defer(function() {
                            $stack[0].focus();
                        }, 200, me);
                    }, me, null, me.dashboardContainer.modalWindowManager);
                    return;
                }
            });
        }, function () {
            evt.currentTarget.focus();
        });
    },

    warn: function (msg, okFn, cancelFn) {
        Ext.widget('alertwindow',{
            title: "Warning",
            html:  msg,
            minHeight: 115,
            dashboardContainer: this.dashboardContainer,
            okFn: okFn,
            cancelFn: cancelFn,
            cls: 'alert-window-widget',
            showCancelButton: !!cancelFn
        }).show();
    },

    notify: function  (title, msg, type /* default is success*/) {
        var stack_bottomright = {"dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25};
        $.pnotify({
            title: title,
            text: msg,
            type: type || 'success',
            addclass: "stack-bottomright",
            stack: stack_bottomright,
            history: false,
            sticker: false,
            icon: false,
            delay: 3000
        });
    },

    activateDashboard: function (guid, stackContext) {
        this.close();
        this.dashboardContainer.activateDashboard(guid, false, stackContext);
    },

    updateWindowSize: function() {
        var newWidth,
            newHeight,
            dashboards = this.body.select('> .all-dashboards').first(),
            item = dashboards.first().dom, //first dashboard/stack
            header = this.header;

        if(!item)
            return;

        var itemEl = Ext.get(item),
            windowEl = this.getEl(),
            widthMargin = itemEl.getMargin('lr'),
            heightMargin = itemEl.getMargin('tb'),
            totalDashboards = dashboards.query('> .dashboard, > .stack').length,
            dashboardInRow = 0;

        this.dashboardItemWidth = itemEl.getWidth();
        this.dashboardItemHeight = itemEl.getHeight();

        if(totalDashboards < this.minDashboardsWidth) {
            dashboardInRow = this.minDashboardsWidth;
        }
        else if (totalDashboards > this.maxDashboardsWidth) {
            dashboardInRow = this.maxDashboardsWidth;
        }
        else {
            dashboardInRow = totalDashboards;
        }

        newWidth = (this.dashboardItemWidth + widthMargin + 1) * dashboardInRow;

        if(totalDashboards > this.maxDashboardsWidth * this.maxDashboardsHeight) {
            // add 30 to accomodate for scrollbar
            newWidth += 30;
        }

        newHeight = (this.dashboardItemHeight + heightMargin) * this.maxDashboardsHeight;

        this.body.setSize(newWidth + 30);

        //the extra 70 is for the stack row's triangle thing
        dashboards.setStyle('max-height', newHeight - this.actionsEl.getHeight() + 70 + 'px');

        //relayout header to account for new size.
        //suspend layout of this component so header layout doesn't resize the
        //whole window
        this.suspendLayout = true;
        header.doComponentLayout(this.getWidth());
        this.suspendLayout = false;
    },

    saveDashboardOrder: function () {
        var dfd = $.Deferred();
        var gridData = this.dashboardStore.data.items;
        var viewsToUpdate = [];
        var viewGuidsToDelete = [];

        for (var i = 0; i < gridData.length; i++) {
            if (!gridData[i].data.removed) {
                viewsToUpdate.push({
                    guid: gridData[i].data.guid,
                    isdefault: gridData[i].data.isdefault,
                    name: gridData[i].data.name.replace(new RegExp(Ozone.lang.regexLeadingTailingSpaceChars), '')
                });
            } else {
                viewGuidsToDelete.push(gridData[i].data.guid);
            }
        }

        Ozone.pref.PrefServer.updateAndDeleteDashboards({
            viewsToUpdate: viewsToUpdate,
            viewGuidsToDelete: viewGuidsToDelete,
            updateOrder: true,
            onSuccess: function() {
                dfd.resolve();
            },
            onFailure: function() {
                dfd.reject();
            }
        });

        return dfd.promise();
    },

    onClose: function() {
        var me = this;

        Ext.select('.itemTip').destroy();

        //me.tearDownCircularFocus();

        this.dashboardSelectionDeferred && this.dashboardSelectionDeferred.state() == "pending" && this.dashboardSelectionDeferred.reject();
        this.dashboardSelectionDeferred = null;

        // refresh if user deleted all dashboards
        if(me.dashboardContainer.dashboardStore.getCount() === 0) {
            window.location.reload();
            return;
        }

        if (me.reordered) {
            if(me.reloadDashboards) {
                me.saveDashboardOrder().always(function () {
                    me.dashboardContainer.reloadDashboards();
                });
            }
            else {
                me.saveDashboardOrder().fail(function () {
                    me.dashboardContainer.reloadDashboards();
                });
            }
        }
        else if(me.reloadDashboards === true) {
            me.dashboardContainer.reloadDashboards();
        }
    },

    destroy: function () {
        this.tearDownCircularFocus();

        // remove jQuery listeners
        if (this.el && this.el.dom) {
            $(this.el.dom).off();
        }

        // destroy view so that it will be recreated when opened next setTimeout
        return this.callParent();
    },
    hideButton: function(className) {
        var $ = jQuery;

        $(className).hide();
    },

    showButton: function(className) {
        var $ = jQuery;

        $(className).show();
    },

    removeStackOrDashboard: function(stack){
    	var $ = jQuery;
    	$("div[id='stack" + stack.id + "']").remove();
    }
});


text:
<?php

namespace edofre\fullcalendarscheduler\models;

/**
 * Class Event
 * @package edofre\fullcalendarscheduler\models
 */
class Event extends CalendarModel
{
    /** Rendering options */
    const RENDERING_BACKGROUND = 'background';
    const RENDERING_INVERSE_BACKGROUND = 'inverse-background';

    /** @var  string Uniquely identifies the given event. Different instances of repeating events should all have the same id. */
    public $id;
    /** @var  string The identifier for the specified resource, attaches this event to the specified resource */
    public $resourceId;
    /** @var  string The text on an event's element */
    public $title;
    /** @var  boolean Whether an event occurs at a specific time-of-day. This property affects whether an event's time is shown. Also, in the agenda views, determines if it is displayed in the "all-day" section. */
    public $allDay;
    /** @var  string The date/time an event begins. A Moment-ish input, like an ISO8601 string. Throughout the API this will become a real Moment object. */
    public $start;
    /** @var  string The exclusive date/time an event ends. A Moment-ish input, like an ISO8601 string. Throughout the API this will become a real Moment object. */
    public $end;
    /** @var  string A URL that will be visited when this event is clicked by the user. For more information on controlling this behavior, see the eventClick callback. */
    public $url;
    /** @var  string|array A CSS class ( or array of classes) that will be attached to this event's element. */
    public $className;
    /** @var  boolean Is the Event editable? Both start and duration. */
    public $editable;
    /** @var  boolean Is the event start editable? */
    public $startEditable;
    /** @var  boolean Is the event duration editable? */
    public $durationEditable;
    /** @var  string Allows alternate rendering of the event, like background events. Can be empty, "background", or "inverse-background" */
    public $rendering;
    /** @var  boolean  Overrides the master eventOverlap option for this single event. If false, prevents this event from being dragged/resized over other events. Also prevents other events from being dragged/resized over this event. */
    public $overlap;
    /** @var  string an event ID, "businessHours", object. Optional. Overrides the master eventConstraint option for this single event. */
    public $constraint;
    /** @var  string Event Source Object. Automatically populated. A reference to the event source that this event came from. */
    public $source;
    /** @var  string Sets an event's background and border color just like the calendar-wide eventColor option. */
    public $color;
    /** @var  string Sets an event's background color just like the calendar-wide eventBackgroundColor option. */
    public $backgroundColor;
    /** @var  string Sets an event's border color just like the the calendar-wide eventBorderColor option. */
    public $borderColor;
    /** @var  string Sets an event's text color just like the calendar-wide eventTextColor option. */
    public $textColor;

    /**
     * @return array
     */
    public function rules()
    {
        return [
            [['title', 'start'], 'required'],
            [['id', 'end', 'url', 'className', 'rendering', 'constraint', 'source', 'color', 'backgroundColor', 'borderColor', 'textColor'], 'safe'],
            [['editable', 'startEditable', 'durationEditable', 'overlap'], 'boolean'],
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:paddingLeft="@dimen/activity_horizontal_margin"
	android:paddingRight="@dimen/activity_horizontal_margin"
	android:paddingTop="@dimen/activity_vertical_margin"
	android:paddingBottom="@dimen/activity_vertical_margin"
	app:layout_behavior="@string/appbar_scrolling_view_behavior"
	tools:showIn="@layout/activity_main"
	tools:context=".MainActivity">

	<ScrollView
		android:orientation="vertical"
		android:layout_width="match_parent"
		android:layout_height="wrap_content">

		<LinearLayout
			android:layout_width="match_parent"
			android:layout_height="match_parent"
			android:orientation="vertical">

			<Button
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_gravity="center_horizontal"
				android:layout_marginTop="16dp"
				android:onClick="enableCamera"
				android:text="Enable camera"
				/>

			<Button
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_gravity="center_horizontal"
				android:layout_marginTop="16dp"
				android:onClick="enableLocation"
				android:text="Enable Location"
				/>
			<Button
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_gravity="center_horizontal"
				android:layout_marginTop="16dp"
				android:onClick="readContacts"
				android:text="Enable read contacts"
				/>
			<Button
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_gravity="center_horizontal"
				android:layout_marginTop="16dp"
				android:onClick="readCalendar"
				android:text="Enable read calendar"
				/>
			<Button
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_gravity="center_horizontal"
				android:layout_marginTop="16dp"
				android:onClick="requestAll"
				android:text="Request all disabled permissions"
			/>

			<Button
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_gravity="center_horizontal"
				android:layout_marginTop="16dp"
				android:onClick="requestEach"
				android:text="Request each disabled permissions"
				/>
		</LinearLayout>
	</ScrollView>
</RelativeLayout>


text:
section.features .icon-red i {
  background-image: linear-gradient(to left, #555555, #ff0000);
}
section.features .icon-black i {
  background-image: linear-gradient(to left, #121213, #000000);
}
section.features .icon-orange i {
  background-image: linear-gradient(#e66000, #e66000);
}
.icon-orange .text-muted {
  color: #ffffff !important;
}
.bg-blue {
  background: #0066ff;
  background: -webkit-linear-gradient(#0066ff, #222222);
  background: linear-gradient(#0066ff, #222222);
  color: #eeeeee;
}
section.contact ul.list-social li.social-github a {
  background-color: #333333;
}
section.contact ul.list-social li.social-github a:hover {
  color: #333333;
  background-color: #f5f5f5;
}
section.contact ul.list-social li.social-linkedin a {
  background-color: #0077b5;
}
section.contact ul.list-social li.social-linkedin a:hover {
  background-color: #00a0dc;
}
section.contact ul.list-social li.social-telegram a {
  background-color: #0088cc;
}
.error-message {
  color: #ff0000;
  font-weight: bold;
  text-decoration: underline;
}
.text-muted {
  color: #51575d !important;
}
.col-centered {
  margin: 0 auto;
}
.img-avatar {
  height: 35px;
  margin: 0 10px;
  border-radius: 50em;
  vertical-align: middle;
  border-style: none;
}
.nav-item {
  height: 55px;
}
.inline-item {
  display: inline;
}
.form_inline_item .form-group {
  display: inline;
}
.cursor-pointer {
  cursor: pointer;
}
.underlined {
  text-decoration: line-through;
}
.pt-1em {
  padding-top: 1em;
}
#lectureFilterInput {
  width: 100%;
  background-image: url('../img/search.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}


text:
Controller Interface Transport Protocol Library
===============================================

Library to allow easy use of the Controller Interface Transport Protcol (CITP) used in the Capture lighting visualizer.
Started by John Warwick, originally based on the Qt 4.5 framework, ported to standard c++ and wxwidgets.

This code is written to exercise a [Wireshark](http://wireshark.org) protocol dissector, but might be more generally useful if you want to stream data to a lighting visualizer.

Complete protocol documentation available at [CITP-Protocol.org](http://www.citp-protocol.org/).

License
-------

All code is MIT licensed. See license.txt for details.


text:
var PushNotifications = (function () {
    function PushNotifications(push) {
        this.pushNotification = push;
        this.setup();
    }
    PushNotifications.prototype.setup = function () {
        if (device.platform == 'android' || device.platform == 'Android') {
            console.log(device);
            this.pushNotification.register(this.successHandler, this.errorHandler, {
                "senderID": "750800674534",
                "ecb": "onNotificationGcm"
            });
        } else {
            this.pushNotification.register(this.tokenHandler, this.errorHandler, {
                "badge": "true",
                "sound": "true",
                "alert": "true",
                "ecb": "onNotificationApn"
            });
        }
    };

    PushNotifications.prototype.successHandler = function (result) {
        console.log(result);
        alert('result = ' + result);
    };

    PushNotifications.prototype.errorHandler = function (error) {
        alert('error = ' + error);
    };

    PushNotifications.prototype.tokenHandler = function (result) {
        // Your iOS push server needs to know the token before it can push to this device
        // here is where you might want to send it the token for later use.
        alert('device token = ' + result);
    };

    // iOS
    PushNotifications.prototype.onNotificationApn = function (event) {
        if (event.alert) {
            navigator.notification.alert(event.alert);
        }

        if (event.sound) {
            var snd = new Media(event.sound);
            snd.play();
        }

        if (event.badge) {
            this.pushNotification.setApplicationIconBadgeNumber(this.successHandler, this.errorHandler, event.badge);
        }
    };

    return PushNotifications;
})();

function onNotificationGcm(e) {
    console.log('onNotificationGcm: ' + JSON.stringify(e));

    console.log('
EVENT -> RECEIVED:' + e.event + '
');

    switch (e.event) {
        case 'registered':
            if (e.regid.length > 0) {
                // Your GCM push server needs to know the regID before it can push to this device
                // here is where you might want to send it the regID for later use.
                console.log('regID = ' + e.regid);
                $.get( 'http://10.50.15.67:3001/u/register/' + e.regid, function( data ) {
                    console.log( 'Register was performed.' );
                });
            }
            break;

        case 'message':
            // if this flag is set, this notification happened while we were in the foreground.
            // you might want to play a sound to get the user's attention, throw up a dialog, etc.
            if (e.foreground) {
                // if the notification contains a soundname, play it.
                alert(e.payload.message);
            } else {
                if (e.coldstart) {
                    console.log('
--COLDSTART NOTIFICATION--' + '
');
                } else {
                    console.log('
--BACKGROUND NOTIFICATION--' + '
');
                }
            }

            console.log('
MESSAGE -> MSG: ' + e.payload.message + '
');
            console.log('
MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '
');
            break;

        case 'error':
            console.log('
ERROR -> MSG:' + e.msg + '
');
            break;

        default:
            console.log('
EVENT -> Unknown, an event was received and we do not know what it is
');
            break;
    }
}


text:
package com.tdunning.math.stats;

import org.apache.mahout.common.RandomUtils;
import org.junit.Before;
import org.junit.Test;

public class AVLGroupTreeTest extends AbstractTest {

    @Before
    public void setUp() {
        RandomUtils.useTestSeed();
    }

    @Test
    public void testSimpleAdds() {
        AVLGroupTree x = new AVLGroupTree(false);
        assertEquals(IntAVLTree.NIL, x.floor(34));
        assertEquals(IntAVLTree.NIL, x.first());
        assertEquals(IntAVLTree.NIL, x.last());
        assertEquals(0, x.size());
        assertEquals(0, x.sum());

        x.add(new Centroid(1));
        assertEquals(1, x.sum());
        Centroid centroid = new Centroid(2);
        centroid.add(3, 1);
        centroid.add(4, 1);
        x.add(centroid);

        assertEquals(2, x.size());
        assertEquals(4, x.sum());
    }

    @Test
    public void testBalancing() {
        AVLGroupTree x = new AVLGroupTree(false);
        for (int i = 0; i < 101; i++) {
            x.add(new Centroid(i));
        }

        assertEquals(101, x.size());
        assertEquals(101, x.sum());

        x.checkBalance();
        x.checkAggregates();
    }

    @Test
    public void testFloor() {
        // mostly tested in other tests
        AVLGroupTree x = new AVLGroupTree(false);
        for (int i = 0; i < 101; i++) {
            x.add(new Centroid(i / 2));
        }

        assertEquals(IntAVLTree.NIL, x.floor(-30));

        for (Centroid centroid : x) {
            assertEquals(centroid.mean(), x.mean(x.floor(centroid.mean() + 0.1)), 0);
        }
    }

    @Test
    public void testHeadSum() {
        AVLGroupTree x = new AVLGroupTree(false);
        for (int i = 0; i < 1000; ++i) {
            x.add(randomDouble(), randomIntBetween(1, 10), null);
        }
        long sum = 0;
        long last = -1;
        for (int node = x.first(); node != IntAVLTree.NIL; node = x.next(node)) {
            assertEquals(sum, x.headSum(node));
            sum += x.count(node);
            last = x.count(node);
        }
        assertEquals(last, x.count(x.last()));
    }

    @Test
    public void testFloorSum() {
        AVLGroupTree x = new AVLGroupTree(false);
        int total = 0;
        for (int i = 0; i < 1000; ++i) {
            int count = randomIntBetween(1, 10);
            x.add(randomDouble(), count, null);
            total += count;
        }
        assertEquals(IntAVLTree.NIL, x.floorSum(-1));
        for (long i = 0; i < total + 10; ++i) {
            final int floorNode = x.floorSum(i);
            assertTrue(x.headSum(floorNode) <= i);
            final int next = x.next(floorNode);
            assertTrue(next == IntAVLTree.NIL || x.headSum(next) > i);
        }
    }

}


text:
 - Rename environment variable `CONSUL_ADDRESS` to `CONSUL_HTTP_ADDR` to be compliant with Consul naming

## v1.1.0

### Features

 - Release Alpine 3.6

## v1.0.4 (May 04, 2017)

### Bugs

- Fix trailing carriage return  in variables registered as container environment variables

## v1.0.3 (April 20, 2017)

### Improvements

  - Use su-exec to run consul-template with a user

## v1.0.2 (April 19, 2017)

### Packages installed

The following package has been added:
  - `su-exec`

## v1.0.1 (April 13, 2017)

### Environment Variables

The following environment variable have been added:
  - `EC2_IP`: Defines the IP of the EC2 instance when the container is running on AWS.
  - `CONSUL_HTTP_ADDR`: The address of Consul agent. This variable is inferred from `EC2_IP` and the Consul port is the HTTP port (`8500`).
  It's possible to define another port with the variable `CONSUL_PORT`

## v1.0.0 (April 2, 2017)

### Packages installed

The following packages are installed:
  - `curl`
  - `wget`
  - `bash`
  - `tree`
  - `jq` (since version 3.5)
  - `bind-tools` (since version 3.5)
  - `consul` (since version 3.5)

### Services installed

The following services runs by default when a container is created:
  - `GoDNSMasq`: For DNS records resolution
  - `Consul Template`: For managing configuration

### Environment Variables

The following environment variable is set:
  - `NPROC`: Defines the number of CPU cores


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using RawRabbit.IntegrationTests.TestMessages;
using RawRabbit.Operations.Request.Middleware;
using Xunit;

namespace RawRabbit.IntegrationTests.Rpc
{
	public class RpcFundamentalTests
	{
		[Fact]
		public async Task Should_Return_Respose_Without_Any_Additional_Configuration()
		{
			using (var requester = RawRabbitFactory.CreateTestClient())
			using (var responder = RawRabbitFactory.CreateTestClient())
			{
				/* Setup */
				var sent = new BasicResponse
				{
					Prop = "I am the response"
				};
				await responder.RespondAsync<BasicRequest, BasicResponse>(request => Task.FromResult(sent)
				);

				/* Test */
				var received = await requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest());

				/* Assert */
				Assert.Equal(received.Prop, sent.Prop);
			}
		}

		[Fact]
		public async Task Should_Return_Response_When_Using_Custom_Request_And_Response_Configuration()
		{
			using (var requester = RawRabbitFactory.CreateTestClient())
			using (var responder = RawRabbitFactory.CreateTestClient())
			{
				/* Setup */
				var sent = new BasicResponse { Prop = "I am the response" };
				await responder.RespondAsync<BasicRequest, BasicResponse>(message =>
						Task.FromResult(sent),
					ctx => ctx.UseRespondConfiguration(cfg => cfg
						.Consume(c => c
							.WithRoutingKey("custom_key"))
						.FromDeclaredQueue(q => q
							.WithName("custom_queue")
							.WithAutoDelete())
						.OnDeclaredExchange(e => e
							.WithName("custom_exchange")
							.WithAutoDelete()))
				);

				/* Test */
				var received = await requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest(), ctx => ctx
					.UseRequestConfiguration(cfg => cfg
						.PublishRequest(p => p
							.OnDeclaredExchange(e => e
								.WithName("custom_exchange")
								.WithAutoDelete())
							.WithRoutingKey("custom_key")
							.WithProperties(prop => prop.DeliveryMode = 1))
						.ConsumeResponse(r => r
							.Consume(c => c
								.WithRoutingKey("response_key"))
							.FromDeclaredQueue(q => q
								.WithName("response_queue")
								.WithAutoDelete())
							.OnDeclaredExchange(e => e
								.WithName("response_exchange")
								.WithAutoDelete()
							)
						)
					));

				/* Assert */
				Assert.Equal(received.Prop, sent.Prop);
			}
		}

		[Fact]
		public async Task Should_Work_With_Dedicated_Consumer_And_Custom_Response_Queue()
		{
			using (var requester = RawRabbitFactory.CreateTestClient())
			using (var responder = RawRabbitFactory.CreateTestClient())
			{
				/* Setup */
				await responder.RespondAsync<BasicRequest, BasicResponse>(async request => new BasicResponse());
				var numberOfRequests = 10;
				var responses = new Task<BasicResponse>[numberOfRequests];

				/* Test */
				for (var i = 0; i < numberOfRequests; i++)
				{
					responses[i] = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest(), ctx => ctx
						.UseDedicatedResponseConsumer()
						.UseRequestConfiguration(cfg => cfg
							.ConsumeResponse(r => r
								.Consume(c => c
									.WithRoutingKey($"response_key_{Guid.NewGuid()}"))
								.FromDeclaredQueue(q => q
									.WithName($"response_queue_{Guid.NewGuid()}")
									.WithAutoDelete())
								.OnDeclaredExchange(e => e
									.WithName("response_exchange")
									.WithAutoDelete(false)
								)
							)
						)
					);
				}
				Task.WaitAll(responses);
				await requester.DeleteExchangeAsync("response_exchange");
				/* Assert */
				Assert.True(responses.All(r => r.IsCompleted));
			}
		}
	}
}


text:
from collections import defaultdict
import csv
import datetime
from optparse import make_option

from dateutil.parser import parse
from django.core.management.base import BaseCommand
from django.utils.itercompat import is_iterable
from django.utils.timezone import make_aware, UTC

from historic.models import CaseArchived

def yesno(str):
    return True if str.upper() == "YES" else False

def parse_dt(str):
    str = str.strip()
    if str and is_iterable(str):
        try:
            return make_aware(parse(str, dayfirst=True), UTC())
        except Exception:
            import pdb

            pdb.set_trace()

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option("-c", "--case_file", dest="case_file", help="path to historic cases .csv file"),
        make_option("-k", "--kb_file", dest="kb_file", help="path to accompanying knowledge-base .csv file"),
    )

    help = "Create CaseArchived object from a case and knowledge-base CSV"

    required_args = ("case_file", "kb_file")

    def handle(self, *args, **options):
        if options["case_file"] is None or options["kb_file"] is None:
            raise ValueError("Missing parameter. Try --help")
        # Load referrals
        self.stderr.write("Loading referrals from %s" % options["kb_file"])
        self.load_referrals(options["kb_file"])
        self.stderr.write("Found referrals %s for cases" % len(self.referrals))

        # Load cases
        self.stderr.write("Loading cases from %s" % options["case_file"])
        self.load_cases(options["case_file"])
        self.stderr.write("Found %s cases" % len(self.cases))

        # Clear out existing cases if required
        existing_cases_count = CaseArchived.objects.all().count()
        if existing_cases_count:
            self.stderr.write("Clearing out %s existing historic cases." % existing_cases_count)
            CaseArchived.objects.all().delete()

        fake_datetime = datetime.datetime(1900, 1, 1).replace(tzinfo=UTC())
        # Writing Cases to the database

        def _getdate(x):
            return x.outcome_code_date or fake_datetime

        self.cases = sorted(self.cases, key=_getdate, reverse=True)

        CaseArchived.objects.bulk_create(self.cases)

    def get_referrals(self, laa_reference):
        all_refs = self.referrals.get(laa_reference)
        if all_refs:
            return "\n".join(all_refs)

    def load_referrals(self, filename):
        self.referrals = defaultdict(list)
        with open(filename, "rU") as f:
            reader = csv.DictReader(f)
            for count, row in enumerate(reader):
                if count % 20 == 0:
                    self.stderr.write(".", ending="")
                self.referrals[row["CaseID"]].append(unicode(row["Title"], "ISO-8859-1"))

    def load_cases(self, filename):
        def record_to_case_archived(row):
            full_name = row["FirstName"] + " " + row["Surname"]
            case = CaseArchived(
                full_name=unicode(full_name, "ISO-8859-1"),
                date_of_birth=parse_dt(row["DateOfBirth"]),
                postcode=unicode(row["PostCode"], "ISO-8859-1"),
                laa_reference=row["CaseID"],
                created=parse_dt(row["DateCreated"]),
                outcome_code=unicode(row["OutcomeCode"], "ISO-8859-1"),
                outcome_code_date=parse_dt(row["OutcomeDate"]),
                specialist_referred_to=unicode(row["SpecialistReferred"], "ISO-8859-1"),
                date_specialist_referred=parse_dt(row["DateSpecialistClosed"]),
                area_of_law=unicode(row["AreaOfLaw"], "ISO-8859-1"),
                in_scope=yesno(row["IsInScope"]),
                financially_eligible=bool(row["Eligible"]),
                knowledgebase_items_used=self.get_referrals(row["CaseID"]),
            )

            search_field = []
            for field in ["full_name", "postcode", "laa_reference", "outcome_code"]:
                val = getattr(case, field)
                if val:
                    search_field.append(val.upper())
            case.search_field = " ".join(search_field)

            return case

        self.cases = []
        with open(filename, "rU") as f:
            reader = csv.DictReader(f, lineterminator="\n")
            for count, row in enumerate(reader):
                if count % 20 == 0:
                    self.stderr.write(".", ending="")
                self.cases.append(record_to_case_archived(row))


text:
Add Principal

<form role="form" ng-submit="savePrincipal()">

		<abel for="type" class="control-label">Type
		<select ng-model="principal.type" class="form-control" id="type">
		  <option value="board">Investment Advisory Board</option>
		  <option value="associate">Associate</option>
		  <option value="director">Director</option>
		</select>

		First name
		<input type="text" ng-model="principal.firstname" class="form-control" id="firstname" placeholder="First name">

		Last name
		<input type="text" ng-model="principal.lastname" class="form-control" id="lastname" placeholder="Last name">

		Bio
		<textarea ng-model="principal.bio" class="form-control ck-editor" id="bio" placeholder="Bio"></textarea>

	<button ng-click="back()" type="button" class="btn btn-default">Cancel</button>
	<input type="submit" class="btn btn-primary" value="Save principal">
</form>


text:
static const char *TAG = "ioextender";

static QueueHandle_t ioextender_queue;

static SemaphoreHandle_t pcf_interrupt_sem;

static int add_arr[] = {0x1a, 0x20, 0x53, 0x77};

static void i2c_scan_task(void *pvParameter);
static bool isvalueinarray(int val, int *arr, int size);

static void pcf8574_check_task(void *pvParameter);
void setup_pcf8574();
static void PCFInterrupt();
bool check_button(PCF857x *pcf8574, button_check_s* button);

void ioextender_initialize() {
  pcf_interrupt_sem = xSemaphoreCreateBinary();
  xTaskCreatePinnedToCore(i2c_scan_task, "i2c_scan_task", 4096, NULL, 1, NULL, 1);
  xTaskCreatePinnedToCore(pcf8574_check_task, "pcf8574_check_task", 4096, NULL, 1, NULL, 1);
}

void buttons_subscribe(QueueHandle_t queue)
{
  ioextender_queue = queue;
}

static void i2c_scan_task(void *pvParameter)
{
  ESP_LOGI(TAG, "i2c scan task running");

  TwoWire testWire(1);
  testWire.begin(GPIO_NUM_21, GPIO_NUM_22);
  testWire.setClock(100000L);

  while(1)
  {
    int address;
    int foundCount = 0;

    for (address=1; address<127; address++) {
      testWire.beginTransmission(address);
      uint8_t error = testWire.endTransmission();
      if (error == 0) {
        foundCount++;
        ESP_LOGI(TAG, "Found device at 0x%.2x", address);

        if (!isvalueinarray(address, add_arr, 4)) {
          ESP_LOGE(TAG, "Found unknown i2c device 0x%.2x", address);
        }
      }
    }

    ESP_LOGI(TAG, "Found %d I2C devices by scanning.", foundCount);

    vTaskDelay(30000 / portTICK_PERIOD_MS);
  }
}

static void pcf8574_check_task(void *pvParameter)
{
  TwoWire testWire(1);
  testWire.begin(GPIO_NUM_21, GPIO_NUM_22);
  testWire.setClock(100000L);

  button_check_s buttonA = {0, 0, HIGH, IOEXT_A_BTN, "ButtonA"};
  button_check_s buttonB = {0, 0, HIGH, IOEXT_B_BTN, "ButtonB"};
  button_check_s encoderButton = {0, 0, HIGH, IOEXT_ENCODER_BTN, "EncoderButton"};

  PCF857x pcf8574(0x20, &testWire);

  pcf8574.begin();

  pcf8574.write8(B00101111);

  pinMode(IOEXT_INTERRUPT_PIN, INPUT_PULLUP);
  pcf8574.resetInterruptPin();
  attachInterrupt(digitalPinToInterrupt(IOEXT_INTERRUPT_PIN), PCFInterrupt, FALLING);

  while(1) {
    xSemaphoreTake(pcf_interrupt_sem, portMAX_DELAY);

    // ESP_LOGI(TAG, "PCF Interrupt");
    check_button(&pcf8574, &buttonA);
    check_button(&pcf8574, &buttonB);
    check_button(&pcf8574, &encoderButton);

    pcf8574.resetInterruptPin();
  }
}

// this is a simple lockout debounce function
bool check_button(PCF857x *pcf8574, button_check_s* button)
{

  uint8_t readState = pcf8574->read(button->pin);

  if (readState == button->state) {
    return false; // no state change
  }

  if (millis() - button->previous_millis >= IOEXT_DEBOUNCE_MILLIS) {
    // We have passed the time threshold, so a new change of state is allowed.
    button->previous_millis = millis();
    button->state = readState;

    button_reading_t reading = {
	  .label = button->label,
	  .state = stringFromState(button->state),
    };

	QueueHandle_t queue = ioextender_queue;
	if (queue) {
      xQueueSendToBack(queue, &reading, 0);
    }

    return true;
  }

  return false;
}

static void IRAM_ATTR PCFInterrupt()
{
    portBASE_TYPE higher_task_awoken = pdFALSE;
	xSemaphoreGiveFromISR(pcf_interrupt_sem, &higher_task_awoken);
	if (higher_task_awoken) {
	  portYIELD_FROM_ISR();
	}
}

void ioextender_write(uint8_t pin, uint8_t value)
{
  //pcf8574.write(pin, value);
}

static bool isvalueinarray(int val, int *arr, int size){
    int i;
    for (i=0; i < size; i++) {
        if (arr[i] == val)
            return true;
    }
    return false;
}


text:
<?php

class AdminModule extends CWebModule
{

	public function init()
	{
		// this method is called when the module is being created
		// you may place code here to customize the module or the application

		// import the module-level models and components
		$this->setImport(array(
			'admin.models.*',
			'admin.components.*',
		));

	}

	public function beforeControllerAction($controller, $action)
	{
		if(parent::beforeControllerAction($controller, $action))
		{
		    $controller->layout='//layouts_admin/column2';
		    Yii::app()->setComponent('frontendUser', Yii::app()->user);
            Yii::app()->setComponent('user', Yii::app()->adminUser);
			// this method is called before any module controller action is performed
			// you may place customized code here
			return true;
		}
		else
			return false;
	}

}


text:
namespace Microsoft.Azure.Management.AppPlatform.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Source information for a deployment
    /// </summary>
    public partial class UserSourceInfo
    {
        /// <summary>
        /// Initializes a new instance of the UserSourceInfo class.
        /// </summary>
        public UserSourceInfo()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the UserSourceInfo class.
        /// </summary>
        /// <param name="type">Type of the source uploaded. Possible values
        /// include: 'Jar', 'NetCoreZip', 'Source'</param>
        /// <param name="relativePath">Relative path of the storage which
        /// stores the source</param>
        /// <param name="version">Version of the source</param>
        /// <param name="artifactSelector">Selector for the artifact to be used
        /// for the deployment for multi-module projects. This should be
        /// the relative path to the target module/project.</param>
        public UserSourceInfo(string type = default(string), string relativePath = default(string), string version = default(string), string artifactSelector = default(string))
        {
            Type = type;
            RelativePath = relativePath;
            Version = version;
            ArtifactSelector = artifactSelector;
            CustomInit();
        }

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

        /// <summary>
        /// Gets or sets type of the source uploaded. Possible values include:
        /// 'Jar', 'NetCoreZip', 'Source'
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets relative path of the storage which stores the source
        /// </summary>
        [JsonProperty(PropertyName = "relativePath")]
        public string RelativePath { get; set; }

        /// <summary>
        /// Gets or sets version of the source
        /// </summary>
        [JsonProperty(PropertyName = "version")]
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets selector for the artifact to be used for the
        /// deployment for multi-module projects. This should be
        /// the relative path to the target module/project.
        /// </summary>
        [JsonProperty(PropertyName = "artifactSelector")]
        public string ArtifactSelector { get; set; }

    }
}


text:
/**
 * Parameters for the driver.
 */
package org.apache.reef.runtime.common.driver.parameters;


text:
package consulapi

import (
	"encoding/base64"
	"net/http"
	"sort"

	"github.com/pkg/errors"
)

type Query struct {
	DC string
}

//go:generate go run github.com/gojuno/minimock/v3/cmd/minimock -g -i KV -s _mock.go

// A KV can access the key-value store of consul.
//
// The consul KV store is useful for storing small values of information. It is
// intended to be used to store things like service configuration and other
// meta-data. The maximum size of a value is 512KiB.
//
// Each DC contains its own KV store. The data in a KV store is not replicated
// across DCs.
//
// https://www.consul.io/api/kv.html
type KV interface {

	// Get will return the value defined at path, for dc.
	Get(Ctx, string, Query) (string, error)

	// Put will set value at path, in dc.
	Put(Ctx, string, string, Query) error

	// Delete will remove the value at path, in dc.
	Delete(Ctx, string, Query) error

	// Keys will list all subpaths in asciibetical order.
	// The returned paths may be terminal (ie, the value is
	// stored content) or they may be further traversable like
	// a directory listing, in dc.
	Keys(Ctx, string, Query) ([]string, error)

	// Recurse will recursively descend through path, collecting
	// all KV pairs along the way, in dc.
	Recurse(Ctx, string, Query) ([]Pair, error)
}

func (c *client) Get(ctx Ctx, path string, query Query) (string, error) {
	var params [][2]string

	if query.DC != "" {
		params = append(params, [2]string{"dc", query.DC})
	}

	path = fixup("/v1/kv", path, params...)

	var values []Pair

	if err := c.get(ctx, path, &values); err != nil {
		if re, ok := err.(*RequestError); ok {
			if re.StatusCode() == http.StatusNotFound {
				return "", errors.Errorf("key %q does not exist", path)
			}
		}
		return "", err
	}

	bs, err := base64.StdEncoding.DecodeString(values[0].Value)
	if err != nil {
		return "", err
	}

	return string(bs), nil
}

func (c *client) Put(ctx Ctx, path, value string, query Query) error {
	var params [][2]string

	if query.DC != "" {
		params = append(params, [2]string{"dc", query.DC})
	}

	path = fixup("/v1/kv", path, params...)

	if err := c.put(ctx, path, value, nil); err != nil {
		return err
	}

	return nil
}

func (c *client) Delete(ctx Ctx, path string, query Query) error {
	var params [][2]string

	if query.DC != "" {
		params = append(params, [2]string{"dc", query.DC})
	}

	path = fixup("/v1/kv", path, params...)

	if err := c.delete(ctx, path); err != nil {
		return err
	}

	return nil
}

func (c *client) Keys(ctx Ctx, path string, query Query) ([]string, error) {
	var params [][2]string

	if query.DC != "" {
		params = append(params, [2]string{"dc", query.DC})
	}

	params = append(params, [2]string{"keys", "true"})

	path = fixup("/v1/kv", path, params...)

	var keys []string
	if err := c.get(ctx, path, &keys); err != nil {
		return nil, err
	}

	sort.Strings(keys)
	return keys, nil
}

func (c *client) Recurse(ctx Ctx, path string, query Query) ([]Pair, error) {
	var params [][2]string

	if query.DC != "" {
		params = append(params, [2]string{"dc", query.DC})
	}

	params = append(params, [2]string{"recurse", "true"})

	rPath := fixup("/v1/kv", path, params...)

	var values []Pair

	if err := c.get(ctx, rPath, &values); err != nil {
		if re, ok := err.(*RequestError); ok {
			if re.StatusCode() == http.StatusNotFound {
				return nil, errors.Errorf("key-space %q does not exist", path)
			}
		}
		return nil, err
	}

	kvPairs := make([]Pair, 0, len(values))

	for _, value := range values {
		decoded, err := base64.StdEncoding.DecodeString(value.Value)
		if err != nil {
			return nil, err
		}

		kvPairs = append(kvPairs, Pair{
			Key:   value.Key,
			Value: string(decoded),
		})
	}

	sort.Slice(kvPairs, func(i, j int) bool {
		return kvPairs[i].Key < kvPairs[j].Key
	})

	return kvPairs, nil
}


text:
namespace sani {

	namespace resource {

		class Texture2DContent : public ResourceItem {
		private:
			using PixelData		= std::vector<unsigned char>;
			using MipmapChain	= std::vector<PixelData>;

			MipmapChain faces;
			const uint32 width;
			const uint32 height;
		public:
			Texture2DContent(const uint32 width, const uint32 height, const PixelData&);

			void generateMipmaps(bool overwrite = false);

			const MipmapChain& getMipmaps() const;

			const uint32 getWidth() const;
			const uint32 getHeight() const;
		};
	}
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <complex.h>
#include <math.h>
#define ISCL_MACROS_SRC 1
#include "iscl/iscl/errorCheckMacros.h"
#include "iscl/signal/design.h"
#include "iscl/memory/memory.h"

/*!
 * @defgroup signal_design_zpklp2bp zpklp2bp
 * @brief Converts a lowpass filter to a bandpass filter.
 * @ingroup signal_design
 */
/*!
 * @brief Transform a lowpass filter prototype to a bandpass filter.
 *
 * @param[in] nzeros     Number of zeros.
 * @param[in] z          Lowpass zeros to transform.  This is an array
 *                       of dimension [nzeros].
 * @param[in] npoles     Number of poles.
 * @param[in] p          Lowpass poles to transform.  This is an array
 *                       of dimension [npoles].
 * @param[in] k          System gain.
 * @param[in] w0         Desired cutoff frequency in (rad/s).
 * @param[in] bw         Desired passband width in (rad/s).
 *
 * @param[out] ierr      ISCL error code where ISCL_SUCCESS indicates success.
 *
 * @result Bandpass poles, zeros, and gain constant corresponding to
 *         the characteristic lowpass filter.
 *
 * @ingroup signal_design_zpklp2bp
 *
 * @author Ben Baker, ISTI
 *
 */
struct signalZPK_struct
     signal_design_zpklp2bp(const int nzeros,
                            const double complex *__restrict__ z,
                            const int npoles,
                            const double complex *__restrict__ p,
                            const double k, const double w0, const double bw,
                            enum isclError_enum *ierr)
{
    struct signalZPK_struct zpk_bp;
    *ierr = ISCL_SUCCESS;
    memset(&zpk_bp, 0, sizeof(struct signalZPK_struct));
    zpk_bp.nzeros = nzeros + npoles;
    zpk_bp.npoles = 2*npoles;
    zpk_bp.z = memory_calloc64z(zpk_bp.nzeros);
    zpk_bp.p = memory_calloc64z(zpk_bp.npoles);
    *ierr = signal_design_zpklp2bp_work(nzeros, z, npoles, p, k, w0, bw,
                                     zpk_bp.nzeros, zpk_bp.z,
                                     zpk_bp.npoles, zpk_bp.p,
                                     &zpk_bp.k);
    if (*ierr != ISCL_SUCCESS)
    {
        isclPrintError("%s", "Error transfering lowpass to bandpass");
        memory_free64z(&zpk_bp.z);
        memory_free64z(&zpk_bp.p);
        memset(&zpk_bp, 0, sizeof(struct signalZPK_struct));
    }
    return zpk_bp;
}
//============================================================================//
/*!
 * @brief Transform a lowpass filter prototype to a bandpass filter.
 *
 * @param[in] nzeros     Number of zeros.
 * @param[in] z          Lowpass zeros to transform.  This is an array of
 *                       dimension [nzeros].
 * @param[in] npoles     Number of poles.
 * @param[in] p          Lowpass poles to transform.  This is an array of
 *                       dimension [npoles].
 * @param[in] k          System gain.
 * @param[in] w0         Desired cutoff frequency (rad/s).
 * @param[in] bw         Desired passband width (rad/s).
 * @param[in] nzeros_bp  Number of transformed zeros.  This should equal
 *                       nzeros + npoles.
 * @param[in] npoles_bp  Number of transformed poles.  This should
 *                       equal 2*npoles.
 *
 * @param[out] z_bp      Bandpass zeros.  This is an array of
 *                       dimension [nzeros_bp].
 * @param[out] p_bp      Bandpass poles.  This is an array of
 *                       dimension [npoles_bp].
 * @param[out] k_bp      Bandpass system gain.
 *
 * @result ISCL error code where ISCL_SUCCESS indicates success.
 *
 * @ingroup signal_design_zpklp2bp
 *
 * @author Ben Baker, ISTI
 *
 */
enum isclError_enum
    signal_design_zpklp2bp_work(const int nzeros,
                             const double complex *__restrict__ z,
                             const int npoles,
                             const double complex *__restrict__ p,
                             const double k, const double w0, const double bw,
                             const int nzeros_bp,
                             double complex *__restrict__ z_bp,
                             const int npoles_bp,
                             double complex *__restrict__ p_bp,
                             double *k_bp)
{
    double complex pdif, plp, plp2, psqrt, zbw2, zdif, zlp, zlp2, zsqrt, zw02;
    int i, j;
    double complex zero = DCMPLX(0.0, 0.0); //0.0 + 0.0*_Complex_I;
    //------------------------------------------------------------------------//
    //
    // Checks
    isclReturnArrayTooSmallError("npoles_bp", npoles_bp, 2*npoles);
    isclReturnArrayTooSmallError("nzeros_bp", nzeros_bp, nzeros + npoles);
    isclReturnNullPointerError("p_bp", p_bp);
    isclReturnNullPointerError("z_bp", z_bp);
    // Define some constants
    zw02 = DCMPLX(w0*w0 , 0.0); //w0*w0 + 0.0*_Complex_I;  //w0^2
    zbw2 = DCMPLX(bw/2.0, 0.0); //bw/2.0 + 0.0*_Complex_I; //bw/2
    // Duplicate poles and zeros and shift from baseband to +w0 and -w0
    j = nzeros;
    for (i=0; i<nzeros; i++)
    {
        zlp = zbw2*z[i];       //Scales zeros to desired bw
        zlp2 = zlp*zlp;        //zlp^2
        zdif = zlp2 - zw02;    //zlp^2 - w0^2
        zsqrt = csqrt(zdif);   //sqrt(zlp^2 - w0^2)
        z_bp[i] = zlp + zsqrt; //zlp+sqrt(zlp^2-w0^2)
        z_bp[j] = zlp - zsqrt; //zlp-sqrt(zlp^2-w0^2)
        j = j + 1;
    }
    j = npoles;
    for (i=0; i<npoles; i++)
    {
        plp = zbw2*p[i];       //Scales poles to desired bw
        plp2 = plp*plp;        //plp^2
        pdif = plp2 - zw02;    //plp^2 - w0^2
        psqrt = csqrt(pdif);   //sqrt(plp^2 - w0^2)
        p_bp[i] = plp + psqrt; //plp+sqrt(plp^2-w0^2)
        p_bp[j] = plp - psqrt; //plp-sqrt(plp^2-w0^2)
        j = j + 1;
    }
    // Move degree zeros to origin leaving degree zeros at infinity for BPF
    for (i=2*nzeros; i<nzeros_bp; i++)
    {
        z_bp[i] = zero;
    }
    // Cancel out gain change from frequency scaling
    *k_bp = k*pow(bw,npoles-nzeros); //k*bw*bw^degree
    return ISCL_SUCCESS;
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class au.gov.amsa.ihs.model.Ship.Builder (parent 0.5.25 API)</title>
<meta name="date" content="2020-09-11">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
au.gov.amsa.ihs.model.Ship.Builder

Packages that use Ship.Builder

Package
Description

au.gov.amsa.ihs.model

Uses of Ship.Builder in au.gov.amsa.ihs.model

Methods in au.gov.amsa.ihs.model that return Ship.Builder

Modifier and Type
Method and Description

Ship.Builder
Ship.Builder.breadthMetres(com.google.common.base.Optional<Float> value)

static Ship.Builder
Ship.builder()

Ship.Builder
Ship.Builder.classificationSocietyCode(com.google.common.base.Optional<String> classificationSocietyCode)

Ship.Builder
Ship.Builder.countryOfBuildCode(com.google.common.base.Optional<String> countryOfBuildCode)

Ship.Builder
Ship.Builder.deadweightTonnage(com.google.common.base.Optional<Float> dwt)

Ship.Builder
Ship.Builder.displacementTonnage(com.google.common.base.Optional<Float> value)

Ship.Builder
Ship.Builder.draughtMetres(com.google.common.base.Optional<Float> value)

Ship.Builder
Ship.Builder.flagCode(com.google.common.base.Optional<String> flagCode)

Ship.Builder
Ship.Builder.grossTonnage(com.google.common.base.Optional<Long> grossTonnage)

Ship.Builder
Ship.Builder.groupBeneficialOwnerCompanyCode(com.google.common.base.Optional<String> groupBeneficialOwnerCompanyCode)

Ship.Builder
Ship.Builder.groupBeneficialOwnerCountryOfDomicileCode(com.google.common.base.Optional<String> groupBeneficialOwnerCountryOfDomicileCode)

Ship.Builder
Ship.Builder.imo(String imo)

Ship.Builder
Ship.Builder.lastUpdateTime(com.google.common.base.Optional<org.joda.time.DateTime> value)

Ship.Builder
Ship.Builder.lengthOverallMetres(com.google.common.base.Optional<Float> value)

Ship.Builder
Ship.Builder.mmsi(com.google.common.base.Optional<String> mmsi)

Ship.Builder
Ship.Builder.monthOfBuild(com.google.common.base.Optional<Integer> monthOfBuild)

Ship.Builder
Ship.Builder.name(com.google.common.base.Optional<String> name)

Ship.Builder
Ship.Builder.shipBuilderCompanyCode(com.google.common.base.Optional<String> shipBuilderCompanyCode)

Ship.Builder
Ship.Builder.speedKnots(com.google.common.base.Optional<Float> value)

Ship.Builder
Ship.Builder.statCode5(com.google.common.base.Optional<String> value)

Ship.Builder
Ship.Builder.type2(com.google.common.base.Optional<String> type2)

Ship.Builder
Ship.Builder.type3(com.google.common.base.Optional<String> type3)

Ship.Builder
Ship.Builder.type4(com.google.common.base.Optional<String> type4)

Ship.Builder
Ship.Builder.type5(com.google.common.base.Optional<String> type5)

Ship.Builder
Ship.Builder.yearOfBuild(com.google.common.base.Optional<Integer> yearOfBuild)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020. All rights reserved.


text:
/**
 * TreeNode class for Tree problems
 */

public class TreeNode{
	public int data;
	public TreeNode left;
	public TreeNode right;
	public TreeNode parent;

	public TreeNode(int data){
		this.data = data;
	}

	public void setLeft(TreeNode left){
		this.left = left;
		if(left != null){
			this.left.parent = this;
		}
	}

	public void setRight(TreeNode right){
		this.right = right;
		if(right != null){
			this.right.parent = this;
		}
	}

	public void setChild(TreeNode left, TreeNode right){
		setLeft(left);
		setRight(right);
	}
}