text:
/**
 * @externs
 */

/**
 * @type {Object}
 */
var oli;

/**
 * @interface
 */
oli.AssertionError = function() {};

/**
 * @type {number}
 */
oli.AssertionError.prototype.code;

/**
 * @interface
 */
oli.events.Event = function() {};

/**
 * @type {Object}
 */
oli.events.Event.prototype.target;

/**
 * @type {string}
 */
oli.events.Event.prototype.type;

/**
 */
oli.events.Event.prototype.preventDefault = function() {};

/**
 */
oli.events.Event.prototype.stopPropagation = function() {};

/**
 * @interface
 */
oli.Collection.Event = function() {};

/**
 * @type {*}
 */
oli.Collection.Event.prototype.element;

/**
 * @interface
 */
oli.DragBoxEvent = function() {};

/**
 * @type {ol.Coordinate}
 */
oli.DragBoxEvent.prototype.coordinate;

/**
 * @type {ol.MapBrowserEvent}
 */
oli.DragBoxEvent.prototype.mapBrowserEvent;

/**
 * @interface
 */
oli.DrawEvent = function() {};

/**
 * @type {ol.Feature}
 */
oli.DrawEvent.prototype.feature;

/**
 * @interface
 */
oli.ExtentEvent = function() {};

/**
 * @type {ol.Extent}
 */
oli.ExtentEvent.prototype.extent;

/**
 * @interface
 */
oli.ModifyEvent = function() {};

/**
 * @type {ol.Collection.<ol.Feature>}
 */
oli.ModifyEvent.prototype.features;

/**
 * @type {ol.MapBrowserEvent}
 */
oli.ModifyEvent.prototype.mapBrowserEvent;

/**
 * @type {Object}
 */
oli.Object;

/**
 * @interface
 */
oli.Object.Event = function() {};

/**
 * @type {string}
 */
oli.Object.Event.prototype.key;

/**
 * @type {*}
 */
oli.Object.Event.prototype.oldValue;

/**
 * @interface
 */
oli.MapBrowserEvent = function() {};

/**
 * @type {ol.Coordinate}
 */
oli.MapBrowserEvent.prototype.coordinate;

/**
 * @type {Event}
 */
oli.MapBrowserEvent.prototype.originalEvent;

/**
 * @type {ol.Pixel}
 */
oli.MapBrowserEvent.prototype.pixel;

/**
 * @type {boolean}
 */
oli.MapBrowserEvent.prototype.dragging;

/**
 * @interface
 */
oli.MapEvent = function() {};

/**
 * @type {ol.PluggableMap}
 */
oli.MapEvent.prototype.map;

/**
 * @type {olx.FrameState}
 */
oli.MapEvent.prototype.frameState;

/**
 * @interface
 */
oli.SelectEvent = function() {};

/**
 * @type {Array.<ol.Feature>}
 */
oli.SelectEvent.prototype.deselected;

/**
 * @type {Array.<ol.Feature>}
 */
oli.SelectEvent.prototype.selected;

/**
 * @type {ol.MapBrowserEvent}
 */
oli.SelectEvent.prototype.mapBrowserEvent;

/**
 * @type {Object}
 */
oli.control;

/**
 * @interface
 */
oli.control.Control = function() {};

/**
 * @param {ol.PluggableMap} map Map.
 * @return {undefined} Undefined.
 */
oli.control.Control.prototype.setMap = function(map) {};

/**
 * @type {Object}
 */
oli.interaction;

/**
 * @interface
 */
oli.interaction.DragAndDropEvent = function() {};

/**
 * @type {Array.<ol.Feature>|undefined}
 */
oli.interaction.DragAndDropEvent.prototype.features;

/**
 * @type {ol.proj.Projection|undefined}
 */
oli.interaction.DragAndDropEvent.prototype.projection;

/**
 * @type {File}
 */
oli.interaction.DragAndDropEvent.prototype.file;

/**
 * @interface
 */
oli.interaction.TranslateEvent = function() {};

/**
 * @type {ol.Collection.<ol.Feature>}
 */
oli.interaction.TranslateEvent.prototype.features;

/**
 * @type {ol.Coordinate}
 */
oli.interaction.TranslateEvent.prototype.coordinate;

/**
 * @type {Object}
 */
oli.render;

/**
 * @interface
 */
oli.render.Event = function() {};

/**
 * @type {CanvasRenderingContext2D|null|undefined}
 */
oli.render.Event.prototype.context;

/**
 * @type {olx.FrameState|undefined}
 */
oli.render.Event.prototype.frameState;

/**
 * @type {ol.webgl.Context|null|undefined}
 */
oli.render.Event.prototype.glContext;

/**
 * @type {ol.render.VectorContext|undefined}
 */
oli.render.Event.prototype.vectorContext;

/**
 * @type {Object}
 */
oli.source;

/**
 * @interface
 */
oli.source.ImageEvent = function() {};

/**
 * @type {ol.Image}
 */
oli.source.ImageEvent.prototype.image;

/**
 * @interface
 */
oli.source.RasterEvent = function() {};

/**
 * @type {ol.Extent}
 */
oli.source.RasterEvent.prototype.extent;

/**
 * @type {number}
 */
oli.source.RasterEvent.prototype.resolution;

/**
 * @type {Object}
 */
oli.source.RasterEvent.prototype.data;

/**
 * @interface
 */
oli.source.Tile.Event = function() {};

/**
 * @type {ol.Tile}
 */
oli.source.Tile.Event.prototype.tile;

/**
 * @interface
 */
oli.source.Vector.Event = function() {};

/**
 * @type {ol.Feature|undefined}
 */
oli.source.Vector.Event.prototype.feature;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Gama.Cooperacion.Wpf.Views
{
    /// <summary>
    /// Interaction logic for ActividadDetailView.xaml
    /// </summary>
    public partial class EditarActividadView : UserControl
    {
        public EditarActividadView()
        {
            InitializeComponent();

            var column1 = _InformacionDeActividadGrid.ColumnDefinitions[0];
            var column3 = _InformacionDeActividadGrid.ColumnDefinitions[2];
            column1.Width = new GridLength(0, GridUnitType.Star);
            column3.Width = new GridLength(99, GridUnitType.Star);
            _InformacionDeActividadStackPanel.Visibility = Visibility.Collapsed;
        }

        private void VerOpcionesActividades_MouseUp(object sender, MouseButtonEventArgs e)
        {
            var column1 = _InformacionDeActividadGrid.ColumnDefinitions[0];
            var column3 = _InformacionDeActividadGrid.ColumnDefinitions[2];
            if (column1.Width.Value == 28)
            {
                column1.Width = new GridLength(0, GridUnitType.Star);
                column3.Width = new GridLength(99, GridUnitType.Star);
                _InformacionDeActividadStackPanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                column1.Width = new GridLength(28, GridUnitType.Star);
                column3.Width = new GridLength(71, GridUnitType.Star);
                _InformacionDeActividadStackPanel.Visibility = Visibility.Visible;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// # Whiteboard Angular Components

// ##### [Back to Table of Contents](./tableofcontents.html)

/*===================================
===== CANVAS/DRAWING DIRECTIVES =====
====================================*/

/*
Angular directive altered and repurposed
from pwambach's Angular-Canvas-Painter:
https://github.com/pwambach/angular-canvas-painter
*/

angular.module('snapcast.whiteboard', [])

/*===================================
===== COLORPICKER DIRECTIVE =====
====================================*/

  .directive('kiColorSelector', function () {
    return {
      restrict: 'AE',
      scope: {
        colorList: '=kiColorSelector',
        selectedColor: '=color'
      },
      templateUrl: '../templates/color-selector.html',
      link: function(scope){
        // sets color on scope to the color chosen
        scope.setColor = function(col){
          scope.selectedColor = col;
        };
      }
    };
  })

/*===================================
======== DRAWING DIRECTIVES =========
====================================*/
  .directive('kiCanvas', function($window, socket) {
    return {
      restrict: 'AE',
      scope: {
        options: '=',
        version: '='
      },
      templateUrl: '../templates/canvas.html',
      link: function postLink(scope, elm) {

        // Detects if touch or mouse for events
        var isTouch = !!('ontouchstart' in window);

        var PAINT_START = isTouch ? 'touchstart' : 'mousedown';
        var PAINT_MOVE = isTouch ? 'touchmove' : 'mousemove';
        var PAINT_END = isTouch ? 'touchend' : 'mouseup';

/*==========================================
 DEFAULT OPTIONS AND VARIABLE INITIALIZATION
============================================*/

        // Timeout for drawing video on canvas
        var timeout;

        var options = scope.options || {};
        options.canvasId = options.customCanvasId || 'boardCanvas';
        options.tmpCanvasId = options.customCanvasId ? (options.canvasId + 'Tmp') : 'tmpCanvas';
        options.bgCanvasId = options.customCanvasId ? (options.canvasId + 'Bg') : 'bgCanvas';
        options.width = options.width || $window.innerWidth;
        options.height = options.height || $window.innerHeight;
        options.backgroundColor = options.backgroundColor || '#fff';
        options.color = options.color || '#000';
        options.undoEnabled = options.undoEnabled || false;
        options.opacity = options.opacity || 0.9;
        options.lineWidth = options.lineWidth || 1;
        options.undo = options.undo || false;
        options.imageSrc = options.imageSrc || './images/dot.png';

        // Loads image source into image object for background
        var loadImage = function(imageSrc) {

          var image = new Image();
          image.onload = function() {
            options.background = image;
            changeBackground(image);
          };
          image.src = imageSrc;
        };

        // Loads default image as background
        if (options.imageSrc) {
          loadImage(options.imageSrc);
        }

/*========================================
           UNDO FUNCTIONALITY
Undo functionality - not used but can be used. To implement, simply
add a function on the control utilizing scope.undo.
==========================================*/
        if (options.undo) {
          var undoCache = [];
          scope.$watch(function() {
            return undoCache.length;
          }, function(newVal) {
            scope.version = newVal;
          });

          scope.$watch('version', function(newVal) {
            if (newVal < 0) {
              scope.version = 0;
              return;
            }
            if (newVal >= undoCache.length) {
              scope.version = undoCache.length;
              return;
            }
            undo(newVal);
          });
        }

/*========================================
       CANVAS INITIALIZATION
Initializes Canvases and respective Contexts.
There are three layers of canvases:
-The background layer, which draws images or videos underneath the other layers
-The temporary layer, where each mark made by the user is originally drawn
-This layer is wiped clean after every mark
-The drawing layer, where all marks are aggregated and rendered smoothly
-This is the layer is sent over sockets to update others
==========================================*/

        var canvas = document.createElement('canvas');
        scope.canvas = canvas;
        canvas.id = options.canvasId;
        var canvasTmp = document.createElement('canvas');
        scope.canvasTmp = canvasTmp;
        canvasTmp.id = options.tmpCanvasId;
        var canvasBg = document.createElement('canvas');
        canvasBg.id = options.bgCanvasId;
        scope.canvasBg = canvasBg;

      // Sets positions of lower layers
        angular.element(canvasTmp).css({
          position: 'absolute',
          top: 0,
          left: 0
        });
        angular.element(canvasBg).css({
          position: 'absolute',
          top: 0,
          left: 0,
          'z-index': -1
        });

      // Appends canvases to the page
        elm.find('div').append(canvas);
        elm.find('div').append(canvasBg);
        elm.find('div').append(canvasTmp);

      // Context creation
        var ctx = canvas.getContext('2d');
        var ctxTmp = canvasTmp.getContext('2d');
        var ctxBg = canvasBg.getContext('2d');

      //Sets canvas sizes
        canvas.width = canvasBg.width = canvasTmp.width = options.width;
        canvas.height = canvasBg.height = canvasTmp.height = options.height;

      //set context styles
        ctxTmp.globalAlpha = options.opacity;
        ctxTmp.lineJoin = ctxTmp.lineCap = 'round';
        ctxTmp.lineWidth = 10;
        ctxTmp.strokeStyle = options.color;

      //Init drawing coordinate variables
        var point = {
          x: 0,
          y: 0
        };

        var ppts = [];

        //Watch options for angular events from controller(s)
        // Screenshare events
        scope.$on('screenshare', function(e, data) {
          changeBackground(data);
        });

        scope.$on('screenshare:removed', function(e) {
          changeBackground();
        });

        // Remoteshare events - created for readability, can be removed
        scope.$on('remoteshare', function(e, data) {
          changeBackground(data);
        });

        scope.$on('remoteshare:removed', function(e) {
          changeBackground();
        });

       // Toggles between backgrounds and updates color of Snapcast logo
        scope.$on('toggleBg', function(e) {
          if (scope.imageSrc === './images/dot.png') {
            scope.imageSrc = './images/dark.jpg';

            $('h1').css('color','#fff');
          } else {
            scope.imageSrc = './images/dot.png';

            $('h1').css('color','#000');
          }

            loadImage(scope.imageSrc);
        });

/*========================================
        SNAPSHOT FUNCTIONALITY
This creates a temporary off-screen canvas, drawing each
canvas layer in order.
The canvas is then converted to an image via toDataURL
and a download function is called to download to user's downloads folder.
Download function is under HELPER FUNCTIONS.
==========================================*/
        scope.$on('snapshot', function(e) {
          var printCanvas = document.createElement('canvas');
          var printCtx = printCanvas.getContext('2d');

          // Sets canvas width/height
          printCanvas.width = canvasBg.width;
          printCanvas.height = canvasBg.height;

          // Recreates seamless pattern
          var pattern = printCtx.createPattern(canvasBg, 'repeat');

          printCtx.rect(0, 0, canvasBg.width, canvasBg.height);
          printCtx.fillStyle = pattern;
          printCtx.fill();

          // Draws the canvas marks over it
          printCtx.drawImage(canvas, 0,0);

          // Creates new image for download
          var img = new Image();
          img.onload=function(){
          };

          // Formats/converts to jpeg
          img.src = printCanvas.toDataURL("image/jpeg", 0.9);

          // Downloads
          download(img.src, 'untitled.jpg');
        });

/*========================================
        CLEAR BOARD FUNCTIONALITY
Clears the board and sends event to make sure
other users' boards are also cleared.
==========================================*/
        scope.$on('clear', function() {
           socket.emit('clear');
           clearBoard();
        });

/*========================================
         BRUSH SETTING EVENTS
==========================================*/
        scope.$watch('options.lineWidth', function(newValue) {
          if (typeof newValue === 'string') {
            newValue = parseInt(newValue, 10);
          }
          if (newValue && typeof newValue === 'number') {
            ctxTmp.lineWidth = options.lineWidth = newValue;
          }
        });

        scope.$watch('options.color', function(newValue) {
          if (newValue) {
            ctxTmp.strokeStyle = ctxTmp.fillStyle = newValue;
          }
        });

        scope.$watch('options.opacity', function(newValue) {
          if (newValue) {
            ctxTmp.globalAlpha = newValue;
          }
        });

/*========================================
            LINE DRAWING
==========================================*/
        var getOffset = function(elem) {
          var offsetTop = 0;
          var offsetLeft = 0;
          do {
            if (!isNaN(elem.offsetLeft)) {
              offsetTop += elem.offsetTop;
              offsetLeft += elem.offsetLeft;
            }
            elem = elem.offsetParent;
          } while (elem);
          return {
            left: offsetLeft,
            top: offsetTop
          };
        };

        // Calculating coordinates
        var setPointFromEvent = function(point, e) {
          if (isTouch) {
            point.x = e.changedTouches[0].pageX - getOffset(e.target).left;
            point.y = e.changedTouches[0].pageY - getOffset(e.target).top;
          } else {
            point.x = e.offsetX !== undefined ? e.offsetX : e.layerX;
            point.y = e.offsetY !== undefined ? e.offsetY : e.layerY;
          }
        };

        var paint = function(e) {

          if (e) {
            e.preventDefault();
            setPointFromEvent(point, e);
          }
          // Saving all the points in an array
          ppts.push({
            x: point.x,
            y: point.y
          });

          if (ppts.length === 3) {
            var b = ppts[0];
            ctxTmp.beginPath();
            ctxTmp.arc(b.x, b.y, ctxTmp.lineWidth / 2, 0, Math.PI * 2, !0);
            ctxTmp.fill();
            ctxTmp.closePath();
            return;
          }

          // Clears the canvas before drawing another mark.
          clearBoard(ctxTmp, canvasTmp);

          ctxTmp.beginPath();
          ctxTmp.moveTo(ppts[0].x, ppts[0].y);

          for (var i = 1; i < ppts.length - 2; i++) {

            var c = (ppts[i].x + ppts[i + 1].x) / 2;
            var d = (ppts[i].y + ppts[i + 1].y) / 2;
            ctxTmp.quadraticCurveTo(ppts[i].x, ppts[i].y, c, d);
          }

          // Draws smooth line based on last two points
          ctxTmp.quadraticCurveTo(
            ppts[i - 1].x,
            ppts[i - 1].y,
            ppts[i].x,
            ppts[i].y
          );
          ctxTmp.stroke();

        };

      // Copies the mark over to drawing layer
        var copyTmpImage = function() {
          if (options.undo) {
            scope.$apply(function() {
              undoCache.push(ctx.getImageData(0, 0, canvasTmp.width, canvasTmp.height));
              if (angular.isNumber(options.undo) && options.undo > 0) {
                undoCache = undoCache.slice(-1 * options.undo);
              }
            });
          }
          canvasTmp.removeEventListener(PAINT_MOVE, paint, false);
          ctx.drawImage(canvasTmp, 0, 0);
          clearBoard(ctxTmp, canvasTmp);
          ppts = [];
        };

      // Copies/Renders the canvas from other users
        var copyRemoteImage = function(canvas) {
          var image = new Image();
          image.onload = function() {
            ctx.drawImage(this, 0, 0);
          };
          image.src = canvas;
        };

      // Draws in the temporary layer
        var startTmpImage = function(e) {
          e.preventDefault();

          canvasTmp.addEventListener(PAINT_MOVE, paint, false);

          setPointFromEvent(point, e);
          ppts.push({
            x: point.x,
            y: point.y
          });
          ppts.push({
            x: point.x,
            y: point.y
          });

          paint();
        };

      // Wrapper for a socket event to be passed into an event listener
        var socketEvent = function() {
          var canvas = canvasTmp.toDataURL('image/png', 0.8);
          socket.emit('draw', canvas);
        };

/*========================================
           CANVAS LISTENERS
          For drawing events.
==========================================*/
        var initListeners = function() {
          canvasTmp.addEventListener(PAINT_START, startTmpImage, false);
          canvasTmp.addEventListener(PAINT_END, socketEvent, false);
          canvasTmp.addEventListener(PAINT_END, copyTmpImage, false);

          if (!isTouch) {
            var MOUSE_DOWN;

            document.body.addEventListener('mousedown', mousedown);
            document.body.addEventListener('mouseup', mouseup);

            scope.$on('$destroy', removeEventListeners);

            canvasTmp.addEventListener('mouseenter', mouseenter);
            canvasTmp.addEventListener('mouseleave', mouseleave);
          }

          function mousedown() {
            MOUSE_DOWN = true;
          }

          function mouseup() {
            MOUSE_DOWN = false;
          }

          function removeEventListeners() {
            document.body.removeEventListener('mousedown', mousedown);
            document.body.removeEventListener('mouseup', mouseup);
          }

          function mouseenter(e) {
            // If the mouse is down when it enters the canvas, start a path
            if (MOUSE_DOWN) {
              startTmpImage(e);
            }
          }

          function mouseleave(e) {
            // If the mouse is down when it leaves the canvas, end the path
            if (MOUSE_DOWN) {
              copyTmpImage(e);
            }
          }

        };
/*========================================
           CANVAS LISTENERS
          For socket events.
==========================================*/
      // Copies remote images received over sockets
        socket.on('draw', copyRemoteImage);

      //Clears the board when someone clears it
        socket.on('clear', function() {
          scope.$apply(clearBoard);
        });

/*========================================
           HELPER FUNCTIONS
          For socket events.
==========================================*/
// Undo function. Dials back to version needed
        var undo = function(version) {
          if (undoCache.length > 0) {
            ctx.putImageData(undoCache[version], 0, 0);
            undoCache = undoCache.slice(0, version);
          }
        };

// Changes the background. Takes an img or video DOM element as a parameter
        var changeBackground = function(newValue) {
           //Stops the rendering of video as background if needed
           if (timeout) { clearTimeout(timeout); }

           //Clears the background canvas
           clearBoard(ctxBg, canvasBg);

           //Renders according to type of element passed in
           if (newValue) {
            if (newValue.tagName === 'VIDEO') {
               //draws the element at 30fps
               console.log(newValue);
               (function loop() {
                   ctxBg.drawImage(newValue, 0, 0);
                   timeout = setTimeout(loop, 1000 / 30);
               })();
             } else if (newValue.tagName === 'IMG') {
               // Tiles the image for seamless texturing
               var pattern = ctxBg.createPattern(newValue, 'repeat');

               ctxBg.rect(0, 0, canvasBg.width, canvasBg.height);
               ctxBg.fillStyle = pattern;
               ctxBg.fill();

             }
           } else {
             // Defaults to whiteboard if no element specified
             var image = new Image();
             image.src = './images/dot.png';
             changeBackground(image);
           }

        };

// Clears the board - takes a context and its canvas
        var clearBoard = function(ctx, canvas) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
        };

// Download function that takes the canvas to download and the filename of the downloaded file
        var download = function (canvas, filename) {

            /// Creates an "off-screen" anchor tag
            var downloadLink = document.createElement('a'),
                e;

            // Sets download attribute of the tag
            downloadLink.download = filename;

            /* Converts canvas content to data-uri for link. When download
            /// attribute is set the content pointed to by link will be
             pushed as "download" in HTML5 capable browsers*/

            downloadLink.href = canvas;

            /// Creates a "fake" click-event to trigger the download
            if (document.createEvent) {

                e = document.createEvent("MouseEvents");
                e.initMouseEvent("click", true, true, window,
                                 0, 0, 0, 0, 0, false, false, false,
                                 false, 0, null);

                downloadLink.dispatchEvent(e);

            } else if (downloadLink.fireEvent) {

                downloadLink.fireEvent("onclick");
            }
        };

        initListeners();

      }
    };
  });


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TempProject
{
    class _102_Binary_Tree_Level_Order_Traversal
    {
        public static void Main(String[] args)
        {
            TreeNode treenode = new TreeNode(3);
            treenode.left = new TreeNode(9);
            treenode.left.left = new TreeNode(101);
            treenode.left.right = new TreeNode(102);

            treenode.right = new TreeNode(20);
            treenode.right.right = new TreeNode(7);
            treenode.right.left = new TreeNode(15);

            //TreeNode treenode = new TreeNode(1);
            //treenode.left = new TreeNode(2);
            //treenode.left.left = new TreeNode(4);

            //treenode.right = new TreeNode(3);
            //treenode.right.right = new TreeNode(5);

            var root = levelOrder(treenode);
            //var root = ZigZag(treenode);
        }
        public static List<List<int>> levelOrder(TreeNode root)
        {
            List<List<int>> ans = new List<List<int>>();
            compute(ans, root, 0);
            return ans;
        }

        public static void compute(List<List<int>> ans, TreeNode curr, int level)
        {
            if (curr == null) return;

            if (ans.Count() == level)
                ans.Add(new List<int>());

            ans[level].Add(curr.val);

            compute(ans, curr.left, level + 1);
            compute(ans, curr.right, level + 1);
        }
        //public static IList<IList<int>> LevelOrder(TreeNode root)
        //{
        //    var result = new List<IList<int>>();
        //    Queue<TreeNode> q = new Queue<TreeNode>();
        //    q.Enqueue(root);
        //    while (q.Count > 1)
        //    {
        //        int size = q.Count();
        //        List<int> temp = new List<int>();
        //        for (int i = 0; i < size; i++)
        //        {
        //            TreeNode curr = q.Dequeue();
        //            temp.Add(curr.val);
        //            if (curr.left != null) q.Enqueue(curr.left);
        //            if (curr.right != null) q.Enqueue(curr.right);
        //        }
        //        result.Add(temp);
        //    }
        //    return result;
        //}

        public static IList<IList<int>> ZigZag(TreeNode root)
        {
            var result = new List<IList<int>>();
            Queue<TreeNode> q = new Queue<TreeNode>();
            q.Enqueue(root);
            int depth = 1;
            while (q.Count >= 1)
            {
                int size = q.Count();
                List<int> temp = new List<int>();
                int avg = temp.OrderByDescending(o => o).First();

                for (int i = 0; i < size; i++)
                {
                    TreeNode curr = q.Dequeue();
                    temp.Add(curr.val);
                    if (depth % 2 == 0)
                    {
                        if (curr.left != null) q.Enqueue(curr.left);
                        if (curr.right != null) q.Enqueue(curr.right);
                    }
                    else
                    {
                        if (curr.right != null) q.Enqueue(curr.right);
                        if (curr.left != null) q.Enqueue(curr.left);
                    }
                }
                depth++;
                result.Add(temp);
            }
            return result;
        }

        public IList<int> RightSideView(TreeNode root)
        {
            var result = new List<int>();
            if (root == null) return result;
            var temp = root;

            while (temp != null)
            {
                result.Add(temp.val);
                if (temp.right != null)
                    temp = temp.right;
                temp = null;
            }
            return result;
        }
    }

    class TreeNode
    {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int x) { val = x; }
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import model.Week;
import model.Weekday;

/**
 *
 * @author Jonas
 */
public class WeekHandler {

    private LinkedList<Week> weekList;
    private Weekday[] weekdaysToSwitch = new Weekday[2];

    public WeekHandler() throws SQLException {
        weekList = new LinkedList<>();
        getWeeksFromDB();
    }

    public void getWeeksFromDB() throws SQLException {
            ResultSet rs = ControlHandler.getDbh().selectAll("wk order by wk_date DESC");
            while (rs.next()) {
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(rs.getLong("wk_date"));
                int weekID = rs.getInt("wk_id");
                Week week = new Week(weekID, cal, gettWeekdays(weekID));
                weekList.add(week);
            }
    }

    public Weekday[] gettWeekdays(int weekID) {
        Weekday[] weekdaysForWeek = new Weekday[7];
        int day = 0;
        for (Weekday weekday : ControlHandler.getWdh().getWeekdays()) {
            if (weekday.getWeek() == weekID) {
                weekdaysForWeek[day] = weekday;
                day++;
            }
        }
        return weekdaysForWeek;
    }

    public Week getWeek(int weekNumber) {
        boolean found = false;
        Week week = null;
        for (int i = 0; i < weekList.size() && !found; i++) {
            if (weekList.get(i).getDate() == weekNumber) {
                week = weekList.get(i);
                found = true;
            }
        }
        return week;
    }

    public LinkedList<Week> getWeekList() {
        return weekList;
    }
}


text:
.PHONY: clean-pyc clean-build docs help
.DEFAULT_GOAL := help
define BROWSER_PYSCRIPT
import os, webbrowser, sys
try:
	from urllib import pathname2url
except:
	from urllib.request import pathname2url

webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
export BROWSER_PYSCRIPT
BROWSER := python -c "$$BROWSER_PYSCRIPT"

help:
	@perl -nle'print $& if m{^[a-zA-Z_-]+:.*?## .*$$}' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}'

clean: clean-build clean-pyc

clean-build: ## remove build artifacts
	rm -fr build/
	rm -fr dist/
	rm -fr *.egg-info

clean-pyc: ## remove Python file artifacts
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +

test: ## run tests quickly with the default Python
	python runtests.py tests

coverage: ## check code coverage quickly with the default Python
	coverage run --source django-qa runtests.py tests
	coverage report -m
	coverage html
	open htmlcov/index.html

docs: ## generate Sphinx HTML documentation, including API docs
	rm -f docs/django-qa.rst
	rm -f docs/modules.rst
	sphinx-apidoc -o docs/ django-qa
	$(MAKE) -C docs clean
	$(MAKE) -C docs html
	$(BROWSER) docs/_build/html/index.html

release: clean ## package and upload a release
	python setup.py sdist upload
	python setup.py bdist_wheel upload

sdist: clean ## package
	python setup.py sdist
	ls -l dist

history: ## Generate the history report from the git log comments records
	rm HISTORY.rst
	printf '%s\n' '.. :changelog:' '' 'History' '-------' >> HISTORY.rst
	git log --no-merges --pretty=format:'%cd - `#%h <https://github.com/swappsco/django-qa/commit/%H>`_ %n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++%n%n* %s%n' >> HISTORY.rst


text:
package org.jasig.portlet.emailpreview.controller;

import java.util.HashMap;
import java.util.Map;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portlet.emailpreview.EmailMessage;
import org.jasig.portlet.emailpreview.util.MessageUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;

/**
 * @author Jen Bourey, jbourey@unicon.net
 * @author Drew Wills, drew@unicon.net
 */
@Controller
@RequestMapping("VIEW")
public class EmailMessageController extends BaseEmailController {

  private static final String CONTENT_TYPE_TEXT_PREFIX = "text/plain;";

  protected final Log log = LogFactory.getLog(getClass());

  @ResourceMapping(value = "emailMessage")
  public ModelAndView showMessage(
      ResourceRequest req, ResourceResponse res, @RequestParam("messageId") String messageId) {

    Map<String, Object> model = new HashMap<String, Object>();

    try {

      // Get current user's account information
      EmailMessage message = getEmailAccountService(req).getMessage(req, messageId);

      /*
       * A bit of after-market work on messages in certain circumstances
       */

      String messageBody = message.getContent().getContentString();

      // Make links embedded in text/plain messages clickable
      String contentType = message.getContentType(); // might be null if there was an error
      if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_PREFIX)) {
        messageBody = MessageUtils.addClickableUrlsToMessageBody(messageBody);
      }

      messageBody = MessageUtils.addMissingTargetToAnchors(messageBody);

      message.getContent().setContentString(messageBody);

      model.put("message", message);

    } catch (Exception ex) {
      log.error("Error encountered while attempting to retrieve message", ex);
    }

    return new ModelAndView("json", model);
  }

  @ResourceMapping(value = "deleteMessages")
  public ModelAndView deleteMessages(
      ResourceRequest req,
      ResourceResponse res,
      @RequestParam(value = "selectMessage", required = false) String[] uids) {

    Map<String, Object> model = new HashMap<String, Object>();

    try {

      String deletePermitted =
          req.getPreferences().getValue(EmailSummaryController.ALLOW_DELETE_PREFERENCE, "true");
      if (!Boolean.valueOf(deletePermitted)) {
        String msg = "The delete function is not permitted for this portlet";
        throw new RuntimeException(msg);
      }

      if (uids != null && uids.length != 0) {
        getEmailAccountService(req).deleteMessages(req, uids);
      }

      model.put("success", "success");

    } catch (Exception e) {
      throw new RuntimeException("Failed to delete specified messages", e);
    }

    return new ModelAndView("json", model);
  }

  @ResourceMapping(value = "toggleSeen")
  public ModelAndView toggleSeen(
      ResourceRequest req,
      ResourceResponse res,
      @RequestParam(value = "selectMessage", required = false) String[] messageIds,
      @RequestParam("seenValue") boolean seenValue) {

    Map<String, Object> model = new HashMap<String, Object>();

    try {

      if (messageIds != null && messageIds.length != 0) {

        // Opportunity for improvement:  respond to return value
        // of 'false' with some user-facing message
        getEmailAccountService(req).setSeenFlag(req, messageIds, seenValue);
      }

      model.put("success", "success");

    } catch (Exception e) {
      throw new RuntimeException("Failed to update the seen flag for specified messageIds", e);
    }

    return new ModelAndView("json", model);
  }
}


text:
function Restart-Explorer {

    try{
        Write-BoxstarterMessage "Restarting the Windows Explorer process..."
        $user = Get-CurrentUser
        try { $explorer = Get-Process -Name explorer -ErrorAction stop -IncludeUserName }
        catch {$global:error.RemoveAt(0)}

        if($explorer -ne $null) {
            $explorer | ? { $_.UserName -eq "$($user.Domain)\$($user.Name)"} | Stop-Process -Force -ErrorAction Stop | Out-Null
        }

        Start-Sleep 1

        if(!(Get-Process -Name explorer -ErrorAction SilentlyContinue)) {
            $global:error.RemoveAt(0)
            start-Process -FilePath explorer
        }
    } catch {$global:error.RemoveAt(0)}
}


text:
AGCategories
============

Collection of Objective-C categories for iOS development to make development easier.


text:
Version history
===============

.. py:currentmodule:: happybase

HappyBase 0.9
-------------

Release date: 2014-11-24

* Fix an issue where scanners would return fewer results than expected due to
  HBase not always behaving as its documentation suggests (`issue #72
  <https://github.com/wbolster/happybase/issues/72>`_).

* Add support for the Thrift compact protocol (``TCompactProtocol``) in
  :py:class:`Connection` (`issue #70
  <https://github.com/wbolster/happybase/issues/70>`_).

HappyBase 0.8
-------------

Release date: 2014-02-25

* Add (and default to) '0.96' compatibility mode in :py:class:`Connection`.

* Add support for retrieving sorted columns, which is possible with the HBase
  0.96 Thrift API. This feature uses a new `sorted_columns` argument to
  :py:meth:`Table.scan`. An ``OrderedDict`` implementation is required for this
  feature; with Python 2.7 this is available from the standard library, but for
  Python 2.6 a separate ``ordereddict`` package has to be installed from PyPI.
  (`issue #39 <https://github.com/wbolster/happybase/issues/39>`_)

* The `batch_size` argument to :py:meth:`Table.scan` is no longer propagated to
  `Scan.setBatching()` at the Java side (inside the Thrift server). To influence
  the `Scan.setBatching()` (which may split rows into partial rows) a new
  `scan_batching` argument to :py:meth:`Table.scan` has been added. See `issue
  #54 <https://github.com/wbolster/happybase/issues/54>`_, `issue #56
  <https://github.com/wbolster/happybase/issues/56>`_, and the HBase docs for
  `Scan.setBatching()` for more details.

HappyBase 0.7
-------------

Release date: 2013-11-06

* Added a `wal` argument to various data manipulation methods on the
  :py:class:`Table` and :py:class:`Batch` classes to determine whether to write
  the mutation to the Write-Ahead Log (WAL). (`issue #36
  <https://github.com/wbolster/happybase/issues/36>`_)

* Pass batch_size to underlying Thrift Scan instance (`issue #38
  <https://github.com/wbolster/happybase/issues/38>`_).

* Expose server name and port in :py:meth:`Table.regions` (recent HBase versions
  only) (`issue #37 <https://github.com/wbolster/happybase/issues/37>`_).

* Regenerated bundled Thrift API modules using a recent upstream Thrift API
  definition. This is required to expose newly added API.

HappyBase 0.6
-------------

Release date: 2013-06-12

* Rewrote exception handling in connection pool. Exception handling is now a lot
  cleaner and does not introduce cyclic references anymore. (`issue #25
  <https://github.com/wbolster/happybase/issues/25>`_).

* Regenerated bundled Thrift code using Thrift 0.9.0 with the new-style classes
  flag (`issue #27 <https://github.com/wbolster/happybase/issues/27>`_).

HappyBase 0.5
-------------

Release date: 2013-05-24

* Added a thread-safe connection pool (:py:class:`ConnectionPool`) to keep
  connections open and share them between threads (`issue #21
  <https://github.com/wbolster/happybase/issues/21>`_).

* The :py:meth:`Connection.delete_table` method now features an optional
  `disable` parameter to make deleting enabled tables easier.

* The debug log message emitted by :py:meth:`Table.scan` when closing a scanner
  now includes both the number of rows returned to the calling code, and also
  the number of rows actually fetched from the server. If scanners are not
  completely iterated over (e.g. because of a 'break' statement in the for loop
  for the scanner), these numbers may differ. If this happens often, and the
  differences are big, this may be a hint that the `batch_size` parameter to
  :py:meth:`Table.scan()` is not optimal for your application.

* Increased Thrift dependency to at least 0.8. Older versions are no longer
  available from PyPI. HappyBase should not be used with obsoleted Thrift
  versions.

* The :py:class:`Connection` constructor now features an optional `timeout`
  parameter to to specify the timeout to use for the Thrift socket (`issue #15
  <https://github.com/wbolster/happybase/issues/15>`_)

* The `timestamp` argument to various methods now also accepts `long` values in
  addition to `int` values. This fixes problems with large timestamp values on
  32-bit systems. (`issue #23
  <https://github.com/wbolster/happybase/issues/23>`_).

* In some corner cases exceptions were raised during interpreter shutdown while
  closing any remaining open connections. (`issue #18
  <https://github.com/wbolster/happybase/issues/18>`_)

HappyBase 0.4
-------------

Release date: 2012-07-11

* Add an optional `table_prefix_separator` argument to the
  :py:class:`Connection` constructor, to specify the prefix used for the
  `table_prefix` argument (`issue #3
  <https://github.com/wbolster/happybase/issues/3>`_)
* Add support for framed Thrift transports using a new optional `transport`
  argument to :py:class:`Connection` (`issue #6
  <https://github.com/wbolster/happybase/issues/6>`_)
* Add the Apache license conditions in the :doc:`license statement <license>`
  (for the included HBase parts)
* Documentation improvements

HappyBase 0.3
-------------

Release date: 2012-05-25

New features:

* Improved compatibility with HBase 0.90.x

  * In earlier versions, using :py:meth:`Table.scan` in combination with HBase
    0.90.x often resulted in crashes, caused by incompatibilities in the
    underlying Thrift protocol.
  * A new `compat` flag to the :py:class:`Connection` constructor has been
    added to enable compatibility with HBase 0.90.x.
  * Note that the :py:meth:`Table.scan` API has a few limitations when used
    with HBase 0.90.x.

* The `row_prefix` argument to :py:meth:`Table.scan` can now be used together
  with `filter` and `timestamp` arguments.

Other changes:

* Lower Thrift dependency to 0.6
* The `setup.py` script no longer installs the tests
* Documentation improvements

HappyBase 0.2
-------------

Release date: 2012-05-22

* Fix package installation, so that ``pip install happybase`` works as expected
  (`issue #1 <https://github.com/wbolster/happybase/issues/1>`_)
* Various small documentation improvements

HappyBase 0.1
-------------

Release date: 2012-05-20

* Initial release


text:
<?php print $image ?>

<?php if (!empty($title) || !empty($description)): ?>

    <?php if (!empty($title)): ?>

<?php print $title ?>

    <?php endif ?>

    <?php if (!empty($description)): ?>

<?php print $description ?>

    <?php endif ?>

<?php endif ?>


text:
require File.expand_path('../../../../../helper', __FILE__)

describe "Categories::Controller::Categories" do
  behaves_like :capybara

  after do
    Zen::Event.delete(
      :before_new_category,
      :after_new_category,
      :before_edit_category,
      :after_edit_category,
      :before_delete_category,
      :after_delete_category
    )
  end

  group         = Categories::Model::CategoryGroup.create(:name => 'Spec group')
  index_url     = Categories::Controller::Categories.r(:index, group.id).to_s
  edit_url      = Categories::Controller::Categories.r(:edit, group.id).to_s
  new_url       = Categories::Controller::Categories.r(:new, group.id).to_s
  save_button   = lang('categories.buttons.save')
  delete_button = lang('categories.buttons.delete')

  it 'Find no existing categories' do
    message = lang('categories.messages.no_categories')

    visit(index_url)

    page.has_content?(message).should           == true
    page.has_selector?('table tbody tr').should == false
    current_path.should                         == index_url
  end

  it 'Try to create a new category with a missing CSRF token' do
    visit(new_url)

    within '#category_form' do
      find('input[name="csrf_token"]').set('')
      click_on(save_button)
    end

    page.has_content?(lang('zen_general.errors.csrf')).should == true
  end

  it "Create a new category" do
    new_button  = lang('categories.buttons.new')
    event_name  = nil
    event_name2 = nil

    Zen::Event.listen(:before_new_category) do |category|
      event_name = category.name
    end

    Zen::Event.listen(:after_new_category) do |category|
      event_name2 = category.name
    end

    visit(index_url)
    click_link(new_button)

    within '#category_form' do
      fill_in('name', :with => 'Spec category')
      click_on(save_button)
    end

    current_path.should =~ /#{edit_url}\/[0-9]+/
    event_name.should   == 'Spec category'
    event_name2.should  == event_name
  end

  it 'Search for a category' do
    visit(index_url)
    search_button = lang('zen_general.buttons.search')
    error         = lang('zen_general.errors.invalid_search')

    within '#search_form' do
      fill_in('query', :with => 'Spec')
      click_on(search_button)
    end

    page.has_content?(error).should           == false
    page.has_content?('Spec category').should == true

    within '#search_form' do
      fill_in('query', :with => 'does not exist')
      click_on(search_button)
    end

    page.has_content?(error).should             == false
    page.has_content?('Spec category').should   == false
    page.has_selector?('table tbody tr').should == false
  end

  it "Edit an existing category" do
    event_name  = nil
    event_name2 = nil
    name        = 'Spec category modified 123'

    Zen::Event.listen(:before_edit_category) do |category|
      event_name = category.name
    end

    Zen::Event.listen(:after_edit_category) do |category|
      event_name2 = category.name
    end

    visit(index_url)
    click_link('Spec category')

    current_path.should =~ /#{edit_url}\/[0-9]+/

    within '#category_form' do
      fill_in('name', :with => name)
      click_on(save_button)
    end

    page.find('input[name="name"]').value.should == name

    event_name.should  == name
    event_name2.should == event_name

    # Modify the name using an event
    Zen::Event.listen(:before_edit_category) do |category|
      category.name = 'Spec category modified'
    end

    within '#category_form' do
      click_on(save_button)
    end

    page.find('input[name="name"]').value.should == 'Spec category modified'
  end

  it "Edit an existing category with invalid data" do
    visit(index_url)
    click_link('Spec category')

    current_path.should =~ /#{edit_url}\/[0-9]+/

    within '#category_form' do
      fill_in('name', :with => '')
      click_on(save_button)
    end

    page.has_selector?('span.error').should == true
  end

  it 'Non numeric category IDs should be handled gracefully' do
    visit(Categories::Controller::Categories.r(:edit, group.id, 'a').to_s)

    page.current_path.should                    == index_url
    page.has_selector?('.message.error').should == true
  end

  enable_javascript

  it 'Automatically save a category' do
    visit(index_url)
    click_link('Spec category')

    within '#category_form' do
      fill_in('name', :with => 'Spec category autosave')
    end

    autosave_form('category_form')

    visit(index_url)

    page.has_content?('Spec category autosave').should == true

    click_link('Spec category autosave')

    within '#category_form' do
      fill_in('name', :with => 'Spec category modified')
      click_on(save_button)
    end

    page.has_selector?('span.error').should      == false
    page.find('input[name="name"]').value.should == 'Spec category modified'
  end

  disable_javascript

  it 'Fail to delete a category without an ID' do
    visit(index_url)
    click_on(delete_button)

    page.has_selector?('input[name="category_ids[]"]').should == true
  end

  it "Delete an existing category" do
    message     = lang('categories.messages.no_categories')
    event_name  = nil
    event_name2 = nil

    Zen::Event.listen(:before_delete_category) do |category|
      event_name = category.name
    end

    Zen::Event.listen(:after_delete_category) do |category|
      event_name2 = category.name
    end

    visit(index_url)
    check('category_ids[]')
    click_on(delete_button)

    page.has_content?(message).should           == true
    page.has_selector?('table tbody tr').should == false

    event_name.should  == 'Spec category modified'
    event_name2.should == event_name
  end

  group.destroy
end


text:
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016-2017.
*/

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace ShiftDrive {

    internal sealed class PanelThrottleBar : Control {

        private float targetThrottle;

        public PanelThrottleBar() {
            lock (NetClient.worldLock) {
                targetThrottle = NetClient.World.GetPlayerShip().Throttle;
            }
        }

        protected override void OnDraw(SpriteBatch spriteBatch) {
            int baseBarHeight = (SDGame.Inst.GameHeight - 100) / 2 - 100;

            // Throttle bar
            // we show local target throttle so that the UI always animates and is responsive,
            // even if the server will only actually apply the target throttle several frames later.
            // bar filling
            int throttleBarY = SDGame.Inst.GameHeight - 40 - baseBarHeight;
            int throttleFillH = (int)(baseBarHeight * targetThrottle);
            int throttleFillY = baseBarHeight - throttleFillH;
            spriteBatch.Draw(Assets.GetTexture("ui/fillbar"), new Rectangle(40, throttleBarY + throttleFillY, 64, throttleFillH), new Rectangle(64, throttleFillY, 64, throttleFillH), Color.White);
            // bar outline
            spriteBatch.Draw(Assets.GetTexture("ui/fillbar"), new Rectangle(40, throttleBarY, 64, 24), new Rectangle(0, 0, 64, 24), Color.White);
            spriteBatch.Draw(Assets.GetTexture("ui/fillbar"), new Rectangle(40, throttleBarY + baseBarHeight - 24, 64, 24), new Rectangle(0, 24, 64, 24), Color.White);
            spriteBatch.DrawString(Assets.fontDefault, Locale.Get("throttle"), new Vector2(32, throttleBarY - 25), Color.White);
            spriteBatch.DrawString(Assets.fontDefault, (int)(targetThrottle * 100f) + "%", new Vector2(128, throttleBarY + throttleFillY - 10), Color.White);
        }

        protected override void OnUpdate(GameTime gameTime) {
            // ignore input from dead players
            if (NetClient.World.GetPlayerShip().Destroyed) return;

            // throttle input
            float oldThrottle = targetThrottle;
            if (Input.GetKey(Keys.W)) {
                targetThrottle += (float)gameTime.ElapsedGameTime.TotalSeconds;
            } else if (Input.GetKey(Keys.S)) {
                targetThrottle -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            targetThrottle = MathHelper.Clamp(targetThrottle, 0f, 1f);

            // replicate throttle input to server, but avoid clogging bandwidth
            if (Math.Abs(oldThrottle - targetThrottle) > 0.01f)
                using (Packet packet = new Packet(PacketID.HelmThrottle)) {
                    packet.Write(targetThrottle);
                    NetClient.Send(packet);
                }
        }

    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Kiwi.Renderers.GLTextureManager - Kiwi.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 1.0.1

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Kiwi.Animations.Animation

Kiwi.Animations.Sequence

Kiwi.Animations.Tween

Kiwi.Animations.Tweens.Easing.Back

Kiwi.Animations.Tweens.Easing.Bounce

Kiwi.Animations.Tweens.Easing.Circular

Kiwi.Animations.Tweens.Easing.Cubic

Kiwi.Animations.Tweens.Easing.Elastic

Kiwi.Animations.Tweens.Easing.Exponential

Kiwi.Animations.Tweens.Easing.Linear

Kiwi.Animations.Tweens.Easing.Quadratic

Kiwi.Animations.Tweens.Easing.Quartic

Kiwi.Animations.Tweens.Easing.Quintic

Kiwi.Animations.Tweens.Easing.Sinusoidal

Kiwi.Animations.Tweens.TweenManager

Kiwi.Camera

Kiwi.CameraManager

Kiwi.Component

Kiwi.ComponentManager

Kiwi.Components.AnimationManager

Kiwi.Components.ArcadePhysics

Kiwi.Components.Box

Kiwi.Components.Input

Kiwi.Components.Sound

Kiwi.Entity

Kiwi.Files.DataLibrary

Kiwi.Files.File

Kiwi.Files.FileStore

Kiwi.Files.Loader

Kiwi.Game

Kiwi.GameManager

Kiwi.GameObjects.Sprite

Kiwi.GameObjects.StaticImage

Kiwi.GameObjects.Textfield

Kiwi.GameObjects.Tilemap.TileMap

Kiwi.GameObjects.Tilemap.TileMapLayer

Kiwi.GameObjects.Tilemap.TileType

Kiwi.Geom.AABB

Kiwi.Geom.Circle

Kiwi.Geom.Intersect

Kiwi.Geom.IntersectResult

Kiwi.Geom.Line

Kiwi.Geom.Matrix

Kiwi.Geom.Point

Kiwi.Geom.Ray

Kiwi.Geom.Rectangle

Kiwi.Geom.Transform

Kiwi.Geom.Vector2

Kiwi.Group

Kiwi.HUD.HUDComponents.Counter

Kiwi.HUD.HUDComponents.Time

Kiwi.HUD.HUDComponents.WidgetInput

Kiwi.HUD.HUDDisplay

Kiwi.HUD.HUDManager

Kiwi.HUD.HUDWidget

Kiwi.HUD.Widget.Bar

Kiwi.HUD.Widget.BasicScore

Kiwi.HUD.Widget.Button

Kiwi.HUD.Widget.Icon

Kiwi.HUD.Widget.IconBar

Kiwi.HUD.Widget.Menu

Kiwi.HUD.Widget.MenuItem

Kiwi.HUD.Widget.TextField

Kiwi.HUD.Widget.Time

Kiwi.IChild

Kiwi.Input.Finger

Kiwi.Input.InputManager

Kiwi.Input.Key

Kiwi.Input.Keyboard

Kiwi.Input.Keycodes

Kiwi.Input.Mouse

Kiwi.Input.MouseCursor

Kiwi.Input.Pointer

Kiwi.Input.Touch

Kiwi.PluginManager

Kiwi.Renderers.CanvasRenderer

Kiwi.Renderers.GLArrayBuffer

Kiwi.Renderers.GLElementArrayBuffer

Kiwi.Renderers.GLRenderManager

Kiwi.Renderers.GLTextureManager

Kiwi.Renderers.GLTextureWrapper

Kiwi.Renderers.Renderer

Kiwi.Renderers.TextureAtlasRenderer

Kiwi.Shaders.ShaderManager

Kiwi.Shaders.ShaderPair

Kiwi.Shaders.TextureAtlasShader

Kiwi.Signal

Kiwi.SignalBinding

Kiwi.Sound.Audio

Kiwi.Sound.AudioLibrary

Kiwi.Sound.AudioManager

Kiwi.Stage

Kiwi.State

Kiwi.StateConfig

Kiwi.StateManager

Kiwi.System.Bootstrap

Kiwi.System.Device

Kiwi.Textures.SingleImage

Kiwi.Textures.SpriteSheet

Kiwi.Textures.TextureAtlas

Kiwi.Textures.TextureLibrary

Kiwi.Time.Clock

Kiwi.Time.ClockManager

Kiwi.Time.MasterClock

Kiwi.Time.Timer

Kiwi.Time.TimerEvent

Kiwi.Utils.Canvas

Kiwi.Utils.Common

Kiwi.Utils.GameMath

Kiwi.Utils.RandomDataGenerator

Kiwi.Utils.RequestAnimationFrame

Kiwi.Utils.Version

Animations

Components

Easing

Files

GameObjects

Geom

HUD

HUDComponents

Input

Kiwi

Renderers

Shaders

Sound

System

Textures

Tilemap

Time

Tweens

Utils

Widget

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

Kiwi.Renderers.GLTextureManager Class

            Defined in: src\render\GLTextureManager.ts:13

            Module: Renderers

            Parent Module: Kiwi

Manages GL Texture objects, including creation, uploading, destruction and memory management

Constructor

Kiwi.Renderers.GLTextureManager

        ()

            GLTextureManager

                Defined in

        src\render\GLTextureManager.ts:13

Returns:

                        GLTextureManager:

Index

Methods

Properties

Item Index

Methods

                                _addTextureToCache

                                _deleteTexture

                                _freeSpace

                                _uploadTexture

                                clearTextures

                                uploadTextureLibrary

                                useTexture

Properties

                                _textureWrapperCache

                                DEFAULT_MAX_TEX_MEM_MB

                                    static

                                maxTextureMem

                                numTextureWrites

                                usedTextureMem

                                usedTextureMem

Methods

_addTextureToCache

            (

                        glTexture

)

        private

                Defined in

        src\render\GLTextureManager.ts:84

Adds a texture wrapper to the cache

Parameters:

                        glTexture
                        GLTextureWrapper

_deleteTexture

            (

                        gl

                        idx

)

        private

                Defined in

        src\render\GLTextureManager.ts:94

Deletes a texture from memory and removes the wrapper from the cache

Parameters:

                        gl
                        WebGLRenderingContext

                        idx
                        Number

_freeSpace

            (

                        gl

                        numBytesToRemove

)

        public

                Defined in

        src\render\GLTextureManager.ts:208

Attemps to free space for to uplaod a texture.
1: Try and find texture that is same size to remove
2: Find next smallest to remove (not yet implemented)
3: Sequentially remove until there is room (not yet implemented)

Parameters:

                        gl
                        WebGLRenderingContext

                        numBytesToRemove
                        Number

Returns:

boolean

_uploadTexture

            (

                        gl

                        glTextureWrapper

)

        private

                Defined in

        src\render\GLTextureManager.ts:108

Uploads a texture to video memory

Parameters:

                        gl
                        WebGLRenderingContext

                        glTextureWrapper
                        GLTextureWrapper

Returns:

boolean

clearTextures

            (

                        gl

)

        public

                Defined in

        src\render\GLTextureManager.ts:159

Removes all textures from video memory and clears the wrapper cache

Parameters:

                        gl
                        WebGLRenderingContext

uploadTextureLibrary

            (

                        gl

                        textureLibrary

)

        public

                Defined in

        src\render\GLTextureManager.ts:129

Uploads a texture library to video memory

Parameters:

                        gl
                        WebGLRenderingContext

                        textureLibrary
                        Kiwi.Textures.TextureLibrary

useTexture

            (

                        gl

                        glTextureWrapper

                        textureSizeUniform

)

        public

                Defined in

        src\render\GLTextureManager.ts:177

Binds the texture ready for use, uploads it if it isn't already

Parameters:

                        gl
                        WebGLRenderingContext

                        glTextureWrapper
                        GLTextureWrappery

                        textureSizeUniform
                        Number

Returns:

boolean

Properties

_textureWrapperCache

    GLTextureWrapper

        private

                Defined in

        src\render\GLTextureManager.ts:76

An array of references to all texture wrappers

DEFAULT_MAX_TEX_MEM_MB

    Number

        public

        static

                Defined in

        src\render\GLTextureManager.ts:28

The default maximum amount of texture memory to use before swapping textures

maxTextureMem

    Number

        public

                Defined in

        src\render\GLTextureManager.ts:37

The maximum amount of texture memory to use before swapping textures, initialised from DEFAULT_MAX_TEX_MEM_MB

numTextureWrites

    Number

        public

                Defined in

        src\render\GLTextureManager.ts:67

The number of textures uploads in the last frame

usedTextureMem

    Number

        public

                Defined in

        src\render\GLTextureManager.ts:45

The amount of texture memory currently uplaoded

usedTextureMem

    Number

        public

                Defined in

        src\render\GLTextureManager.ts:56

The number of textures currently uplaoded


text:
export const enum EntityState {
    Detached = 0,
    Unchanged,
    Deleted,
    Modified,
    Added,
}


text:
require 'rubygems'
require 'stringio'
require 'logger'
require 'rack'

module Yars
  class RequestHandler
      def initialize(app, logfile)
        @app = app
      end

      def service(req)
        request = req[:request]
        method = request['method']
        version = request['http_version']
        remote_addr = request['remote_addr']
        path = request['querypath']
        query = request['querydata'] == :undefined ? '' : request['querydata']
        server = request['servername']
        headers = request['headers']
        cookies = request['cookies']
        postdata = request['postdata'] == :undefined ? '' : request['postdata']

        translate = {'content_type' => 'CONTENT_TYPE',
                     'content_length' => 'CONTENT_LENGTH',
                     'authorization' => 'HTTP_AUTHORIZATION',
                     'accept' => 'HTTP_ACCEPT',
                     'Accept-Charset' => 'HTTP_ACCEPT_CHARSET',
                     'Accept-Encoding' => 'HTTP_ACCEPT_ENCODING',
                     'Accept-Language' => 'HTTP_ACCEPT_LANGUAGE',
                     'connection' => 'HTTP_CONNECTION',
                     'keep_alive' => 'HTTP_KEEP_ALIVE',
                     'host' => 'HTTP_HOST',
                     'referer' => 'HTTP_REFERER',
                     'user_agent' => 'HTTP_USER_AGENT',
                     'X-Prototype-Version' => 'HTTP_X_PROTOTYPE_VERSION',
                     'X-Requested-With' => 'HTTP_X_REQUESTED_WITH',
                     'X-Forwarded-Proto' => 'HTTP_X_FORWARDED_PROTO'}

        env = {}
        env['REQUEST_METHOD'] = method.to_s
        env['REMOTE_ADDR'] = remote_addr
        env['QUERY_STRING'] = query
        env["PATH_INFO"] = path
        env = headers.inject(env) { |a, x| a[translate[x[0]] || x[0].to_s] = x[1]; a }
        env.delete_if { |k, v| v.nil? }

        env.update({"rack.version" => [0, 1],
                    "rack.input" => StringIO.new(postdata),
                    "rack.errors" => STDERR,

                    "rack.multithread" => true,
                    "rack.multiprocess" => false,
                    "rack.run_once" => false,

                    "rack.url_scheme" => request['https'] == 1 ? "https" : "http"
                  })

        env['SERVER_NAME'] = server.split(':')[0]
        env['SERVER_PORT'] = server.split(':')[1]
        env['HTTP_VERSION'] = version.join('.')
        env['HTTPS'] = request['https'] == 1 ? "on" : "off"

        env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
        env["QUERY_STRING"] ||= ""
        env["REQUEST_PATH"] ||= "/"
        env.delete "PATH_INFO" if env["PATH_INFO"] == ""

        cookies.each do |cookie|
          env["HTTP_COOKIE"] = cookie.to_s
        end

        begin
          status, headers, body = @app.call(env)

          html = ''
          body.each do |part|
            html << part
          end

          headers['Server'] = 'YARS 0.0.1'
          headers['Connection'] = 'close'

          cookies = headers.delete('cookie')
          headers['Set-Cookie'] = cookies if cookies

          status = (headers["Status"].split(" ").first rescue nil) || status
          headers.delete("Status") if headers["Status"]

          [:response,
                  [[:status, status.to_i],
                  [:allheaders, headers.keys.inject([]) {|x,y| x << [:header, y, headers[y]]}],
                  [:html, html]]]
        rescue => e
          [:response,
                  [[:status, 500],
                  [:allheaders, [
                    [:header, "Content-Type", "text/plain; charset=utf-8"],
                    [:header, "Cache-Control", "no-cache"]]],
                  [:html, "500 Internal Error\n\n#{e}\n\n#{e.backtrace}"]]]
        end
    end
  end
end


text:
<?php
    $right=$_SESSION["MSA"]["right"];
    $loggedIn=$_SESSION["MSA"]["loggedIn"];
?>

    <form id="form-reportFilter" action="report/showDailyWork" method="post" target="iframe-report">

                <input type="text" name="Search" class="header-search-input z-depth-2" placeholder="Explore Materialize">

รายงานการปฏิบัติงานรายวันรถขยะ

รายงาน

รายงานน้ำหนักขยะ

                            <select id="branchID" name="branchID">
                                <?php
                                    if(isset($right["view-allBranch"])){
                                        foreach ($branchName as $branchID => $name) {
                                            ?>
                                <option value="<?=$branchID?>"><?=$name?></option>
                                            <?php
                                        }
                                    }else{
                                        ?>
                                <option value="<?=$loggedIn["branchID"]?>"><?=$branchName[$loggedIn["branchID"]]?></option>
                                        <?php
                                    }
                                ?>
                            </select>
                            สาขา

                            <select id="truckID" name="truckID">
                                <option value="">ทั้งหมด</option>
                                <?php
                                    if(isset($right["view-allBranch"])){
                                        foreach ($branchName as $branchID => $name) {
                                            ?>
                                <option value="<?=$branchID?>"><?=$name?></option>
                                            <?php
                                        }
                                    }else{
                                        ?>
                                <option value="<?=$loggedIn["branchID"]?>"><?=$branchName[$loggedIn["branchID"]]?></option>
                                        <?php
                                    }
                                ?>
                            </select>
                            รถขยะ (รหัสทรัพย์สิน / ทะเบียน)

                <input type="hidden" id="displayType" name="displayType" value="print">
                <input type="hidden" name="method" value="<?=$this->router->fetch_method()?>">

                    <input type="text" name="startDate" id="startDate" placeholder="" required="">
                    ตั้งแต่

                    <input type="text" name="endDate" id="endDate" placeholder="" required="">
                    ถึง

                    <button id="button-submit" class="btn waves-effect waves-light right green" type="submit">
                        ออกรายงาน
                    </button>
                    <button id="button-fullScreen" class="btn waves-effect waves-light right blue" type="button" style="margin-right: 5px;">
                        ขยายหน้าจอ
                    </button>

    </form>


text:
FROM node:6.9.1

EXPOSE 3000

ENV NODE_ENV=production

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app
RUN npm i

COPY index.js /usr/src/app
COPY src /usr/src/app/src
COPY config /usr/src/app/config

CMD npm start


text:
#include "caipadapterutils_eth.h"

#include <Arduino.h>
#include <Ethernet.h>
#include <socket.h>
#include <w5100.h>
#include <EthernetUdp.h>
#include <IPAddress.h>

#include "logger.h"
#include "cacommon.h"
#include "caadapterinterface.h"
#include "caipadapter_singlethread.h"
#include "caadapterutils.h"

#define TAG "IPU"

CAResult_t CAArduinoGetAvailableSocket(int *sockID)
{
    VERIFY_NON_NULL(sockID, TAG, "sockID");
    uint8_t state;
    //Is any socket available to work with ?
    *sockID = 0;
    for (int i = 1; i < MAX_SOCK_NUM; i++)
    {
        state = W5100.readSnSR(i);
        if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT)
        {
            *sockID = i;
            break;
        }
    }

    if (*sockID == 0)
    {
        OIC_LOG(ERROR, TAG, "sockID 0");
        return CA_SOCKET_OPERATION_FAILED;
    }

    return CA_STATUS_OK;
}

CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID)
{
    OIC_LOG(DEBUG, TAG, "IN");
    VERIFY_NON_NULL(port, TAG, "port");
    VERIFY_NON_NULL(socketID, TAG, "socketID");

    CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
    if (ret != CA_STATUS_OK)
    {
        OIC_LOG(ERROR, TAG, "get sock fail");
        return ret;
    }

    //Create a datagram socket on which to recv/send.
    if (!socket(*socketID, SnMR::UDP, *port, 0))
    {
        OIC_LOG(ERROR, TAG, "sock fail");
        return CA_STATUS_FAILED;
    }

    OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID);
    OIC_LOG(DEBUG, TAG, "OUT");
    return CA_STATUS_OK;
}

CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress,
                                           uint16_t mport,
                                           uint16_t lport, int *socketID)
{
    OIC_LOG(DEBUG, TAG, "IN");
    VERIFY_NON_NULL(mcastAddress, TAG, "address");
    VERIFY_NON_NULL(socketID, TAG, "socket");

    uint8_t mcastMacAddr[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00};
    uint8_t ipAddr[4] = { 0 };
    uint16_t parsedPort = 0;
    if (CAParseIPv4AddressInternal(mcastAddress, ipAddr, sizeof(ipAddr),
                                   &parsedPort) != CA_STATUS_OK)
    {
        OIC_LOG(ERROR, TAG, "parse fail");
        return CA_STATUS_FAILED;
    }

    *socketID = 0;
    CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
    if (ret != CA_STATUS_OK)
    {
        OIC_LOG(ERROR, TAG, "sock fail");
        return ret;
    }

    //Calculate Multicast MAC address
    mcastMacAddr[3] = ipAddr[1] & 0x7F;
    mcastMacAddr[4] = ipAddr[2];
    mcastMacAddr[5] = ipAddr[3];
    W5100.writeSnDIPR(*socketID, (uint8_t *)ipAddr);
    W5100.writeSnDHAR(*socketID, mcastMacAddr);
    W5100.writeSnDPORT(*socketID, mport);

    //Create a datagram socket on which to recv/send.
    if (!socket(*socketID, SnMR::UDP, lport, SnMR::MULTI))
    {
        OIC_LOG(ERROR, TAG, "sock fail");
        return CA_SOCKET_OPERATION_FAILED;
    }

    OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID);
    OIC_LOG(DEBUG, TAG, "OUT");
    return CA_STATUS_OK;
}


text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the EntityTypeDefinition class.
 * @constructor
 * Describes an entity.
 *
 * @member {string} [apiEntitySetName] The api entity set name. This becomes
 * the odata entity set name for the entity Type being refered in this object.
 *
 * @member {string} [entityType] Type of entity. Possible values include:
 * 'None', 'Profile', 'Interaction', 'Relationship'
 *
 * @member {array} [fields] The properties of the Profile.
 *
 * @member {number} [instancesCount] The instance count.
 *
 * @member {date} [lastChangedUtc] The last changed time for the type
 * definition.
 *
 * @member {string} [provisioningState] The provisioning state of the Type.
 *
 * @member {string} [schemaItemTypeLink] The schema org link. This helps ACI
 * identify and suggest semantic models.
 *
 * @member {string} [tenantId] The hub name.
 *
 * @member {string} [timestampFieldName] The timestamp property name.
 * Represents the time when the interaction or profile update happened.
 *
 * @member {string} [typeName] The name of the entity.
 *
 */
class EntityTypeDefinition extends models['MetadataDefinitionBase'] {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of EntityTypeDefinition
   *
   * @returns {object} metadata of EntityTypeDefinition
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'EntityTypeDefinition',
      type: {
        name: 'Composite',
        className: 'EntityTypeDefinition',
        modelProperties: {
          attributes: {
            required: false,
            serializedName: 'attributes',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'ArrayElementType',
                  type: {
                    name: 'Sequence',
                    element: {
                        required: false,
                        serializedName: 'StringElementType',
                        type: {
                          name: 'String'
                        }
                    }
                  }
              }
            }
          },
          description: {
            required: false,
            serializedName: 'description',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          displayName: {
            required: false,
            serializedName: 'displayName',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          localizedAttributes: {
            required: false,
            serializedName: 'localizedAttributes',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'ObjectElementType',
                  type: {
                    name: 'Dictionary',
                    value: {
                        required: false,
                        serializedName: 'StringElementType',
                        type: {
                          name: 'String'
                        }
                    }
                  }
              }
            }
          },
          smallImage: {
            required: false,
            serializedName: 'smallImage',
            type: {
              name: 'String'
            }
          },
          mediumImage: {
            required: false,
            serializedName: 'mediumImage',
            type: {
              name: 'String'
            }
          },
          largeImage: {
            required: false,
            serializedName: 'largeImage',
            type: {
              name: 'String'
            }
          },
          apiEntitySetName: {
            required: false,
            serializedName: 'apiEntitySetName',
            type: {
              name: 'String'
            }
          },
          entityType: {
            required: false,
            serializedName: 'entityType',
            type: {
              name: 'Enum',
              allowedValues: [ 'None', 'Profile', 'Interaction', 'Relationship' ]
            }
          },
          fields: {
            required: false,
            serializedName: 'fields',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'PropertyDefinitionElementType',
                  type: {
                    name: 'Composite',
                    className: 'PropertyDefinition'
                  }
              }
            }
          },
          instancesCount: {
            required: false,
            serializedName: 'instancesCount',
            type: {
              name: 'Number'
            }
          },
          lastChangedUtc: {
            required: false,
            readOnly: true,
            serializedName: 'lastChangedUtc',
            type: {
              name: 'DateTime'
            }
          },
          provisioningState: {
            required: false,
            readOnly: true,
            serializedName: 'provisioningState',
            type: {
              name: 'String'
            }
          },
          schemaItemTypeLink: {
            required: false,
            serializedName: 'schemaItemTypeLink',
            type: {
              name: 'String'
            }
          },
          tenantId: {
            required: false,
            readOnly: true,
            serializedName: 'tenantId',
            type: {
              name: 'String'
            }
          },
          timestampFieldName: {
            required: false,
            serializedName: 'timestampFieldName',
            type: {
              name: 'String'
            }
          },
          typeName: {
            required: false,
            serializedName: 'typeName',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = EntityTypeDefinition;


text:
<?php

    // These variables define the connection information for your MySQL database
    $username = "Philipp";
    $password = "chat12345";
    $host = "localhost";
    $dbname = "chat";

// UTF-8 is a character encoding scheme that allows you to conveniently store
    // a wide varienty of special characters, like ¢ or €, in your database.
    // By passing the following $options array to the database connection code we
    // are telling the MySQL server that we want to communicate with it using UTF-8
    // See Wikipedia for more information on UTF-8:
    // http://en.wikipedia.org/wiki/UTF-8
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

    // A try/catch statement is a common method of error handling in object oriented code.
    // First, PHP executes the code within the try block.  If at any time it encounters an
    // error while executing that code, it stops immediately and jumps down to the
    // catch block.  For more detailed information on exceptions and try/catch blocks:
    // http://us2.php.net/manual/en/language.exceptions.php
    try
    {
        // This statement opens a connection to your database using the PDO library
        // PDO is designed to provide a flexible interface between PHP and many
        // different types of database servers.  For more information on PDO:
        // http://us2.php.net/manual/en/class.pdo.php
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
    }
    catch(PDOException $ex)
    {
        // If an error occurs while opening a connection to your database, it will
        // be trapped here.  The script will output an error and stop executing.
        // Note: On a production website, you should not output $ex->getMessage().
        // It may provide an attacker with helpful information about your code
        // (like your database username and password).
        die("Failed to connect to the database: " . $ex->getMessage());
    }

    // This statement configures PDO to throw an exception when it encounters
    // an error.  This allows us to use try/catch blocks to trap database errors.
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // This statement configures PDO to return database rows from your database using an associative
    // array.  This means the array will have string indexes, where the string value
    // represents the name of the column in your database.
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    // This block of code is used to undo magic quotes.  Magic quotes are a terrible
    // feature that was removed from PHP as of PHP 5.4.  However, older installations
    // of PHP may still have magic quotes enabled and this code is necessary to
    // prevent them from causing problems.  For more information on magic quotes:
    // http://php.net/manual/en/security.magicquotes.php
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
    {
        function undo_magic_quotes_gpc(&$array)
        {
            foreach($array as &$value)
            {
                if(is_array($value))
                {
                    undo_magic_quotes_gpc($value);
                }
                else
                {
                    $value = stripslashes($value);
                }
            }
        }

        undo_magic_quotes_gpc($_POST);
        undo_magic_quotes_gpc($_GET);
        undo_magic_quotes_gpc($_COOKIE);
    }

    // This tells the web browser that your content is encoded using UTF-8
    // and that it should submit content back to you using UTF-8
    header('Content-Type: text/html; charset=utf-8');

    session_start();
    $session_id = session_id();

    // *******************************************************************************************

    require "common.inc.php";

    // suppose that we're logged in
    $view = "home";

    if(!empty($_GET['view'])) {
        // view was passed in
        $view = $_GET['view'];
    }

    // protect view name (allow only letters and numbers)
    $view = preg_replace("/[^a-z0-9_]/", "", $view);

    // allow registering
    $view_register = false;
    if($view == "register")
        $view_register = true;

    // allow login
    $view_login = false;
    if($view == "login")
        $view_login = true;

    // delete session
    if(!empty($_GET['logout'])) {
        $query = "DELETE FROM sessions WHERE session_id = :session_id";
        $query_params = array(
            ':session_id' => $session_id
        );

        exec_query($db, $query, $query_params);
        response_success("Logged out!");
    }

    $logged_in = false;

    // checking login
    // access on session table?
    $query = "SELECT * FROM sessions WHERE session_id = :session_id";
    $query_params = array(
        ':session_id' => $session_id
    );

    $stmt = exec_query($db, $query, $query_params);

    $row = $stmt->fetch();
    if($row) {
        $logged_in = true;
        $active_user_id = $row['user_id'];
        $active_username = get_username_by_id($db, $active_user_id);
    }

    // show authentification_error view if not logged in
    // and current view is neither register nor login
    if(!$logged_in) {
        if(!$view_register && !$view_login)
            $view = "authentication_error";
    }

    // build view-filename
    $incfile = "view_".$view.".inc.php";
    if(!file_exists($incfile)) {
        $incfile = "view_notfound.inc.php";
    }

    require $incfile;

?>


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(PURUSInsurance.Startup))]
namespace PURUSInsurance
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Reftest Test: Segment Break Transformation Rules</title>
<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
<link rel="author" title="Mozilla" href="https://www.mozilla.org">
<link rel="help" href="https://drafts.csswg.org/css-text-3/#line-break-transform">
<meta name="assert" content="'segment-break-transformation-rules: with Hangul/Not East Asian (Neutral) in front/back of the semgment break.">
<link rel="stylesheet" type="text/css" href="/fonts/ahem.css">
<link rel="match" href="segment-break-transformation-rules-048-ref.html">

Pass if there is ONE white space between the two strings below.

테스트
آزمون


text:
package com.intellij.psi.impl.source.tree.java;

import com.intellij.psi.*;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.tree.CompositePsiElement;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class PsiTypeTestPatternImpl extends CompositePsiElement implements PsiTypeTestPattern, Constants {
  public PsiTypeTestPatternImpl() {
    super(TYPE_TEST_PATTERN);
  }

  @NotNull
  @Override
  public PsiTypeElement getCheckType() {
    for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child instanceof PsiTypeElement) return (PsiTypeElement)child;
      if (child instanceof PsiPatternVariable) return ((PsiPatternVariable)child).getTypeElement();
    }
    throw new IllegalStateException(this.getText());
  }

  @Nullable
  @Override
  public PsiPatternVariable getPatternVariable() {
    return PsiTreeUtil.getChildOfType(this, PsiPatternVariable.class);
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitTypeTestPattern(this);
    }
    else {
      visitor.visitElement(this);
    }
  }

  @Override
  public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent,
                                     @NotNull PsiElement place) {
    processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this);

    PsiPatternVariable variable = getPatternVariable();
    if (variable != lastParent) {
      return processor.execute(variable, state);
    }
    return true;
  }

  @Override
  public String toString() {
    return "PsiTypeTestPattern";
  }
}


text:
'''
Utility functions for visualizing results of DeepSurv experiments
'''

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import pylab

import numpy as np

import os

from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test

def extract_value_list(arr):
    return list(np.array(arr)[:,1])

def plot_log(log):
    """
    Plots the training and validation curves for a network's loss function
    and calculated concordance index.

    Parameters:
        log: a dictionary with a list of values for any of the following keys:
            'train': training loss
            'valid': validation loss
            'train_ci': training concordance index
            VALID_CI: validation concordance index
    """
    TRAIN_LOSS = 'loss'
    TRAIN_CI = 'c-index'
    VALID_LOSS = 'valid_loss'
    VALID_CI = 'valid_c-index'

    num_epochs = len(log[TRAIN_LOSS])

    # Plots Negative Log Likelihood vs. Epoch
    fig, ax1 = plt.subplots()
    # plt.figure()
    handles = []
    if TRAIN_LOSS in log:
        epochs = range(num_epochs)
        values = extract_value_list(log[TRAIN_LOSS])
        train, = ax1.plot(epochs, values, 'b', label = 'Training')
        ax1.tick_params('y', colors='b')
        handles.append(train)
    if VALID_LOSS in log:
        ax2 = ax1.twinx()
        epochs = np.linspace(0,num_epochs-1,num=len(log[VALID_LOSS]))
        values = extract_value_list(log[VALID_LOSS])
        valid, = ax2.plot(epochs,values, 'r', label = 'Validation')
        ax2.tick_params('y', colors='r')
        handles.append(valid)
    plt.xlabel('Epoch')
    plt.ylabel('Negative Log Likelihood')
    plt.legend(handles=handles, loc = 0)

    # Plots Concordance Index vs. Epoch
    plt.figure()
    handles = []
    if TRAIN_CI in log:
        epochs = np.linspace(0,num_epochs-1,num=len(log[TRAIN_CI]))
        train, = plt.plot(epochs, extract_value_list(log[TRAIN_CI]), label = 'Training')
        handles.append(train)
    if VALID_CI in log:
        epochs = np.linspace(0,num_epochs-1,num=len(log[VALID_CI]))
        valid, = plt.plot(epochs, extract_value_list(log[VALID_CI]), label = 'Validation')
        handles.append(valid)
    plt.xlabel('Epoch')
    plt.ylabel('Concordance Index')
    plt.legend(handles = handles, loc = 4)

def plot_risk_model(x_0, x_1, hr, figsize=(4,3), clim = (-3,3), cmap = 'jet'):
    fig, ax = plt.subplots(figsize=figsize)
    plt.xlim(-1, 1)
    plt.xlabel('$x_0$', fontsize='large')
    plt.xticks(np.arange(-1, 1.5, .5))

    plt.ylim(-1, 1)
    plt.ylabel('$x_1$', fontsize='large')
    plt.yticks(np.arange(-1, 1.5, .5))

    im = plt.scatter(x=x_0, y=x_1, c=hr, marker='.', cmap=cmap)
    fig.colorbar(im)
    # plt.clim(0, 1)
    plt.clim(*clim)
    plt.tight_layout()
    return (fig, ax, im)

def save_fig(fig, fp):
    # TODO fit the pdf saving cutting off the x and y axis labels
    pp_true = PdfPages(fp)
    pp_true.savefig(fig, dpi=600)
    pp_true.close()

def plot_experiment_scatters(risk_fxn, dataset, norm_vals = None, output_file=None,
    figsize = (4,3), clim=(-3,3), cmap = 'jet', plot_error=False, trt_idx = None):

    def norm_hr(hr):
        # return hr
        return hr - hr.mean();
        # return (hr - hr.min()) / (hr.max() - hr.min())

    x_0 = dataset['x'][:, 0]
    x_1 = dataset['x'][:, 1]

    # Plot model predictions
    x = dataset['x']
    if norm_vals:
        x = (x - norm_vals['mean']) / norm_vals['std']

    (head, tail) = os.path.split(output_file)

    if not trt_idx is None:
        trt_values = np.unique(x[:,trt_idx])
        for (idx,trt_value) in enumerate(trt_values):
            x_trt = np.copy(x)
            x_trt[:,trt_idx] = trt_value
            hr_trt = risk_fxn(x_trt)
            hr_trt = norm_hr(hr_trt)
            fig_trt, _, _ = plot_risk_model(x_0, x_1, hr_trt, figsize, clim, cmap)

            if output_file:
                save_fig(fig_trt, os.path.join(head, "treatment_%d_" % idx + tail))
    else:
        hr_pred = risk_fxn(x)
        hr_pred = norm_hr(hr_pred)
        fig_pred, _, _ = plot_risk_model(x_0, x_1, hr_pred, figsize, clim, cmap)

        if output_file:
            save_fig(fig_pred, os.path.join(head, "pred_" + tail))

    if 'hr' in dataset:
        hr_true = dataset['hr']
        hr_true = norm_hr(hr_true)
        fig_true, _, _ = plot_risk_model(x_0, x_1, hr_true, figsize, clim, cmap)

        if output_file:
            save_fig(fig_true, os.path.join(head, "true_" + tail))

        if plot_error:
            hr_error = np.abs(hr_true - hr_pred)
            fig_error, _, _ = plot_risk_model(x_0, x_1, hr_error, figsize, clim=(0,20), cmap = cmap)

            if output_file:
                save_fig(fig_error, os.path.join(head, "error_" + tail))

def plot_survival_curves(rec_t, rec_e, antirec_t, antirec_e, experiment_name = '', output_file = None):
    # Set-up plots
    plt.figure(figsize=(12,3))
    ax = plt.subplot(111)

    # Fit survival curves
    kmf = KaplanMeierFitter()
    kmf.fit(rec_t, event_observed=rec_e, label=' '.join([experiment_name, "Recommendation"]))
    kmf.plot(ax=ax,linestyle="-")
    kmf.fit(antirec_t, event_observed=antirec_e, label=' '.join([experiment_name, "Anti-Recommendation"]))
    kmf.plot(ax=ax,linestyle="--")

    # Format graph
    plt.ylim(0,1);
    ax.set_xlabel('Timeline (months)',fontsize='large')
    ax.set_ylabel('Percentage of Population Alive',fontsize='large')

    # Calculate p-value
    results = logrank_test(rec_t, antirec_t, rec_e, antirec_e, alpha=.95)
    results.print_summary()

    # Location the label at the 1st out of 9 tick marks
    xloc = max(np.max(rec_t),np.max(antirec_t)) / 9
    if results.p_value < 1e-5:
        ax.text(xloc,.2,'$p < 1\mathrm{e}{-5}$',fontsize=20)
    else:
        ax.text(xloc,.2,'$p=%f$' % results.p_value,fontsize=20)
    plt.legend(loc='best',prop={'size':15})

    if output_file:
        plt.tight_layout()
        pylab.savefig(output_file)


text:
<?php

namespace Symfony\Component\Uid;

/**
 * @experimental in 5.1
 *
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 */
class NilUuid extends Uuid
{
    protected const TYPE = \UUID_TYPE_NULL;

    public function __construct()
    {
        $this->uid = '00000000-0000-0000-0000-000000000000';
    }
}


text:
You can find Python language examples in this folder.

## Connection management

- [Test a specified connection](test_connection.py)

## Manage Dashboards

- [Soft delete dashboard](soft_delete_dashboard.py)

## Manage Render Tasks

- [Download dashboard tile in specified format](download_tile.py)
- [Download look in specified format](download_look.py)
- [Generate and download dashboard PDFs](download_dashboard_pdf.py)

## User Management

- [Disable all active user sessions](logout_all_users.py)


text:
using System;

namespace Chloe.Server.Exceptions
{
    public class NotFoundException: Exception
    {
        public NotFoundException()
            :base("Entity Not Found")
        {
        }

        public NotFoundException(string message)
            :base(message)
        {

        }

        public NotFoundException(string message, Exception inner)
        {

        }
    }
}


text:
//
//  UIViewController+ScrollingNavbar.h
//  ScrollingNavbarDemo
//
//  Created by Andrea on 24/03/14.
//  Copyright (c) 2014 Andrea Mazzini. All rights reserved.
//

@import Foundation;
@import UIKit;

extern const NSInteger kAMScrollingNavBarOverlayTag;
/**-----------------------------------------------------------------------------
 * @name AMScrollingNavbarDelegate
 * -----------------------------------------------------------------------------
 */

@protocol AMScrollingNavbarDelegate <NSObject>
@optional

/** Navbar collapsed
 *
 * Called when the navbar change its state to collapsed
 */
- (void)navigationBarDidChangeToCollapsed:(BOOL)collapsed;

/** Navbar expanded
 *
 * Called when the navbar change its state to expanded
 */
- (void)navigationBarDidChangeToExpanded:(BOOL)expanded;

@end

@interface UIViewController (ScrollingNavbar) <UIGestureRecognizerDelegate>

/**-----------------------------------------------------------------------------
 * @name UIViewController+ScrollingNavbar
 * -----------------------------------------------------------------------------
 */

/** Scrolling init method
 *
 * Enables the scrolling on a generic UIView.
 * Also sets the value (in points) that needs to scroll through beofre the navbar is moved back into scene
 * Remember to call showNavbar or showNavBarAnimated: in your viewDidDisappear.
 *
 * @param scrollableView The UIView where the scrolling is performed.
 * @param delay The delay of the downward scroll gesture
 */
- (void)followScrollView:(UIView *)scrollableView withDelay:(float)delay;

/** Scrolling init method with Autolayout
 *
 * Enables the scrolling on a generic UIView.
 * It requires the top constraint of the first view below the navbar.
 * Remember to call showNavbar or showNavBarAnimated: in your viewDidDisappear.
 *
 * @param scrollableView The UIView where the scrolling is performed.
 * @param constraint The top constraint of the first view below the navbar
 */
- (void)followScrollView:(UIView *)scrollableView usingTopConstraint:(NSLayoutConstraint *)constraint;

/** Scrolling init method with Autolayout
 *
 * Enables the scrolling on a generic UIView.
 * It requires the top constraint of the first view below the navbar.
 * Also sets the value (in points) that needs to scroll through beofre the navbar is moved back into scene
 * Remember to call showNavbar or showNavBarAnimated: in your viewDidDisappear.
 *
 * @param scrollableView The UIView where the scrolling is performed.
 * @param constraint The top constraint of the first view below the navbar
 * @param delay The delay of the downward scroll gesture
 */
- (void)followScrollView:(UIView *)scrollableView usingTopConstraint:(NSLayoutConstraint *)constraint withDelay:(float)delay;

/** Scrolling init method
 *
 * Enables the scrolling on a generic UIView.
 * Remember to call showNavbar or showNavBarAnimated: in your viewDidDisappear.
 *
 * @param scrollableView The UIView where the scrolling is performed.
 */
- (void)followScrollView:(UIView *)scrollableView;

/** Navbar slide down
 *
 * Manually show the navbar
 */
- (void)showNavbar;

/** Navbar slide down
 *
 * Manually show the navbar
 *
 * @param animated Animates the navbar scrolling
 */
- (void)showNavBarAnimated:(BOOL)animated;

/** Navbar slide down
 *
 * Manually show the navbar
 */
- (void)hideNavbar;

/** Navbar slide up
 *
 * Manually hide the navbar
 *
 * @param animated Animates the navbar scrolling
 */
- (void)hideNavbarAnimated:(BOOL)animated;

/** Remove the scrollview tracking
 *
 * Use this method to stop following the navbar
 */
- (void)stopFollowingScrollView;

/** Enable or disable the scrolling
 *
 * Set this property to NO to disable the scrolling of the navbar.
 */
- (void)setScrollingEnabled:(BOOL)enabled;

/** Enable or disable the scrolling when the content size is smaller than the bounds
 *
 * Set this property to YES to enable the scrolling of the navbar even when the
 * content size of the scroll view is smaller than its height.
 */
- (void)setShouldScrollWhenContentFits:(BOOL)enabled;

/** Add scrolling to a custom view
 *
 * Enables the scrolling of a generic UIView placed underneath the navbar (e.g.: a custom header)
 * It requires the top constraint of the first view below the navbar.
 *
 * @param constraint The top constraint of the first view below the navbar
 * @param delay The height of the custom view
 */
- (void)setScrollableViewConstraint:(NSLayoutConstraint *)constraint withOffset:(CGFloat)offset;

/** AMScrollingNavbarDelegate setter
 *
 * Sets the AMScrollingNavbarDelegate
 *
 * @param scrollingNavbarDelegate The delegate
 */
- (void)setScrollingNavbarDelegate:(id <AMScrollingNavbarDelegate>)scrollingNavbarDelegate;

/** Use superview as container view
 *
 * Set the scrollable view's superview as main container.
 * Default to YES, set it to NO when using a UITableViewController or a UICollectionViewController
 *
 * @param useSuperview The BOOL flag.
 */
- (void)setUseSuperview:(BOOL)useSuperview;

- (void)setScrollingSuperview:(UIView*)superview;
- (void)setScrollingViewController:(UIViewController*)viewController;
- (BOOL)expanded;
@end