text:
/*
Package historytree implements part of Crosby's and Wallach's history tree data
structure, as presented in "Efficient Data Structures for Tamper-Evident Logging",
available at http://static.usenix.org/event/sec09/tech/full_papers/crosby.pdf .
We provide membership proofs and omit incremental proofs and signing roots.
We also support computing the updated roots on the history tree based on a
membership proof that fixes the rest of the tree. See the Balloon paper for details.
*/
package historytree

import (
	"errors"
	"math"
	"strconv"

	"github.com/mndrix/ps"
	"github.com/pylls/balloon/util"
)

var prefixZero = []byte{0x0}
var prefixOne = []byte{0x1}

// Tree is a history tree.
type Tree struct {
	//frozen map[Position][]byte
	//events map[int][]byte
	frozen ps.Map
	events ps.Map
	size   int
}

// Position is a position in the tree.
type Position struct {
	Index, Layer int
}

func (p *Position) toString() string {
	return strconv.Itoa(p.Index) + "." + strconv.Itoa(p.Layer)
}

// ProofPosition is a position and its hash in the tree.
type ProofPosition struct {
	Hash []byte
	Position
}

// MembershipProof is a proof of membership of an event.
type MembershipProof struct {
	Nodes          []ProofPosition
	Index, Version int
	Event, Root    []byte
}

// NewTree returns a new history tree.
func NewTree() (t *Tree) {
	t = new(Tree)
	t.size = 0
	t.frozen = ps.NewMap()
	t.events = ps.NewMap()
	return
}

// Clone creates a copy of the history tree.
func (t *Tree) Clone() (clone *Tree) {
	clone = new(Tree)
	clone.size = t.size
	clone.frozen = t.frozen
	clone.events = t.events
	return
}

// layeR, Index, Version
// See Figure 5 in "Efficient Data Structures for Tamper-Evident Logging"
func (t *Tree) getHashedNode(index, layer, version int, proofMode bool) (value []byte, err error) {
	// always prefer frozen hashes, if we have calculated them
	if proofMode || version >= index+util.Pow(2, layer)-1 {
		if t.isFrozenHash(index, layer) {
			return t.getFrozenHash(index, layer)
		}
	}

	// special case for child nodes
	if layer == 0 && version >= index {
		event, err := t.getEvent(index)
		if err != nil {
			return nil, errors.New("no event with the provided index")
		}

		value = util.Hash(prefixZero, event)
		// have version determine if the right node is there or not
	} else if version >= index+util.Pow(2, layer-1) {
		a1, err := t.getHashedNode(index, layer-1, version, proofMode)
		if err != nil {
			return nil, errors.New("failed to get internal node with index " + strconv.Itoa(index))
		}
		a2, err := t.getHashedNode(index+util.Pow(2, layer-1), layer-1, version, proofMode)
		if err != nil {
			return nil, errors.New("failed to get internal node with index " + strconv.Itoa(index))
		}

		value = util.Hash(prefixOne, a1, a2)
	} else {
		a, err := t.getHashedNode(index, layer-1, version, proofMode)
		if err != nil {
			return nil, errors.New("failed to get internal node with index " + strconv.Itoa(index))
		}
		value = util.Hash(prefixOne, a)
	}

	// should we add this to the frozen hash cache?
	if version >= index+util.Pow(2, layer)-1 {
		t.setFrozenHash(index, layer, value)
	}

	return
}

func (t *Tree) isFrozenHash(index, layer int) bool {
	p := new(Position)
	p.Index = index
	p.Layer = layer
	_, exists := t.frozen.Lookup(p.toString())
	return exists
}

func (t *Tree) setFrozenHash(index, layer int, value []byte) {
	p := new(Position)
	p.Index = index
	p.Layer = layer
	t.frozen = t.frozen.Set(p.toString(), value)
}

func (t *Tree) getFrozenHash(index, layer int) (value []byte, err error) {
	p := new(Position)
	p.Index = index
	p.Layer = layer
	v, exists := t.frozen.Lookup(p.toString())
	if !exists {
		return nil, errors.New("no such frozen hash")
	}

	return v.([]byte), nil
}

// MembershipProof generates a membership proof.
func (t *Tree) MembershipProof(index, version int) (proof MembershipProof, err error) {
	if index < 0 || index >= t.Size() || index > version {
		return proof, errors.New("invalid index, has to be: 0 <= index <= version < size")
	}

	proof.Index = index
	proof.Version = version
	proof.Event, err = t.getEvent(index)
	if err != nil {
		return
	}
	proof.Root, err = t.getHashedNode(0, t.calculateDepth(version+1), version, false)
	if err != nil {
		return
	}

	// we know that the biggest possible proof is one node per layer
	proof.Nodes = make([]ProofPosition, 0, t.getDepth())
	err = t.membershipProof(index, 0, t.getDepth(), version, &proof)
	return
}

// the game is: walk the tree from the root to the target leaf
func (t *Tree) membershipProof(target, index, layer, version int, proof *MembershipProof) (err error) {
	if layer == 0 {
		return
	}
	// the number of events to the left of the node
	n := index + util.Pow(2, layer-1)
	if target < n {
		// go left, but should we save right first? We need to save right if there are any leaf nodes
		// fixed by the right node (otherwise we know it's hash is nil), dictated by the version of the
		// tree we are generating
		if version >= n {
			p := new(ProofPosition)
			p.Index = n
			p.Layer = layer - 1
			p.Hash, err = t.getHashedNode(p.Index, p.Layer, version, false)
			if err != nil {
				return
			}
			proof.Nodes = append(proof.Nodes, *p)
		}
		return t.membershipProof(target, index, layer-1, version, proof)
	}
	// go right, once we have saved the left node
	p := new(ProofPosition)
	p.Index = index
	p.Layer = layer - 1
	p.Hash, err = t.getHashedNode(p.Index, p.Layer, version, false)
	if err != nil {
		return
	}
	proof.Nodes = append(proof.Nodes, *p)

	return t.membershipProof(target, n, layer-1, version, proof)

}

// Verify verifies a membership proof
func (p *MembershipProof) Verify() (correct bool) {
	if p.Root == nil || p.Event == nil || p.Index < 0 ||
		p.Version < 0 {
		return false
	}

	proofTree := NewTree()
	for _, n := range p.Nodes {
		proofTree.frozen = proofTree.frozen.Set(n.Position.toString(), n.Hash)
	}
	proofTree.events = proofTree.events.Set(strconv.Itoa(p.Index), p.Event)

	c, err := proofTree.getHashedNode(0, proofTree.calculateDepth(p.Version+1), p.Version, true)
	if err != nil {
		return false
	}

	return util.Equal(c, p.Root)
}

func (t *Tree) getEvent(index int) (event []byte, err error) {
	e, exists := t.events.Lookup(strconv.Itoa(index))
	if !exists {
		return nil, errors.New("no such event")
	}
	return e.([]byte), nil
}

func (t *Tree) setEvent(index int, event []byte) (err error) {
	_, exists := t.events.Lookup(strconv.Itoa(index))
	if exists {
		return errors.New("there is already an event with that index")
	}
	t.events = t.events.Set(strconv.Itoa(index), event)
	t.size++
	return
}

func (t *Tree) getDepth() (depth int) {
	return t.calculateDepth(t.size)
}

func (t *Tree) calculateDepth(n int) (depth int) {
	if n == 0 {
		return 0
	}
	return int(math.Ceil(math.Log2(float64(n))))
}

// Size returns the number of events in the tree.
func (t *Tree) Size() int {
	return t.size
}

// LatestVersion returns the latest version of the tree.
func (t *Tree) LatestVersion() int {
	return t.size - 1
}

// Add adds an event to the history tree.
func (t *Tree) Add(event []byte) (root []byte, err error) {
	err = t.setEvent(t.Size(), event)
	if err != nil {
		return
	}
	// Since we use getDepth() here, inside it, the depth is already +1 due to
	// len(t.events) being +1 due to the SetEvent above. This means that we get
	// a growing tree that supports an arbitrary number of events, as noted by
	// Crosby and Wallach on page 6.
	return t.getHashedNode(0, t.getDepth(), t.Size()-1, false)
}

// Update calculates the updated history tree, represented by the valid membership
// proof for the latest event inserted into a history tree, by inserting the provided
// events. Returns the updated root, or an error.
func (p *MembershipProof) Update(events [][]byte) (root []byte, version int, err error) {
	proofTree := NewTree()

	// set all the nodes in the proof, we know they are all frozen
	// due to the membership proof being on the last inserted event
	for _, n := range p.Nodes {
		proofTree.frozen = proofTree.frozen.Set(n.Position.toString(), n.Hash)
	}

	// check if we are updating an empty history tree or not
	var startIndex int
	if len(p.Event) == 0 {
		proofTree.size = 0
		startIndex = 0
	} else {
		proofTree.size = p.Version + 1
		startIndex = p.Index + 1
		// set the event we are proving to and the size of the pruned tree
		// to the size of the actual tree
		proofTree.events = proofTree.events.Set(strconv.Itoa(p.Index), p.Event)
	}

	// add all events in order of the slice
	for i := 0; i < len(events); i++ {
		err = proofTree.setEvent(startIndex+i, events[i])
		if err != nil {
			return
		}
	}

	return proofTree.Root(), proofTree.Size() - 1, nil
}

// Root returns the current root of the tree.
func (t *Tree) Root() (c []byte) {
	if t.Size() > 0 {
		c, _ = t.getHashedNode(0, t.getDepth(), t.Size()-1, false)
	}
	return
}

// Size returns the size in bytes of a membership proof.
func (p *MembershipProof) Size() (bytes int) {
	bytes = 8 + 8 + len(p.Root) + len(p.Event)
	bytes = bytes + len(p.Nodes)*(16+util.HashOutputLen)
	return
}


text:
layout: tagpage
tag: re_imaginings
---

redpajama_set_name: RedPajamaGithub


text:
from control4.cloud.cloud_interface import load_cloud_config,create_cloud,get_slave_names
import argparse

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("--start_slaves",action="store_true")
    parser.add_argument("--slave_prefix")
    parser.add_argument("--num_slaves",type=int)
    parser.add_argument("--start_master",action="store_true")
    parser.add_argument("--master_name",type=str,default="master")
    parser.add_argument("--slave_start_idx",type=int,default=0)
    parser.add_argument("--list",action="store_true")
    parser.add_argument("--dry",action="store_true")
    args = parser.parse_args()

    cloud_config = load_cloud_config()
    cloud = create_cloud(cloud_config)

    instance_names = []
    if args.start_slaves:
        instance_names.extend(get_slave_names(args.num_slaves,instance_prefix=args.slave_prefix,start_idx=args.slave_start_idx))
    if args.start_master:
        instance_names.append(args.master_name)
    if len(instance_names)>0: cloud.start_instances(instance_names=instance_names,dry=args.dry)
    if args.list:
        print "**** ALL INSTANCES ****"
        infos = cloud.list_instances()
        for info in infos:
            print cloud.instance_name(info), cloud.instance_address(info)
        print "**** CLUSTERS ****"
        cluster_names = cloud.get_cluster_names(infos)
        "\n".join(cluster_names)

    # cloud.start_instances()

if __name__ == "__main__":
    main()


text:
import { StackNavigator } from 'react-navigation';
import screens from '../constants/screens';
import { OnBoarding } from '../screens';
import NavigatorDrawer from './NavigatorDrawer';

const routes = {
  [screens.OnBoarding]: {
    screen: OnBoarding,
    headerMode: 'screen',
  },
  [screens.DrawerRoot]: {
    screen: NavigatorDrawer,
    headerMode: 'screen',
    navigationOptions: {
      header: null,
    },
  },
};

export default StackNavigator(routes);


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cdn.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** The level at which the content needs to be cached. */
public final class CacheType extends ExpandableStringEnum<CacheType> {
    /** Static value All for CacheType. */
    public static final CacheType ALL = fromString("All");

    /**
     * Creates or finds a CacheType from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding CacheType.
     */
    @JsonCreator
    public static CacheType fromString(String name) {
        return fromString(name, CacheType.class);
    }

    /**
     * Gets known CacheType values.
     *
     * @return known CacheType values.
     */
    public static Collection<CacheType> values() {
        return values(CacheType.class);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <meta name="description" content="" />
    <meta name="author" content="" />
    <link rel="icon" href="./favicon.ico" />

    <title th:text="#{project_name}">Dashboard Template for Bootstrap</title>

    <link href="/assets/css/bootstrap.min.css" rel="stylesheet" />
    <link href="/assets/css/dashboard.css" rel="stylesheet" />

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Project name

Dashboard

Settings

Profile

Help

          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search..." />
          </form>

Overview

パーティ検討 (current)

メモリア検討

アイテム検討

パーティ検討

評価条件

          <form method="post" th:action="@{/party/search}">
            <input type="submit" value="検索" />
          </form>

パーティ一覧


text:
import { BASE_URL } from '../Constant/constant';
import {
  FETCH_COUNTRY,
  FETCH_COMPONENT,
  TEST_CONNECTION
} from '../actions/SharedDataAction';

// TODO:
export default function(state=[], action) {
  switch(action.type) {
    case FETCH_COUNTRY:
      return Object.assign({}, state, {
        countries: action.payload.data
      });
    case FETCH_COMPONENT:
      return Object.assign({}, state, {
        components: action.payload.data
      });
    case TEST_CONNECTION:
      return Object.assign({}, state, {
        testConnection: action.payload.data
      });
    default:
      return state;
  }
}


text:
/**
 * Cache mixin. Requires a storage mixin to be applied first.
 *
 * @param {Object} cls The class/object to which this mixin should be applied.
 * @param {int} timeout The cache timeout, in seconds.
 * @mixin
 * @todo Garbage collection.
 * @todo LRU or other more scalable cache types.
 */
function Cache(cls, timeout) {
  var mdl = cls._mdl.plugin('Cache', 'Local cache');

  if (typeof timeout !== 'number' || timeout <= 0) {
    timeout = false;
  }

  /* Prevent internal _cache flag from showing up while enumerating. */
  Object.defineProperty(cls.prototype, '_cache', {
    configurable: false,
    enumerable: false,
    writable: true
  });

  var cache = {};

  /**
   * Closure to set a cache entry.
   *
   * @param {string} id
   * @param {Object} entry
   */
  function setEntry(id, entry) {
    /* Set an entry to undefined to delete it. */
    if (entry === undefined) {
      delete cache[id];
      return;
    }

    /* Don't re-cache entries that come from the cache. */
    if (entry._cache) return;

    entry._cache = true;
    cache[id] = [
      timeout ? new Date().valueOf() + timeout : false,
      entry
    ];
  }

  /**
   * Closure to get a local cache entry.
   *
   * @param {string} id
   * @return {Object} The entry, if found and not expired. Undefined otherwise.
   */
  function getEntry(id) {
    var entry;
    if (cache[id]) {
      if (!timeout || (new Date().valueOf() < cache[id][0])) {
        return cache[id][1]
      }
      delete cache[id];
    }
    return undefined;
  }

  /**
   * The cache hooks in before the asynchronous get call. It injects a result before an asynch call is necessary.
   */
  mdl.on("beforeGet", function(event) {
    if (event.handled) return; /* Bail if we can't do anything. */

    var cls = event.target;
    var id = event.data;

    if (id instanceof Array) {
      var entries = [];
      for (var i = 0; i < id.length; i++) {
        var entry = getEntry(id[i]);

        if (!entry) return;

        entries.push(entry);
      }
      event.success(entries);
    } else {
      var entry = getEntry(id);
      if (entry) {
        event.success(entry);
      }
    }
  });

  /**
   * Save the object after it is retrieved elsewhere.
   */
  mdl.on("afterGet", function(event) {
    if (event.error) return;

    var res = event.result;

    if (!(res instanceof Array)) res = [res];

    for (var i = 0; i < res.length; i++) {
      setEntry(res[i].id, res[i]);
    }
  });

  /**
   * If something calls purge, we follow suit.
   */
  mdl.on("afterPurge", function(event) {
    cache = {};
  });

  /**
   * If something is deleted, clear its cache entry.
   */
  mdl.on("afterDelete", function(event) {
    setEntry(event.target.id, undefined);
  });

  /**
   * If something is saved, clear its cache flag.
   */
  mdl.on("beforeSave", function(event) {
    var obj = event.target;
    if (obj._cache) {
      obj._cache = false;
    }
  });

  /**
   * Put an object into cache after saving so long as there was no error.
   */
  mdl.on("afterSave", function(event) {
    if (event.error) return;

    var obj = event.target;
    setEntry(obj.id, obj);
  });
}

module.exports = Cache;


text:
<!DOCTYPE html>
<html lang="en">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Default example - Fileuploader</title>

		<!-- Google Fonts -->
		<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">

		<!-- styles -->
		<link href="../../src/jquery.fileuploader.css" media="all" rel="stylesheet">

		<!-- js -->
		<script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
		<script src="../../src/jquery.fileuploader.min.js" type="text/javascript"></script>
		<script src="./js/custom.js" type="text/javascript"></script>

		<style>
			body {
				font-family: 'Roboto', sans-serif;
				font-size: 14px;
                line-height: normal;
				color: #47525d;
				background-color: #fff;

				margin: 0;
				padding: 20px;

				width: 560px;
			}
		</style>
	</head>

	<body>
		<form action="php/form_upload.php" method="post" enctype="multipart/form-data">
			<input type="file" name="files">
			<input type="submit">
		</form>
    </body>
</html>


text:
<?php

namespace source\modules\tools\admin\controllers;

use Yii;
use source\LuLu;
use source\modules\tools\models\CacheForm;
use source\core\base\BackController;

class CacheController extends BackController
{
    public function actionIndex() {
        $model = new CacheForm();

        if (app()->request->isPost && $model->load(app()->request->post())) {
            if ($model->cache) {
                app()->cache->flush();
                app()->schemaCache->flush();
            }

            if ($model->asset) {
                $assetDir = Yii::getAlias('@assets');
                //FileHelper::removeDirectoryContent($assetDir);
            }

            return $this->redirect(['index']);
        }

        return $this->render('index', ['model' => $model]);
    }
}


text:
namespace DiscUtils.Iscsi
{
    /// <summary>
    /// Reasons for iSCSI login sucess or failure.
    /// </summary>
    public enum LoginStatusCode
    {
        /// <summary>
        /// Login succeeded
        /// </summary>
        Success = 0,

        /// <summary>
        /// The iSCSI target name has moved temporarily to a new address.
        /// </summary>
        TargetMovedTemporarily = 0x0101,

        /// <summary>
        /// The iSCSI target name has moved permanently to a new address.
        /// </summary>
        TargetMovedPermanently = 0x0102,

        /// <summary>
        /// The Initiator was at fault.
        /// </summary>
        InitiatorError = 0x0200,

        /// <summary>
        /// The Initiator could not be authenticated, or the Target doesn't support authentication.
        /// </summary>
        AuthenticationFailure = 0x0201,

        /// <summary>
        /// The Initiator is not permitted to access the given Target.
        /// </summary>
        AuthorizationFailure = 0x0202,

        /// <summary>
        /// The given iSCSI Target Name was not found.
        /// </summary>
        NotFound = 0x0203,

        /// <summary>
        /// The Target has been removed, and no new address provided.
        /// </summary>
        TargetRemoved = 0x0204,

        /// <summary>
        /// The Target does not support this version of the iSCSI protocol.
        /// </summary>
        UnsupportedVersion = 0x0205,

        /// <summary>
        /// Too many connections for this iSCSI session.
        /// </summary>
        TooManyConnections = 0x0206,

        /// <summary>
        /// A required parameter is missing.
        /// </summary>
        MissingParameter = 0x0207,

        /// <summary>
        /// The Target does not support session spanning to this connection (address).
        /// </summary>
        CannotIncludeInSession = 0x0208,

        /// <summary>
        /// The Target does not support this type of session (or not from this Initiator).
        /// </summary>
        SessionTypeNotSupported = 0x0209,

        /// <summary>
        /// Attempt to add a connection to a non-existent session.
        /// </summary>
        SessionDoesNotExist = 0x020A,

        /// <summary>
        /// An invalid request was sent during the login sequence.
        /// </summary>
        InvalidDuringLogin = 0x020B,

        /// <summary>
        /// The Target suffered an unknown hardware or software failure.
        /// </summary>
        TargetError = 0x0300,

        /// <summary>
        /// The iSCSI service or Target is not currently operational.
        /// </summary>
        ServiceUnavailable = 0x0301,

        /// <summary>
        /// The Target is out of resources.
        /// </summary>
        OutOfResources = 0x0302
    }
}


text:
package ro.isdc.wro.http;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.CountingOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ro.isdc.wro.http.support.HttpHeader;
import ro.isdc.wro.http.support.RedirectedStreamServletResponseWrapper;
import ro.isdc.wro.model.resource.locator.support.DispatcherStreamLocator;
import ro.isdc.wro.util.WroUtil;

/**
 * A filter responsible for gzipping all content served through this filter.
 *
 * @author Alex Objelean
 * @created 11 Apr 2013
 * @since 1.7.0
 */
public class GzipFilter
    implements Filter {
  private static final Logger LOG = LoggerFactory.getLogger(GzipFilter.class);

  /**
   * {@inheritDoc}
   */
  public void init(final FilterConfig filterConfig)
      throws ServletException {
  }

  /**
   * {@inheritDoc}
   */
  public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
      throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    if (isGzipAllowed(request)) {
      doGzipResponse(request, response, chain);
    } else {
      LOG.debug("Gzip not allowed. Proceeding with chain.");
      chain.doFilter(request, response);
    }
  }

  /**
   * Performs actual gzip of the filtered content.
   */
  private void doGzipResponse(final HttpServletRequest req, final HttpServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    LOG.debug("Applying gzip on resource: {}", req.getRequestURI());
    response.setHeader(HttpHeader.CONTENT_ENCODING.toString(), "gzip");
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final CountingOutputStream countingStream = new CountingOutputStream(new GZIPOutputStream(new BufferedOutputStream(
        baos)));
    // final GZIPOutputStream gzout = new GZIPOutputStream(new BufferedOutputStream(baos));
    // Perform gzip operation in-memory before sending response
    final HttpServletResponseWrapper wrappedResponse = new RedirectedStreamServletResponseWrapper(countingStream,
        response);
    chain.doFilter(req, wrappedResponse);
    // close underlying stream
    countingStream.close();
    response.setContentLength(countingStream.getCount());
    // avoid NO CONTENT error thrown by jetty when gzipping empty response
    if (countingStream.getCount() > 0) {
      IOUtils.write(baos.toByteArray(), response.getOutputStream());
    }
  }

  /**
   * Checks if the request supports gzip and is not a include request (these cannot be gzipped)
   */
  private boolean isGzipAllowed(final HttpServletRequest request) {
    return !DispatcherStreamLocator.isIncludedRequest(request) && WroUtil.isGzipSupported(request);
  }

  /**
   * {@inheritDoc}
   */
  public void destroy() {
  }

}


text:
//------------------------------------------------------------------------------
// <copyright file="DataGridViewTextBoxCell.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Windows.Forms
{
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.ComponentModel;
    using System.Windows.Forms.Internal;
    using System.Globalization;

    /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell"]/*' />
    /// <devdoc>
    ///    <para>Identifies a cell in the dataGridView.</para>
    /// </devdoc>
    public class DataGridViewTextBoxCell : DataGridViewCell
    {
        private static readonly int PropTextBoxCellMaxInputLength = PropertyStore.CreateKey();
        private static readonly int PropTextBoxCellEditingTextBox = PropertyStore.CreateKey();

        private const byte DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick = 0x01;
        private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft = 3;
        private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight = 4;
        private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft = 0;
        private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight = 0;
        private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop = 2;
        private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetBottom = 1;
        private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping = 1;
        private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping = 2;
        private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom = 1;

        private const int DATAGRIDVIEWTEXTBOXCELL_maxInputLength = 32767;

        private byte flagsState;  // see DATAGRIDVIEWTEXTBOXCELL_ consts above

        private static Type defaultFormattedValueType = typeof(System.String);
        private static Type defaultValueType = typeof(System.Object);
        private static Type cellType = typeof(DataGridViewTextBoxCell);

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.DataGridViewTextBoxCell"]/*' />
        public DataGridViewTextBoxCell()
        {
        }

        private DataGridViewTextBoxEditingControl EditingTextBox
        {
            get
            {
                return (DataGridViewTextBoxEditingControl) this.Properties.GetObject(PropTextBoxCellEditingTextBox);
            }
            set
            {
                if (value != null || this.Properties.ContainsObject(PropTextBoxCellEditingTextBox))
                {
                    this.Properties.SetObject(PropTextBoxCellEditingTextBox, value);
                }
            }
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.FormattedValueType"]/*' />
        public override Type FormattedValueType
        {
            get
            {
                // we return string for the formatted type
                return defaultFormattedValueType;
            }
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.MaxInputLength"]/*' />
        [DefaultValue(DATAGRIDVIEWTEXTBOXCELL_maxInputLength)]
        public virtual int MaxInputLength
        {
            get
            {
                bool found;
                int maxInputLength = this.Properties.GetInteger(PropTextBoxCellMaxInputLength, out found);
                if (found)
                {
                    return maxInputLength;
                }
                return DATAGRIDVIEWTEXTBOXCELL_maxInputLength;
            }
            set
            {
                // VSWhidbey 515823
                //if (this.DataGridView != null && this.RowIndex == -1)
                //{
                //    throw new InvalidOperationException(SR.GetString(SR.DataGridView_InvalidOperationOnSharedCell));
                //}
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("MaxInputLength", SR.GetString(SR.InvalidLowBoundArgumentEx, "MaxInputLength", value.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
                }
                this.Properties.SetInteger(PropTextBoxCellMaxInputLength, value);
                if (OwnsEditingTextBox(this.RowIndex))
                {
                    this.EditingTextBox.MaxLength = value;
                }
            }
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.ValueType"]/*' />
        public override Type ValueType
        {
            get
            {
                Type valueType = base.ValueType;
                if (valueType != null)
                {
                    return valueType;
                }
                return defaultValueType;
            }
        }

        // Called when the row that owns the editing control gets unshared.
        internal override void CacheEditingControl()
        {
            this.EditingTextBox = this.DataGridView.EditingControl as DataGridViewTextBoxEditingControl;
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.Clone"]/*' />
        public override object Clone()
        {
            DataGridViewTextBoxCell dataGridViewCell;
            Type thisType = this.GetType();
            if(thisType == cellType) //performance improvement
            {
                dataGridViewCell = new DataGridViewTextBoxCell();
            }
            else
            {
                // SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info..
                //
                dataGridViewCell = (DataGridViewTextBoxCell)System.Activator.CreateInstance(thisType);
            }
            base.CloneInternal(dataGridViewCell);
            dataGridViewCell.MaxInputLength = this.MaxInputLength;
            return dataGridViewCell;
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.DetachEditingControl"]/*' />
        [
            EditorBrowsable(EditorBrowsableState.Advanced)
        ]
        public override void DetachEditingControl()
        {
            DataGridView dgv = this.DataGridView;
            if (dgv == null || dgv.EditingControl == null)
            {
                throw new InvalidOperationException();
            }

            TextBox textBox = dgv.EditingControl as TextBox;
            if (textBox != null)
            {
                textBox.ClearUndo();
            }

            this.EditingTextBox = null;

            base.DetachEditingControl();
        }

        private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds, DataGridViewCellStyle cellStyle)
        {
            Debug.Assert(cellStyle.WrapMode != DataGridViewTriState.NotSet);
            Debug.Assert(this.DataGridView != null);

            TextBox txtEditingControl = this.DataGridView.EditingControl as TextBox;
            int originalWidth = editingControlBounds.Width;
            if (txtEditingControl != null)
            {
                switch (cellStyle.Alignment)
                {
                    case DataGridViewContentAlignment.TopLeft:
                    case DataGridViewContentAlignment.MiddleLeft:
                    case DataGridViewContentAlignment.BottomLeft:
                        // Add 3 pixels on the left of the editing control to match non-editing text position
                        if (this.DataGridView.RightToLeftInternal)
                        {
                            editingControlBounds.X += 1;
                            editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 2);
                        }
                        else
                        {
                            editingControlBounds.X += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft;
                            editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 1);
                        }
                        break;

                    case DataGridViewContentAlignment.TopCenter:
                    case DataGridViewContentAlignment.MiddleCenter:
                    case DataGridViewContentAlignment.BottomCenter:
                        editingControlBounds.X += 1;
                        editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - 3);
                        break;

                    case DataGridViewContentAlignment.TopRight:
                    case DataGridViewContentAlignment.MiddleRight:
                    case DataGridViewContentAlignment.BottomRight:
                        // Shorten the editing control by 5 pixels to match non-editing text position
                        if (this.DataGridView.RightToLeftInternal)
                        {
                            editingControlBounds.X += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1;
                            editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight);
                        }
                        else
                        {
                            editingControlBounds.X += 1;
                            editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1);
                        }
                        break;
                }

                switch (cellStyle.Alignment)
                {
                    case DataGridViewContentAlignment.TopLeft:
                    case DataGridViewContentAlignment.TopCenter:
                    case DataGridViewContentAlignment.TopRight:
                        editingControlBounds.Y += DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop;
                        editingControlBounds.Height = Math.Max(0, editingControlBounds.Height - DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop);
                        break;

                    case DataGridViewContentAlignment.MiddleLeft:
                    case DataGridViewContentAlignment.MiddleCenter:
                    case DataGridViewContentAlignment.MiddleRight:
                        editingControlBounds.Height++;
                        break;

                    case DataGridViewContentAlignment.BottomLeft:
                    case DataGridViewContentAlignment.BottomCenter:
                    case DataGridViewContentAlignment.BottomRight:
                        editingControlBounds.Height = Math.Max(0, editingControlBounds.Height - DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetBottom);
                        break;
                }

                int preferredHeight;
                if (cellStyle.WrapMode == DataGridViewTriState.False)
                {
                    preferredHeight = txtEditingControl.PreferredSize.Height;
                }
                else
                {
                    string editedFormattedValue = (string) ((IDataGridViewEditingControl) txtEditingControl).GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting);
                    if (string.IsNullOrEmpty(editedFormattedValue))
                    {
                        editedFormattedValue = " ";
                    }
                    TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
                    using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
                    {
                        preferredHeight = DataGridViewCell.MeasureTextHeight(g, editedFormattedValue, cellStyle.Font, originalWidth, flags);
                    }
                }
                if (preferredHeight < editingControlBounds.Height)
                {
                    switch (cellStyle.Alignment)
                    {
                        case DataGridViewContentAlignment.TopLeft:
                        case DataGridViewContentAlignment.TopCenter:
                        case DataGridViewContentAlignment.TopRight:
                            // Single pixel move - leave it as is for now
                            break;
                        case DataGridViewContentAlignment.MiddleLeft:
                        case DataGridViewContentAlignment.MiddleCenter:
                        case DataGridViewContentAlignment.MiddleRight:
                            editingControlBounds.Y += (editingControlBounds.Height - preferredHeight) / 2;
                            break;
                        case DataGridViewContentAlignment.BottomLeft:
                        case DataGridViewContentAlignment.BottomCenter:
                        case DataGridViewContentAlignment.BottomRight:
                            editingControlBounds.Y += editingControlBounds.Height - preferredHeight;
                            break;
                    }
                }
            }

            return editingControlBounds;
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.GetContentBounds"]/*' />
        protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
        {
            if (cellStyle == null)
            {
                throw new ArgumentNullException("cellStyle");
            }

            if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null)
            {
                return Rectangle.Empty;
            }

            object value = GetValue(rowIndex);
            object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting);

            DataGridViewAdvancedBorderStyle dgvabsEffective;
            DataGridViewElementStates cellState;
            Rectangle cellBounds;

            ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);

            Rectangle textBounds = PaintPrivate(graphics,
                cellBounds,
                cellBounds,
                rowIndex,
                cellState,
                formattedValue,
                null /*errorText*/,                 // textBounds is independent of errorText
                cellStyle,
                dgvabsEffective,
                DataGridViewPaintParts.ContentForeground,
                true /*computeContentBounds*/,
                false /*computeErrorIconBounds*/,
                false /*paint*/);

#if DEBUG
            Rectangle textBoundsDebug = PaintPrivate(graphics,
                cellBounds,
                cellBounds,
                rowIndex,
                cellState,
                formattedValue,
                GetErrorText(rowIndex),
                cellStyle,
                dgvabsEffective,
                DataGridViewPaintParts.ContentForeground,
                true /*computeContentBounds*/,
                false /*computeErrorIconBounds*/,
                false /*paint*/);
            Debug.Assert(textBoundsDebug.Equals(textBounds));
#endif

            return textBounds;
        }

        /// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetErrorIconBounds"]/*' />
        protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
        {
            if (cellStyle == null)
            {
                throw new ArgumentNullException("cellStyle");
            }

            if (this.DataGridView == null ||
                rowIndex < 0 ||
                this.OwningColumn == null ||
                !this.DataGridView.ShowCellErrors ||
                String.IsNullOrEmpty(GetErrorText(rowIndex)))
            {
                return Rectangle.Empty;
            }

            DataGridViewAdvancedBorderStyle dgvabsEffective;
            DataGridViewElementStates cellState;
            Rectangle cellBounds;

            ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);

            Rectangle errorBounds = PaintPrivate(graphics,
                cellBounds,
                cellBounds,
                rowIndex,
                cellState,
                null /*formattedValue*/,            // errorIconBounds is independent of formattedValue
                GetErrorText(rowIndex),
                cellStyle,
                dgvabsEffective,
                DataGridViewPaintParts.ContentForeground,
                false /*computeContentBounds*/,
                true /*computeErrorIconBounds*/,
                false /*paint*/);

#if DEBUG
            object value = GetValue(rowIndex);
            object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting);

            Rectangle errorBoundsDebug = PaintPrivate(graphics,
                cellBounds,
                cellBounds,
                rowIndex,
                cellState,
                formattedValue,
                GetErrorText(rowIndex),
                cellStyle,
                dgvabsEffective,
                DataGridViewPaintParts.ContentForeground,
                false /*computeContentBounds*/,
                true /*computeErrorIconBounds*/,
                false /*paint*/);
            Debug.Assert(errorBoundsDebug.Equals(errorBounds));
#endif

            return errorBounds;
        }

        /// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetPreferredSize"]/*' />
        protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
        {
            if (this.DataGridView == null)
            {
                return new Size(-1, -1);
            }

            if (cellStyle == null)
            {
                throw new ArgumentNullException("cellStyle");
            }

            Size preferredSize;
            Rectangle borderWidthsRect = this.StdBorderWidths;
            int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal;
            int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical;
            DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize);
            object formattedValue = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize);
            string formattedString = formattedValue as string;
            if (string.IsNullOrEmpty(formattedString))
            {
                formattedString = " ";
            }
            TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
            if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1)
            {
                switch (freeDimension)
                {
                    case DataGridViewFreeDimension.Width:
                    {
                        preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics,
                                                                                formattedString,
                                                                                cellStyle.Font,
                                                                                Math.Max(1, constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom),
                                                                                flags),
                                                 0);
                        break;
                    }
                    case DataGridViewFreeDimension.Height:
                    {
                        preferredSize = new Size(0,
                                                 DataGridViewCell.MeasureTextHeight(graphics,
                                                                                formattedString,
                                                                                cellStyle.Font,
                                                                                Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight),
                                                                                flags));
                        break;
                    }
                    default:
                    {
                        preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics,
                                                                                formattedString,
                                                                                cellStyle.Font,
                                                                                5.0F,
                                                                                flags);
                        break;
                    }
                }
            }
            else
            {
                switch (freeDimension)
                {
                    case DataGridViewFreeDimension.Width:
                    {
                        preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width,
                                                 0);
                        break;
                    }
                    case DataGridViewFreeDimension.Height:
                    {
                        preferredSize = new Size(0,
                                                 DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height);
                        break;
                    }
                    default:
                    {
                        preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags);
                        break;
                    }
                }
            }

            if (freeDimension != DataGridViewFreeDimension.Height)
            {
                preferredSize.Width += DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight + borderAndPaddingWidths;
                if (this.DataGridView.ShowCellErrors)
                {
                    // Making sure that there is enough room for the potential error icon
                    preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth);
                }
            }
            if (freeDimension != DataGridViewFreeDimension.Width)
            {
                int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping;
                preferredSize.Height += verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom + borderAndPaddingHeights;
                if (this.DataGridView.ShowCellErrors)
                {
                    // Making sure that there is enough room for the potential error icon
                    preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight);
                }
            }
            return preferredSize;
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.InitializeEditingControl"]/*' />
        public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            Debug.Assert(this.DataGridView != null &&
                         this.DataGridView.EditingPanel != null &&
                         this.DataGridView.EditingControl != null);
            Debug.Assert(!this.ReadOnly);
            base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
            TextBox textBox = this.DataGridView.EditingControl as TextBox;
            if (textBox != null)
            {
                textBox.BorderStyle = BorderStyle.None;
                textBox.AcceptsReturn = textBox.Multiline = dataGridViewCellStyle.WrapMode == DataGridViewTriState.True;
                textBox.MaxLength = this.MaxInputLength;
                string initialFormattedValueStr = initialFormattedValue as string;
                if (initialFormattedValueStr == null)
                {
                    textBox.Text = string.Empty;
                }
                else
                {
                    textBox.Text = initialFormattedValueStr;
                }

                this.EditingTextBox = this.DataGridView.EditingControl as DataGridViewTextBoxEditingControl;
            }
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.KeyEntersEditMode"]/*' />
        public override bool KeyEntersEditMode(KeyEventArgs e)
        {
            if (((char.IsLetterOrDigit((char)e.KeyCode) && !(e.KeyCode >= Keys.F1 && e.KeyCode <= Keys.F24)) ||
                 (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.Divide) ||
                 (e.KeyCode >= Keys.OemSemicolon && e.KeyCode <= Keys.Oem102) ||
                 (e.KeyCode == Keys.Space && !e.Shift)) &&
                !e.Alt &&
                !e.Control)
            {
                return true;
            }
            return base.KeyEntersEditMode(e);
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.OnEnter"]/*' />
        protected override void OnEnter(int rowIndex, bool throughMouseClick)
        {
            if (this.DataGridView == null)
            {
                return;
            }
            if (throughMouseClick)
            {
                this.flagsState |= (byte)DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick;
            }
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.OnLeave"]/*' />
        protected override void OnLeave(int rowIndex, bool throughMouseClick)
        {
            if (this.DataGridView == null)
            {
                return;
            }
            this.flagsState = (byte)(this.flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick);
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.OnMouseClick"]/*' />
        protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
            if (this.DataGridView == null)
            {
                return;
            }
            Debug.Assert(e.ColumnIndex == this.ColumnIndex);
            Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
            if (ptCurrentCell.X == e.ColumnIndex && ptCurrentCell.Y == e.RowIndex && e.Button == MouseButtons.Left)
            {
                if ((this.flagsState & DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick) != 0x00)
                {
                    this.flagsState = (byte)(this.flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick);
                }
                else if (this.DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically)
                {
                    this.DataGridView.BeginEdit(true /*selectAll*/);
                }
            }
        }

        private bool OwnsEditingTextBox(int rowIndex)
        {
            return rowIndex != -1 && this.EditingTextBox != null && rowIndex == ((IDataGridViewEditingControl)this.EditingTextBox).EditingControlRowIndex;
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.Paint"]/*' />
        protected override void Paint(Graphics graphics,
            Rectangle clipBounds,
            Rectangle cellBounds,
            int rowIndex,
            DataGridViewElementStates cellState,
            object value,
            object formattedValue,
            string errorText,
            DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts)
        {
            if (cellStyle == null)
            {
                throw new ArgumentNullException("cellStyle");
            }

            PaintPrivate(graphics,
                clipBounds,
                cellBounds,
                rowIndex,
                cellState,
                formattedValue,
                errorText,
                cellStyle,
                advancedBorderStyle,
                paintParts,
                false /*computeContentBounds*/,
                false /*computeErrorIconBounds*/,
                true /*paint*/);
        }

        // PaintPrivate is used in three places that need to duplicate the paint code:
        // 1. DataGridViewCell::Paint method
        // 2. DataGridViewCell::GetContentBounds
        // 3. DataGridViewCell::GetErrorIconBounds
        //
        // if computeContentBounds is true then PaintPrivate returns the contentBounds
        // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
        // else it returns Rectangle.Empty;
        private Rectangle PaintPrivate(Graphics graphics,
            Rectangle clipBounds,
            Rectangle cellBounds,
            int rowIndex,
            DataGridViewElementStates cellState,
            object formattedValue,
            string errorText,
            DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts,
            bool computeContentBounds,
            bool computeErrorIconBounds,
            bool paint)
        {
            // Parameter checking.
            // One bit and one bit only should be turned on
            Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
            Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
            Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
            Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
            Debug.Assert(cellStyle != null);

            // If computeContentBounds == TRUE then resultBounds will be the contentBounds.
            // If computeErrorIconBounds == TRUE then resultBounds will be the error icon bounds.
            // Else resultBounds will be Rectangle.Empty;
            Rectangle resultBounds = Rectangle.Empty;

            if (paint && DataGridViewCell.PaintBorder(paintParts))
            {
                PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            }

            Rectangle borderWidths = BorderWidths(advancedBorderStyle);
            Rectangle valBounds = cellBounds;
            valBounds.Offset(borderWidths.X, borderWidths.Y);
            valBounds.Width -= borderWidths.Right;
            valBounds.Height -= borderWidths.Bottom;

            SolidBrush br;

            Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
            bool cellCurrent = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex;
            bool cellEdited = cellCurrent && this.DataGridView.EditingControl != null;
            bool cellSelected = (cellState & DataGridViewElementStates.Selected) != 0;

            if (DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected && !cellEdited)
            {
                br = this.DataGridView.GetCachedBrush(cellStyle.SelectionBackColor);
            }
            else
            {
                br = this.DataGridView.GetCachedBrush(cellStyle.BackColor);
            }

            if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 0 && valBounds.Height > 0)
            {
                graphics.FillRectangle(br, valBounds);
            }

            if (cellStyle.Padding != Padding.Empty)
            {
                if (this.DataGridView.RightToLeftInternal)
                {
                    valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
                }
                else
                {
                    valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
                }
                valBounds.Width -= cellStyle.Padding.Horizontal;
                valBounds.Height -= cellStyle.Padding.Vertical;
            }

            if (paint && cellCurrent && !cellEdited)
            {
                // Draw focus rectangle
                if (DataGridViewCell.PaintFocus(paintParts) &&
                    this.DataGridView.ShowFocusCues &&
                    this.DataGridView.Focused &&
                    valBounds.Width > 0 &&
                    valBounds.Height > 0)
                {
                    ControlPaint.DrawFocusRectangle(graphics, valBounds, Color.Empty, br.Color);
                }
            }

            Rectangle errorBounds = valBounds;
            string formattedString = formattedValue as string;

            if (formattedString != null && ((paint && !cellEdited) || computeContentBounds))
            {
                // Font independent margins
                int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping;
                valBounds.Offset(DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft, verticalTextMarginTop);
                valBounds.Width -= DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight;
                valBounds.Height -= verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom;
                if (valBounds.Width > 0 && valBounds.Height > 0)
                {
                    TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
                    if (paint)
                    {
                        if (DataGridViewCell.PaintContentForeground(paintParts))
                        {
                            if ((flags & TextFormatFlags.SingleLine) != 0)
                            {
                                flags |= TextFormatFlags.EndEllipsis;
                            }
                            TextRenderer.DrawText(graphics,
                                formattedString,
                                cellStyle.Font,
                                valBounds,
                                cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor,
                                flags);
                        }
                    }
                    else
                    {
                        resultBounds = DataGridViewUtilities.GetTextBounds(valBounds, formattedString, flags, cellStyle);
                    }
                }
            }
            else if (computeErrorIconBounds)
            {
                if (!String.IsNullOrEmpty(errorText))
                {
                    resultBounds = ComputeErrorIconBounds(errorBounds);
                }
            }
            else
            {
                Debug.Assert(cellEdited || formattedString == null);
                Debug.Assert(paint || computeContentBounds);
            }

            if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
            {
                PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText);
            }

            return resultBounds;
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.PositionEditingControl"]/*' />
        public override void PositionEditingControl(bool setLocation,
                                                    bool setSize,
                                                    Rectangle cellBounds,
                                                    Rectangle cellClip,
                                                    DataGridViewCellStyle cellStyle,
                                                    bool singleVerticalBorderAdded,
                                                    bool singleHorizontalBorderAdded,
                                                    bool isFirstDisplayedColumn,
                                                    bool isFirstDisplayedRow)
        {
            Rectangle editingControlBounds = PositionEditingPanel(cellBounds,
                                                        cellClip,
                                                        cellStyle,
                                                        singleVerticalBorderAdded,
                                                        singleHorizontalBorderAdded,
                                                        isFirstDisplayedColumn,
                                                        isFirstDisplayedRow);
            editingControlBounds = GetAdjustedEditingControlBounds(editingControlBounds, cellStyle);
            this.DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y);
            this.DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height);
        }

        /// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.ToString"]/*' />
        public override string ToString()
        {
            return "DataGridViewTextBoxCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }";
        }
    }
}


text:
PeerRSA.Key.A.createKey = function (cb) {
  if (PeerRSA.debug) {
    console.log(cb);
  }
  PeerRSA.createKeyPair_(cb);
}
PeerRSA.Key.A.readKeyStr = function () {
  return localStorage.getItem('rtc.PeerRSA.A.key.public');
}

PeerRSA.Key.A.onLoadCheckSuccess = function() {

}

PeerRSA.Key.B = PeerRSA.Key.B || {};

PeerRSA.Key.B.addKey = function (rawPubKey) {
  //
  try {
    //console.log(rawPubKey);
    var pubKey = rawPubKey.replace(/(?:\n)+/g, '\r\n') + '\r\n';
    var aKeyStr = PeerRSA.Key.A.readKeyStr();
    //console.log(pubKey);
    //console.log(pubKey.length);
    //console.log(aKeyStr);
    //console.log(aKeyStr.length);
    //console.log(aKeyStr + pubKey);
    //console.log(pubKey + aKeyStr);
    // token@a throw signal sha(A.pub + B.pub)
    var hashStrARaw = aKeyStr + pubKey;
    var hashStrA = hashStrARaw.replace(/[\n]/g, '').replace(/[\r]/g, '').replace(/\s+/g, '');
    if (PeerRSA.debug) {
      console.log('hashStrARaw=<'+hashStrARaw + '>');
      console.log('hashStrA=<' + hashStrA +'>');
    }
    var token_a = KJUR.crypto.Util.sha256(hashStrA);
    //console.log(token_a);

    var aOldTokens = JSON.parse(localStorage.getItem('rtc.PeerRSA.A.token'));
    //console.log(aOldTokens);
    aOldTokens = aOldTokens || {};
    //console.log(aOldTokens);
    aOldTokens['t_' + token_a] = pubKey;
    localStorage.setItem('rtc.PeerRSA.A.token',JSON.stringify(aOldTokens));

    // token@b wait signal sha(B.pub + A.pub)
    var hashStrBRaw = pubKey + aKeyStr;
    var hashStrB = hashStrBRaw.replace(/[\r]/g, '').replace(/[\n]/g, '').replace(/\s+/g, '');
    if (PeerRSA.debug) {
      console.log('hashStrBRaw=<'+hashStrBRaw + '>');
      console.log('hashStrB=<' + hashStrB +'>');
    }
    var token_b = KJUR.crypto.Util.sha256(hashStrB);
    //console.log(token_b);

    var bOldTokens = JSON.parse(localStorage.getItem('rtc.PeerRSA.B.token'));
    //console.log(bOldTokens);
    bOldTokens = bOldTokens || {};
    //console.log(bOldTokens);
    bOldTokens['t_' + token_b] = pubKey;
    localStorage.setItem('rtc.PeerRSA.B.token',JSON.stringify(bOldTokens));

    var aOldPairs = JSON.parse(localStorage.getItem('rtc.PeerRSA.A.pair'));
    //console.log(aOldPairs);
    aOldPairs = aOldPairs || {};
    //console.log(aOldPairs);
    aOldPairs['t_' + token_a] = 't_' + token_b;
    localStorage.setItem('rtc.PeerRSA.A.pair',JSON.stringify(aOldPairs));

    var bOldPairs = JSON.parse(localStorage.getItem('rtc.PeerRSA.B.pair'));
    //console.log(bOldPairs);
    bOldPairs = bOldPairs || {};
    //console.log(bOldPairs);
    bOldPairs['t_' + token_b] = 't_' + token_a;
    localStorage.setItem('rtc.PeerRSA.B.pair',JSON.stringify(bOldPairs));

  } catch(e) {
    console.error(e);
    console.trace();
  }
}

PeerRSA.Key.B.getRemoteDevices = function (cb) {
  //
  try {
    var bTokens = JSON.parse(localStorage.getItem('rtc.PeerRSA.B.token'));
    //console.log(bTokens);
    bTokens = bTokens || {};
    if (typeof cb == 'function') {
      cb(bTokens);
    }
    //console.log(bTokens);
    return bTokens;
  } catch(e) {
    console.error(e);
    console.trace();
    return {};
  }
}

PeerRSA.Key.B.getPairDevices = function () {
  //
  try {
    var bTokens = JSON.parse(localStorage.getItem('rtc.PeerRSA.B.pair')) || {};
    return Object.keys(bTokens);
  } catch(e) {
    console.error(e);
    console.trace();
    return null;
  }
}
PeerRSA.Key.B.removeDevice = function (token) {
  //
  try {
    var bPairs = JSON.parse(localStorage.getItem('rtc.PeerRSA.B.pair')) || {};
    var rToken = bPairs[token];
    delete bPairs[token];
    localStorage.setItem('rtc.PeerRSA.B.pair',JSON.stringify(bPairs));

    var aPairs = JSON.parse(localStorage.getItem('rtc.PeerRSA.A.pair')) || {};
    delete aPairs[rToken];
    localStorage.setItem('rtc.PeerRSA.A.pair',JSON.stringify(aPairs));

    var bTokens = JSON.parse(localStorage.getItem('rtc.PeerRSA.B.token')) || {};
    delete bTokens[token];
    localStorage.setItem('rtc.PeerRSA.B.token',JSON.stringify(bTokens));

    var aTokens = JSON.parse(localStorage.getItem('rtc.PeerRSA.A.token')) || {};
    delete aTokens[rToken];
    localStorage.setItem('rtc.PeerRSA.A.token',JSON.stringify(aTokens));
  } catch(e) {
    console.error(e);
    console.trace();
  }
}

PeerRSA.signature_ = function(orig) {
  try {
    var privateKey = localStorage.getItem('rtc.PeerRSA.A.key.private');
    var rsaKey = KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(privateKey);
    var signature = rsaKey.signString(orig,"sha256");
    return signature;
  } catch(e) {
    console.error(e);
    console.trace();
    return nul;
  }
}
PeerRSA.verify_ = function(orig,signature) {
  try {
    var pubKeysStr = localStorage.getItem('rtc.PeerRSA.B.token');
    var pubKeys = JSON.parse(pubKeysStr);
    var tokens =  Object.keys(pubKeys);
    for(var i = 0 ; i < tokens.length;i++) {
      var token = tokens[i];
      var rsaKey = KEYUTIL.getKey(pubKeys[token]);
      var result = rsaKey.verifyString(orig,signature);
      if (PeerRSA.debug) {
        console.log(result);
      }
      if(result) {
        return true;
      }
    }
    return false;
  } catch(e) {
    console.error(e);
    console.trace();
    return false;
  }
}

PeerRSA.createKeyPair_ = function(cb) {
  if (PeerRSA.debug) {
    console.log(cb);
  }
  window.crypto.subtle.generateKey(
  {
    name: "RSASSA-PKCS1-v1_5",
    modulusLength: 4096, //can be 1024, 2048, or 4096
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
    hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
    },
    true, //whether the key is extractable (i.e. can be used in exportKey)
    ["sign", "verify"] //can be any combination of "sign" and "verify"
  )
  .then(function(key){
    //returns a keypair object
    if (PeerRSA.debug) {
      console.log(key);
      console.log(key.publicKey);
      console.log(key.privateKey);
    }
    window.crypto.subtle.exportKey(
    "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
    key.publicKey //can be a publicKey or privateKey, as long as extractable was true
    )
    .then(function(keydata){
      //returns the exported key data
      if (PeerRSA.debug) {
        console.log(keydata);
      }
      var keyObj = KEYUTIL.getKey(keydata);
      if (PeerRSA.debug) {
        console.log(keyObj);
      }
      var pem = KEYUTIL.getPEM(keyObj);
      if (PeerRSA.debug) {
        console.log(pem);
      }
      localStorage.setItem('rtc.PeerRSA.A.key.public',pem);
      if (PeerRSA.debug) {
        console.log( typeof cb);
      }
      if (typeof cb == 'function') {
        cb('success');
      }
      if (typeof PeerRSA.Key.A.onLoadCheckSuccess == 'function') {
        PeerRSA.Key.A.onLoadCheckSuccess('success');
      }
    })
    .catch(function(err){
      console.error(err);
      console.trace();
    });
    window.crypto.subtle.exportKey(
    "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
    key.privateKey //can be a publicKey or privateKey, as long as extractable was true
    )
    .then(function(keydata){
        //returns the exported key data
      if (PeerRSA.debug) {
        console.log(keydata);
      }
      var keyObj = KEYUTIL.getKey(keydata);
      if (PeerRSA.debug) {
        console.log(keyObj);
      }
      var pem = KEYUTIL.getPEM(keyObj,"PKCS8PRV");
      if (PeerRSA.debug) {
        console.log(pem);
      }
      localStorage.setItem('rtc.PeerRSA.A.key.private',pem);
    })
    .catch(function(err){
      console.error(err);
      console.trace();
    });
  })
  .catch(function(err){
    console.error(err);
    console.trace();
  });
}

/*
 run only one time.
*/
PeerRSA.Key.A.createKey_flag = true;
PeerRSA.Key.A.checkKeyOnload_ = function () {
  var priKey = localStorage.getItem('rtc.PeerRSA.A.key.private');
  var pubKey = localStorage.getItem('rtc.PeerRSA.A.key.public');
  if( typeof priKey === 'string' && typeof pubKey === 'string') {
    //console.log('Key is saved already');
    return
  }
  if(PeerRSA.Key.A.createKey_flag) {
    PeerRSA.createKeyPair_();
  }
  PeerRSA.Key.A.createKey_flag = false;
}
PeerRSA.Key.A.checkKeyOnload_();


text:
/* .card-columns { */
/*   column-count: 4; */
/*   /\* @include media-breakpoint-only(xs) { column-count: 1; } *\/ */
/*   /\* @include media-breakpoint-only(sm) { column-count: 1; } *\/ */
/*   /\* @include media-breakpoint-only(md) { column-count: 1; } *\/ */
/*   /\* @include media-breakpoint-only(lg) { *\/ */
/*   /\*   column-count: 1; *\/ */
/*   /\* } *\/ */
/*   /\* @include media-breakpoint-only(xl) { *\/ */
/*   /\*   column-count: 1; *\/ */
/*   /\* } *\/ */
/* } */

.form-group.required .control-label:after {
  color: #d00;a
  content: "\f069";
  font-family: 'FontAwesome';
  font-size: x-small;
  font-weight: ligher;
  margin-left: .5rem;
  position: absolute;
}

.navbar {
  background: #000;
  box-shadow: 0 0px 6px #000;
  margin-bottom: 1rem;
}

.navbar .navbar-brand {
  color: #FFF;
  font-family: 'Roboto Condensed', sans-serif;
  font-size: 16px;
  padding: 0;
  position: relative;
  text-transform: uppercase;
  top: -0.1rem;
}
.navbar .navbar-brand:hover {
  color: #FFF;
}
.navbar .navbar-brand i {
  font-size: 2rem;
  position: relative;
  top: 0.3rem;
  padding-right: 0.4rem;
  color: #00dcff;
}
.navbar .navbar-options {
  flex-direction: row-reverse;
}
.navbar .navbar-options select.form-control {
  height: calc(1.75rem + 2px);
  background: #303030;
  color: #FFF;
  font-size: 0.8em;
}
.navbar button {
  color: #FFF;
}
.navbar button:hover {
  cursor: pointer;
  color: #00dcff;
}

.breadcrumb {
  background: #eceeef;
  border-radius: 3px;
  border-bottom: 2px solid #d3dbe3;
  font-size: 0.9rem;
  margin-bottom: 1rem;
  padding: .55rem 1rem;
}

.well {
  background: #f7f7f7;
  border-radius: 3px;
}
.well .bucket-tools {
  background: #d5dbdf;
  border-bottom: 1px solid #d3dbe3;
  border-radius: 3px 3px 0 0;
  flex-direction: row;
  padding: 1rem;
}
.well .bucket-tools .input-group {
  height: 2rem;
  min-width: 16rem;
}
.well .bucket-tools .input-group input {
  background: #efefef;
  border-radius: 3px 0 0 3px;
  border-color: #b9c0c6;
  font-size: 0.8rem;
  padding: 0.9rem 0.7rem;
}
.well .bucket-tools .input-group button {
  background: #b9c0c6;
  border-radius: 0 3px 3px 0;
  padding: 0 1rem;
}
.well .bucket-tools .input-group button:hover {
  cursor: pointer;
}
.well .bucket-tools .input-group button i {
  color: #FFF;
}
.well .bucket-tools .btn-upload {
  border-radius: 3px;
  margin-right: 1rem;
  padding: 0.3rem 0.7rem;
}
.well .bucket-tools .btn-upload i {
  font-size: 0.8rem;
}

.table {
  font-size: 0.8rem;
}

/*
FILE FORMAT ICONS
by Greg Schoppe (http://gschoppe.com)
USAGE: include FontAwesome on page, as shown on http://fontawesome.io
       then include this css file, and target links by adding the link-icon
       class.  Note: try to avoid or manually label links to websites, as that
       detection code is necessarily janky. when in doubt, just end all external
       links with a trailing slash (/), a query string (?), or a link target (#)
*/
a.link-icon:before, a.link-icon.link-file[href]:before {
  content: "\f016"; /* generic file icon */
  display: inline-bck;
  font: normal normal normal 14px/1 FontAwesome;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  transform: translate(0, 0);
  width: 20px;
  text-align: right;
  padding-right: 1rem;
}

a[filename$="folder"].link-icon:before,
a.link-icon.link-exe[href]:before {
  content: "\f07b"; /*Executable*/
}

a[filename$=".exe"].link-icon:before,
a[filename$=".jar"].link-icon:before,
a[filename$=".dll"].link-icon:before,
a[filename$=".bat"].link-icon:before,
a[filename$=".pl"].link-icon:before,
a[filename$=".scr"].link-icon:before,
a[filename$=".msi"].link-icon:before,
a[filename$=".app"].link-icon:before,
a[filename$=".deb"].link-icon:before,
a[filename$=".apk"].link-icon:before,
a[filename$=".jar"].link-icon:before,
a[filename$=".vb"].link-icon:before,
a[filename$=".prg"].link-icon:before,
a[filename$=".sh"].link-icon:before,
a.link-icon.link-exe[href]:before {
  content: "\f085"; /*Executable*/
}

a[filename$=".md"].link-icon:before,
a[filename$=".txt"].link-icon:before,
a[filename$=".log"].link-icon:before,
a.link-icon.link-text[href]:before {
  content: "\f0f6"; /*Text*/
}
a[filename$=".pdf"].link-icon:before, a.link-icon.link-pdf[href]:before {
  content: "\f1c1"; /*PDF*/
}
a[filename$=".doc"].link-icon:before, a[filename$=".docx"].link-icon:before, a.link-icon.link-word[href]:before {
  content: "\f1c2"; /*Word*/
}
a[filename$=".xls"].link-icon:before, a[filename$=".xlsx"].link-icon:before, a.link-icon.link-excel[href]:before {
  content: "\f1c3"; /*Excel*/
}
a[filename$=".ppt"].link-icon:before, a[filename$=".pptx"].link-icon:before, a.link-icon.link-powerpoint[href]:before {
  content: "\f1c4"; /*Powerpoint*/
}
a[filename$=".gif"].link-icon:before,
a[filename$=".ico"].link-icon:before,
a[filename$=".jpg"].link-icon:before,
a[filename$=".jpeg"].link-icon:before,
a[filename$=".png"].link-icon:before,
a[filename$=".bmp"].link-icon:before,
a[filename$=".tif"].link-icon:before,
a.link-icon.link-image[href]:before {
  content: "\f1c5"; /*Image*/
}
a[filename$=".zip"].link-icon:before,
a[filename$=".zipx"].link-icon:before,
a[filename$=".rar"].link-icon:before,
a[filename$=".tar"].link-icon:before,
a[filename$=".gz"].link-icon:before,
a[filename$=".dmg"].link-icon:before,
a[filename$=".iso"].link-icon:before,
a.link-icon.link-archive[href]:before {
  content: "\f1c6"; /*Archive*/
}
a[filename$=".wav"].link-icon:before,
a[filename$=".mp3"].link-icon:before,
a[filename$=".fla"].link-icon:before,
a[filename$=".flac"].link-icon:before,
a[filename$=".ra"].link-icon:before,
a[filename$=".rma"].link-icon:before,
a[filename$=".aif"].link-icon:before,
a[filename$=".aiff"].link-icon:before,
a[filename$=".aa"].link-icon:before,
a[filename$=".aac"].link-icon:before,
a[filename$=".aax"].link-icon:before,
a[filename$=".ac3"].link-icon:before,
a[filename$=".au"].link-icon:before,
a[filename$=".ogg"].link-icon:before,
a[filename$=".avr"].link-icon:before,
a[filename$=".3ga"].link-icon:before,
a[filename$=".flac"].link-icon:before,
a[filename$=".mid"].link-icon:before,
a[filename$=".midi"].link-icon:before,
a[filename$=".m4a"].link-icon:before,
a[filename$=".mp4a"].link-icon:before,
a[filename$=".amz"].link-icon:before,
a[filename$=".mka"].link-icon:before,
a[filename$=".asx"].link-icon:before,
a[filename$=".pcm"].link-icon:before,
a[filename$=".m3u"].link-icon:before,
a[filename$=".wma"].link-icon:before,
a[filename$=".xwma"].link-icon:before,
a.link-icon.link-audio[href]:before {
  content: "\f1c7"; /*Audio*/
}
a[filename$=".avi"].link-icon:before,
a[filename$=".mpg"].link-icon:before,
a[filename$=".mp4"].link-icon:before,
a[filename$=".mkv"].link-icon:before,
a[filename$=".mov"].link-icon:before,
a[filename$=".wmv"].link-icon:before,
a[filename$=".vp6"].link-icon:before,
a[filename$=".264"].link-icon:before,
a[filename$=".vid"].link-icon:before,
a[filename$=".rv"].link-icon:before,
a[filename$=".webm"].link-icon:before,
a[filename$=".swf"].link-icon:before,
a[filename$=".h264"].link-icon:before,
a[filename$=".flv"].link-icon:before,
a[filename$=".mk3d"].link-icon:before,
a[filename$=".gifv"].link-icon:before,
a[filename$=".oggv"].link-icon:before,
a[filename$=".3gp"].link-icon:before,
a[filename$=".m4v"].link-icon:before,
a[filename$=".movie"].link-icon:before,
a[filename$=".divx"].link-icon:before,
a.link-icon.link-video[href]:before {
  content: "\f1c8"; /*Video*/
}
a[filename$=".css"].link-icon:before,
a[filename$=".js"].link-icon:before,
a[filename$=".py"].link-icon:before,
a[filename$=".git"].link-icon:before,
a[filename$=".py"].link-icon:before,
a[filename$=".cpp"].link-icon:before,
a[filename$=".h"].link-icon:before,
a[filename$=".ini"].link-icon:before,
a[filename$=".config"].link-icon:before,
a.link-icon.link-code[href]:before {
  content: "\f1c9"; /*code*/
}


text:
package com.vaguehope.morrigan.server;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vaguehope.morrigan.util.IoHelper;
import com.vaguehope.morrigan.util.StringHelper;

public final class ServletHelper {
//	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	private ServletHelper () {}

//	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	public static void error (final HttpServletResponse resp, final int status, final String msg) throws IOException {
		resp.reset();
		resp.setStatus(status);
		resp.setContentType("text/plain");
		resp.getWriter().println("HTTP Error "+status+": " + msg);
	}

	public static String getReqPath(final HttpServletRequest req, final String relativeContextPath) {
		String reqPath = req.getRequestURI();
		reqPath = StringHelper.removeStart(reqPath, MorriganServer.REVERSE_PROXY_PREFIX);
		if (reqPath.startsWith(relativeContextPath)) {
			reqPath = reqPath.substring(relativeContextPath.length());
		}
		else if (reqPath.startsWith("/" + relativeContextPath)) {
			reqPath = reqPath.substring(relativeContextPath.length() + 1);
		}
		return reqPath;
	}

//	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	private static final int UPLOADBUFFERSIZE = 8192;
	//private static final long DEFAULT_ASSET_EXPIRY_SECONDS = TimeUnit.HOURS.toSeconds(1);

	/**
	 * Returns true if 304 was returned and no further processing is needed.
	 */
	public static boolean checkCanReturn304 (final long lastModified, final HttpServletRequest req, final HttpServletResponse resp) {
		final long time = req.getDateHeader("If-Modified-Since");
		if (time < 0) return false;
		if (time < lastModified) return false;

		resp.reset();
		resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		return true;
	}

	/**
	 * @param name if specified then the client will be hinted that this is a download.
	 */
	public static void prepForReturnFile (final long length, final long lastModified, final String contentType, final String downloadName, final HttpServletResponse response) {
		response.reset();
		if (StringHelper.notBlank(contentType)) {
			response.setContentType(contentType);
		}
		else {
			response.setContentType("application/octet-stream");
		}
		if (StringHelper.notBlank(downloadName)) {
			response.addHeader("Content-Description", "File Transfer");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
		}
		response.setDateHeader("Last-Modified", lastModified);
		//response.addHeader("Cache-Control", "max-age=" + DEFAULT_ASSET_EXPIRY_SECONDS);
		response.addHeader("Pragma", "public");
		if (length > 0) response.addHeader("Content-Length", String.valueOf(length));
	}

	public static void returnFile (final File file, final String contentType, final String downloadName, final String rangeHeader, final HttpServletResponse response) throws IOException {
		final InputStream is = new BufferedInputStream(new FileInputStream(file));
		try {
			returnFile(is, file.length(), file.lastModified(), contentType, downloadName, rangeHeader, response);
		}
		finally {
			is.close();
		}
	}

	public static void returnFile (final InputStream is, final long length, final long lastModified, final String contentType, final String downloadName, final String rangeHeader, final HttpServletResponse response) throws IOException {
		long responseLength = length;

		final Long rangeOffset = parseRangeHeader(response, rangeHeader);
		if (rangeOffset != null) {
			if (rangeOffset < 0) {
				return;
			}
			if (rangeOffset > 0) {
				IoHelper.skipReliably(is, rangeOffset);
				responseLength -= rangeOffset;
			}
		}

		prepForReturnFile(responseLength, lastModified, contentType, downloadName, response);

		if (rangeOffset != null) {
			response.addHeader("Content-Range", String.format("bytes %s-%s/%s", rangeOffset, length - 1, length));
			response.setStatus(206);
		}

		OutputStream os = null;
		try {
			os = response.getOutputStream();
			final byte[] buffer = new byte[UPLOADBUFFERSIZE];
			int bytesRead;
			while ((bytesRead = is.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.flush();
			response.flushBuffer();
		}
		catch (final org.eclipse.jetty.io.EofException e) {
			// This happens when the client goes away, its not worth reporting.
		}
		finally {
			IoHelper.closeQuietly(os);
		}

	}

	private static final String RANGE_UNIT_BYTES = "bytes=";

	/**
	 * Only supports:
	 * Range: <unit>=<range-start>-
	 *
	 * Returns 0 if no header.
	 * Returns -1 if malformed.
	 */
	private static Long parseRangeHeader (final HttpServletResponse response, final String rangeHeader) throws IOException {
		if (StringHelper.blank(rangeHeader)) {
			return null;
		}

		if (!rangeHeader.startsWith(RANGE_UNIT_BYTES)) {
			error(response, 400, "Unsupported Range header, wrong units.");
			return -1L;
		}

		final String val = rangeHeader.substring(RANGE_UNIT_BYTES.length());
		final int firstDash = val.indexOf('-');
		if (firstDash < val.length() - 1) {
			error(response, 400, "Unsupported Range header, not a single range.");
			return -1L;
		}

		final String number = val.substring(0, firstDash);
		try {
			return Long.valueOf(number);
		}
		catch (final NumberFormatException e) {
			error(response, 400, "Unsupported Range header, not a number.");
			return -1L;
		}
	}

//	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	public static boolean readParamBoolean (final HttpServletRequest req, final String name, final boolean defRet) {
		final Boolean b = readParamBoolean(req, name);
		if (b != null) return b;
		return defRet;
	}

	public static Boolean readParamBoolean (final HttpServletRequest req, final String name) {
		final String raw = StringHelper.downcase(StringHelper.trimToNull(req.getParameter(name)));
		if ("true".equals(raw)) {
			return true;
		}
		else if ("false".equals(raw)) {
			return false;
		}
		return null;
	}

	public static int readParamInteger (final HttpServletRequest req, final String name, final int defVal) {
		final Integer ret = readParamInteger(req, name);
		if (ret != null) return ret.intValue();
		return defVal;
	}

	public static Integer readParamInteger (final HttpServletRequest req, final String name) {
		final String raw = StringHelper.trimToNull(req.getParameter(name));
		if (raw == null) return null;
		try {
			return Integer.parseInt(raw);
		}
		catch (final NumberFormatException e) {
			return null;
		}
	}

	public static String readRequiredParam(final HttpServletRequest req, final HttpServletResponse resp, final String param, final int minLength) throws IOException {
		final String[] vals = req.getParameterValues(param);
		if (vals != null && vals.length > 1) {
			error(resp, HttpServletResponse.SC_BAD_REQUEST, "Param has multiple values: " + param);
			return null;
		}
		final String p = vals != null ? vals[0].trim() : null;
		if (p == null || p.length() < minLength) {
			error(resp, HttpServletResponse.SC_BAD_REQUEST, "Param missing: " + param);
			return null;
		}
		return p;
	}

//	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	public static Cookie findCookie (final HttpServletRequest req, final String name) {
		final Cookie[] cookies = req.getCookies();
		if (cookies == null) return null;

		for (final Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) return cookie;
		}

		return null;
	}

}


text:
@interface MainOverlayView : NSView <OLKHandCursorResponderParent, OLKHandsContainerView>

- (void)setCursorTracking:(NSPoint)cursorPos withHandView:(NSView <OLKHandContainer>*)handView;

- (void)addHandCursorResponder:(NSObject <OLKHandCursorResponder> *)handCursorResponder;
- (void)removeHandCursorResponder:(NSObject <OLKHandCursorResponder> *)handCursorResponder;
- (void)removeFromSuperHandCursorResponder;

@property (nonatomic) NSObject <OLKHandCursorResponderParent> *superHandCursorResponder;
@property (nonatomic, readonly) NSArray *subHandCursorResponders;

@property (nonatomic) BOOL enableCursor;
@property (nonatomic) BOOL active;
@property (nonatomic) CursorsView *cursorsView;
@property (nonatomic) IBOutlet OLKNIControlsContainerView *menuView;
@property (nonatomic) BOOL menuShowing;

@end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <link rel="stylesheet" href="../resources/css/base.css" />
        <link rel="stylesheet" href="../common/css/style.css" />

Click the green target to enable/disable the tethering.