text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.profiler.memory;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.events.Location.LineAndColumn;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleFunction;
import com.google.devtools.build.lib.profiler.memory.AllocationTracker.RuleBytes;
import com.google.devtools.build.lib.syntax.BaseFunction;
import com.google.devtools.build.lib.syntax.Callstack;
import com.google.devtools.build.lib.syntax.Expression;
import com.google.devtools.build.lib.syntax.ParserInput;
import com.google.devtools.build.lib.syntax.SyntaxError;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.perftools.profiles.ProfileProto.Function;
import com.google.perftools.profiles.ProfileProto.Profile;
import com.google.perftools.profiles.ProfileProto.Sample;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link AllocationTracker}. */
@RunWith(JUnit4.class)
public class AllocationTrackerTest {

  private AllocationTracker allocationTracker;

  // makeExpr returns an expression located at the specified file and line.
  private static Expression makeExpr(String file, int line) throws SyntaxError {
    ParserInput input =
        ParserInput.create(
            new String(new char[line - 1]).replace('\u0000', '\n') + "None",
            PathFragment.create(file));
    return Expression.parse(input);
  }

  static class TestFunction extends BaseFunction {
    TestFunction(String file, String name, int line) {
      super(name);
      this.location = location(file, line);
    }
  }

  static class TestRuleFunction extends TestFunction implements RuleFunction {

    private final RuleClass ruleClass;

    TestRuleFunction(String file, String name, int line) {
      super(file, name, line);
      this.ruleClass = mock(RuleClass.class);
      when(ruleClass.getName()).thenReturn(name);
      when(ruleClass.getKey()).thenReturn(name);
    }

    @Override
    public RuleClass getRuleClass() {
      return ruleClass;
    }
  }

  @Before
  public void setup() {
    Callstack.setEnabled(true);
    CurrentRuleTracker.setEnabled(true);
    allocationTracker = new AllocationTracker(1, 0);
  }

  @After
  public void tearDown() {
    Callstack.resetStateForTest();
    CurrentRuleTracker.setEnabled(false);
  }

  @Test
  public void testSimpleMemoryProfile() throws Exception {
    Object allocation = new Object();
    Callstack.push(new TestFunction("fileA", "fn", 120));
    Callstack.push(makeExpr("fileA", 10));
    allocationTracker.sampleAllocation(1, "", allocation, 12);
    Callstack.pop();
    Callstack.pop();

    Map<String, RuleBytes> rules = new HashMap<>();
    Map<String, RuleBytes> aspects = new HashMap<>();
    allocationTracker.getRuleMemoryConsumption(rules, aspects);
    assertThat(rules).isEmpty();
    assertThat(aspects).isEmpty();

    Profile profile = allocationTracker.buildMemoryProfile();
    assertThat(profile.getSampleList()).hasSize(1);
    assertThat(sampleToCallstack(profile, profile.getSample(0))).containsExactly("fileA:fn:10");
  }

  @Test
  public void testLongerCallstack() throws Exception {
    Object allocation = new Object();
    Callstack.push(new TestFunction("fileB", "fnB", 120));
    Callstack.push(makeExpr("fileB", 10));
    Callstack.push(makeExpr("fileB", 12));
    Callstack.push(makeExpr("fileB", 14));
    Callstack.push(makeExpr("fileB", 18));
    Callstack.push(new TestFunction("fileA", "fnA", 120));
    Callstack.push(makeExpr("fileA", 10));
    allocationTracker.sampleAllocation(1, "", allocation, 12);
    for (int i = 0; i < 7; ++i) {
      Callstack.pop();
    }

    Profile profile = allocationTracker.buildMemoryProfile();
    assertThat(profile.getSampleList()).hasSize(1);
    assertThat(sampleToCallstack(profile, profile.getSample(0)))
        .containsExactly("fileB:fnB:18", "fileA:fnA:10");
  }

  @Test
  public void testConfiguredTargetsMemoryAllocation() throws Exception {
    RuleClass ruleClass = mock(RuleClass.class);
    when(ruleClass.getName()).thenReturn("rule");
    when(ruleClass.getKey()).thenReturn("rule");
    CurrentRuleTracker.beginConfiguredTarget(ruleClass);
    Object ruleAllocation0 = new Object();
    Object ruleAllocation1 = new Object();
    allocationTracker.sampleAllocation(1, "", ruleAllocation0, 10);
    allocationTracker.sampleAllocation(1, "", ruleAllocation1, 20);
    CurrentRuleTracker.endConfiguredTarget();

    CurrentRuleTracker.beginConfiguredAspect(() -> "aspect");
    Object aspectAllocation = new Object();
    allocationTracker.sampleAllocation(1, "", aspectAllocation, 12);
    CurrentRuleTracker.endConfiguredAspect();

    Map<String, RuleBytes> rules = new HashMap<>();
    Map<String, RuleBytes> aspects = new HashMap<>();
    allocationTracker.getRuleMemoryConsumption(rules, aspects);
    assertThat(rules).containsExactly("rule", new RuleBytes("rule").addBytes(30L));
    assertThat(aspects).containsExactly("aspect", new RuleBytes("aspect").addBytes(12L));

    Profile profile = allocationTracker.buildMemoryProfile();
    assertThat(profile.getSampleList()).isEmpty(); // No callstacks
  }

  @Test
  public void testLoadingPhaseRuleAllocations() throws Exception {
    Object allocation = new Object();
    Callstack.push(new TestFunction("fileB", "fnB", 120));
    Callstack.push(makeExpr("fileB", 18));
    Callstack.push(new TestFunction("fileA", "fnA", 120));
    Callstack.push(makeExpr("fileA", 10));
    Callstack.push(new TestRuleFunction("<native>", "proto_library", -1));
    allocationTracker.sampleAllocation(1, "", allocation, 128);
    for (int i = 0; i < 5; ++i) {
      Callstack.pop();
    }

    Map<String, RuleBytes> rules = new HashMap<>();
    Map<String, RuleBytes> aspects = new HashMap<>();
    allocationTracker.getRuleMemoryConsumption(rules, aspects);
    assertThat(rules)
        .containsExactly("proto_library", new RuleBytes("proto_library").addBytes(128L));
  }

  /** Formats a callstack as (file):(method name):(line) */
  private List<String> sampleToCallstack(Profile profile, Sample sample) {
    List<String> result = new ArrayList<>();
    for (long locationId : sample.getLocationIdList()) {
      com.google.perftools.profiles.ProfileProto.Location location =
          profile.getLocation((int) locationId - 1);
      assertThat(location.getLineList()).hasSize(1);
      long functionId = location.getLine(0).getFunctionId();
      long line = location.getLine(0).getLine();
      Function function = profile.getFunction((int) functionId - 1);
      long fileId = function.getFilename();
      long methodId = function.getName();
      String file = profile.getStringTable((int) fileId);
      String method = profile.getStringTable((int) methodId);
      result.add(String.format("%s:%s:%d", file, method, line));
    }
    return result;
  }

  private static Location location(String path, int line) {
    return Location.fromPathAndStartColumn(
        PathFragment.create(path), 0, 0, new LineAndColumn(line, 0));
  }
}


text:
def main(request, response):
    type = request.GET.first(b"type", None)

    content = b"// nothing to see here"
    content += b"\n"
    content += b"this.postMessage('hi')"

    response.add_required_headers = False
    response.writer.write_status(200)
    response.writer.write_header(b"x-content-type-options", b"nosniff")
    response.writer.write_header(b"content-length", len(content))
    if(type != None):
        response.writer.write_header(b"content-type", type)
    response.writer.end_headers()

    response.writer.write(content)

redpajama_set_name: RedPajamaGithub


text:
"""Tests for the DeclareLaunchArgument action class."""

from launch import LaunchContext
from launch.actions import DeclareLaunchArgument

import pytest

def test_declare_launch_argument_constructors():
    """Test the constructors for DeclareLaunchArgument class."""
    DeclareLaunchArgument('name')
    DeclareLaunchArgument('name', default_value='default value')
    DeclareLaunchArgument('name', default_value='default value', description='description')
    DeclareLaunchArgument('name', default_value='val1', description='description',
                          choices=['val1', 'val2'])

def test_declare_launch_argument_methods():
    """Test the methods of the DeclareLaunchArgument class."""
    dla1 = DeclareLaunchArgument('name', default_value='default value', description='description')
    assert dla1.name == 'name'
    assert isinstance(dla1.default_value, list)
    assert dla1.description == 'description'
    assert dla1.choices is None
    assert 'DeclareLaunchArgument' in dla1.describe()
    assert isinstance(dla1.describe_sub_entities(), list)
    assert isinstance(dla1.describe_conditional_sub_entities(), list)

    dla2 = DeclareLaunchArgument('name')
    assert dla2.default_value is None
    assert dla2.choices is None
    assert dla2.description, 'description does not have a non-empty default value'

    dla3 = DeclareLaunchArgument('name', description='description', choices=['var1', 'var2'])
    assert dla3.default_value is None
    assert dla3.choices == ['var1', 'var2']
    assert str(dla3.choices) in dla3.description

    with pytest.raises(RuntimeError) as excinfo:
        DeclareLaunchArgument('name', description='description', choices=['var1', 'var2'],
                              default_value='invalid')
    assert 'not in provided choices' in str(excinfo.value)

def test_declare_launch_argument_execute():
    """Test the execute (or visit) of the DeclareLaunchArgument class."""
    action1 = DeclareLaunchArgument('name')
    lc1 = LaunchContext()
    with pytest.raises(RuntimeError) as excinfo:
        action1.visit(lc1)
    assert 'Required launch argument' in str(excinfo.value)

    lc1.launch_configurations['name'] = 'value'
    assert action1.visit(lc1) is None

    action2 = DeclareLaunchArgument('name', default_value='value')
    lc2 = LaunchContext()
    assert action2.visit(lc2) is None
    assert lc1.launch_configurations['name'] == 'value'

    action3 = DeclareLaunchArgument('name', default_value='var1', choices=['var1', 'var2'])
    lc3 = LaunchContext()
    assert action3.visit(lc3) is None
    lc3.launch_configurations['name'] = 'invalid_value'
    with pytest.raises(RuntimeError) as excinfo:
        action3.visit(lc3)
        assert 'Valid options are: [var1, var2]' in str(excinfo.value)
    lc3.launch_configurations['name'] = 'var1'
    assert action3.visit(lc3) is None
    lc3.launch_configurations['name'] = 'var2'
    assert action3.visit(lc3) is None


text:
////////////
// depends on:
//  version.js
//  class.js

(function () {
    'use strict';

    alphabot.Engine = alphabot.Engine || {};

    if (alphabot.Engine.Person) {
        if (console !== undefined && console.log !== undefined) {
            console.log('alphabot.Engine.Person is already defined.');
        }

        return;
    }

    alphabot.Engine.Person = Class.extend({
        init: function (option) {
            this.name = option.name;
            this.faceSet = option.faceSet;

            // The faces looks like:
            // [{x: 0, y: 0}, {x: 30, y: 0}]
            // faceset is actually a sprite image. faces inicates the position of each face on the sprite.
            this.faces = option.faces;

            if (option.faceIndex !== undefined) {
                this.currentFaceIndex = option.faceIndex;
            }
            else {
                this.currentFaceIndex = 0;
            }
        },

        setCurrentFace: function (faceIndex) {
            var self = this;
            self.currentFaceIndex = faceIndex;
        },

        getCurrentFace: function () {
            var self = this;
            var currentFace = self.faces[self.currentFaceIndex];

            return currentFace;
        },

        getFace: function (faceIndex) {
            var self = this;
            var f = self.faces[faceIndex];

            return f;
        },

        getName: function () {
            var self = this;

            return self.name;
        },

        getFaceSet: function () {
            var self = this;

            return self.faceSet;
        },

        getFaces: function () {
            var self = this;

            return self.faces;
        }
    });
})();


text:
package org.apache.hadoop.hdfs.server.datanode;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.hdfs.*;
import org.apache.hadoop.hdfs.server.namenode.*;
import org.apache.hadoop.hdfs.server.datanode.*;
import org.apache.hadoop.hdfs.server.common.*;
import org.apache.hadoop.hdfs.protocol.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.*;
import org.apache.hadoop.http.HtmlQuoting;
import java.text.DateFormat;

public final class browseBlock_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  static JspHelper jspHelper = new JspHelper();

  public void generateFileDetails(JspWriter out, HttpServletRequest req,
                                  Configuration conf
                                 ) throws IOException, InterruptedException {

    int chunkSizeToView = 0;
    long startOffset = 0;
    int datanodePort;

    String blockIdStr = null;
    long currBlockId = 0;
    blockIdStr = req.getParameter("blockId");
    if (blockIdStr == null) {
      out.print("Invalid input (blockId absent)");
      return;
    }
    currBlockId = Long.parseLong(blockIdStr);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
      out.print("Invalid input (datanodePort absent)");
      return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);

    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
      namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);

    String chunkSizeToViewStr = req.getParameter("chunkSizeToView");
    if (chunkSizeToViewStr != null &&
        Integer.parseInt(chunkSizeToViewStr) > 0) {
     chunkSizeToView = Integer.parseInt(chunkSizeToViewStr);
    } else {
     chunkSizeToView = JspHelper.getDefaultChunkSize(conf);
    }

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0)
      startOffset = 0;
    else startOffset = Long.parseLong(startOffsetStr);

    String filename = HtmlQuoting.unquoteHtmlChars(req.getParameter("filename"));
    if (filename == null || filename.length() == 0) {
      out.print("Invalid input");
      return;
    }

    String blockSizeStr = req.getParameter("blockSize");
    long blockSize = 0;
    if (blockSizeStr == null || blockSizeStr.length() == 0) {
      out.print("Invalid input");
      return;
    }
    blockSize = Long.parseLong(blockSizeStr);

    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    DFSClient dfs = JspHelper.getDFSClient(ugi, jspHelper.nameNodeAddr, conf);
    List<LocatedBlock> blocks =
      dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks();
    //Add the various links for looking at the file contents
    //URL for downloading the full file
    String downloadUrl = "http://" + req.getServerName() + ":" +
                         + req.getServerPort() + "/streamFile"
                         + URLEncoder.encode(filename, "UTF-8")
                         + "?" + JspHelper.DELEGATION_PARAMETER_NAME
                         + "=" + tokenString;
    out.print("");
    out.print("Download this file
");

    DatanodeInfo chosenNode;
    //URL for TAIL
    LocatedBlock lastBlk = blocks.get(blocks.size() - 1);
    long blockId = lastBlk.getBlock().getBlockId();
    try {
      chosenNode = jspHelper.bestNode(lastBlk);
    } catch (IOException e) {
      out.print(e.toString());
      dfs.close();
      return;
    }
    String fqdn =
           InetAddress.getByName(chosenNode.getHost()).getCanonicalHostName();
    String tailUrl = "http://" + fqdn + ":" +
                     chosenNode.getInfoPort() +
                 "/tail.jsp?filename=" + URLEncoder.encode(filename, "UTF-8") +
                 "&namenodeInfoPort=" + namenodeInfoPort +
                 "&chunkSizeToView=" + chunkSizeToView +
                 "&referrer=" +
          URLEncoder.encode(req.getRequestURL() + "?" + req.getQueryString(),
                            "UTF-8") +
                 JspHelper.getDelegationTokenUrlParam(tokenString);
    out.print("Tail this file
");

    out.print("<form action=\"/browseBlock.jsp\" method=GET>");
    out.print("Chunk size to view (in bytes, up to file's DFS block size): ");
    out.print("<input type=\"hidden\" name=\"blockId\" value=\"" + currBlockId +
              "\">");
    out.print("<input type=\"hidden\" name=\"blockSize\" value=\"" +
              blockSize + "\">");
    out.print("<input type=\"hidden\" name=\"startOffset\" value=\"" +
              startOffset + "\">");
    out.print("<input type=\"hidden\" name=\"filename\" value=\"" + filename +
              "\">");
    out.print("<input type=\"hidden\" name=\"datanodePort\" value=\"" +
              datanodePort+ "\">");
    out.print("<input type=\"hidden\" name=\"namenodeInfoPort\" value=\"" +
              namenodeInfoPort + "\">");
    out.print("<input type=\"text\" name=\"chunkSizeToView\" value=" +
              chunkSizeToView + " size=10 maxlength=10>");
    out.print("  <input type=\"submit\" name=\"submit\" value=\"Refresh\">");
    out.print("</form>");
    out.print("
");
    out.print("");
    out.print("Total number of blocks: "+blocks.size()+"
");
    //generate a table and dump the info
    out.println("\n
");
    for (LocatedBlock cur : blocks) {
      out.print("
");
      blockId = cur.getBlock().getBlockId();
      blockSize = cur.getBlock().getNumBytes();
      String blk = "blk_" + Long.toString(blockId);
      out.print(""+Long.toString(blockId)+":	");
      DatanodeInfo[] locs = cur.getLocations();
      for(int j=0; j<locs.length; j++) {
        String datanodeAddr = locs[j].getName();
        datanodePort = Integer.parseInt(datanodeAddr.substring(
                                        datanodeAddr.indexOf(':') + 1,
                                    datanodeAddr.length()));
        fqdn = InetAddress.getByName(locs[j].getHost()).getCanonicalHostName();
        String blockUrl = "http://"+ fqdn + ":" +
                        locs[j].getInfoPort() +
                        "/browseBlock.jsp?blockId=" + Long.toString(blockId) +
                        "&blockSize=" + blockSize +
                        "&filename=" + URLEncoder.encode(filename, "UTF-8") +
                        "&datanodePort=" + datanodePort +
                        "&genstamp=" + cur.getBlock().getGenerationStamp() +
                        "&namenodeInfoPort=" + namenodeInfoPort +
                        "&chunkSizeToView=" + chunkSizeToView;
        out.print("&nbsp	"
          + "" + datanodeAddr + "	");
      }
      out.println("
");
    }
    out.println("
");
    out.print("
");
    String namenodeHost = jspHelper.nameNodeAddr.getHostName();
    out.print("
Go back to DFS home");
    dfs.close();
  }

  public void generateFileChunks(JspWriter out, HttpServletRequest req,
                                 Configuration conf
                                ) throws IOException, InterruptedException {
    long startOffset = 0;
    int datanodePort = 0;
    int chunkSizeToView = 0;

    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
      namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);

    String filename = HtmlQuoting.unquoteHtmlChars(req.getParameter("filename"));
    if (filename == null) {
      out.print("Invalid input (filename absent)");
      return;
    }

    String blockIdStr = null;
    long blockId = 0;
    blockIdStr = req.getParameter("blockId");
    if (blockIdStr == null) {
      out.print("Invalid input (blockId absent)");
      return;
    }
    blockId = Long.parseLong(blockIdStr);

    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    final DFSClient dfs = JspHelper.getDFSClient(ugi, jspHelper.nameNodeAddr,
                                                 conf);

    Token<BlockTokenIdentifier> accessToken = BlockTokenSecretManager.DUMMY_TOKEN;
    if (conf
        .getBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, false)) {
      List<LocatedBlock> blks = dfs.namenode.getBlockLocations(filename, 0,
          Long.MAX_VALUE).getLocatedBlocks();
      if (blks == null || blks.size() == 0) {
        out.print("Can't locate file blocks");
        dfs.close();
        return;
      }
      for (int i = 0; i < blks.size(); i++) {
        if (blks.get(i).getBlock().getBlockId() == blockId) {
          accessToken = blks.get(i).getBlockToken();
          break;
        }
      }
    }

    String blockGenStamp = null;
    long genStamp = 0;
    blockGenStamp = req.getParameter("genstamp");
    if (blockGenStamp == null) {
      out.print("Invalid input (genstamp absent)");
      return;
    }
    genStamp = Long.parseLong(blockGenStamp);

    String blockSizeStr;
    long blockSize = 0;
    blockSizeStr = req.getParameter("blockSize");
    if (blockSizeStr == null) {
      out.print("Invalid input (blockSize absent)");
      return;
    }
    blockSize = Long.parseLong(blockSizeStr);

    String chunkSizeToViewStr = req.getParameter("chunkSizeToView");
    if (chunkSizeToViewStr != null && Integer.parseInt(chunkSizeToViewStr) > 0)
      chunkSizeToView = Integer.parseInt(chunkSizeToViewStr);
    else chunkSizeToView = JspHelper.getDefaultChunkSize(conf);

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0)
      startOffset = 0;
    else startOffset = Long.parseLong(startOffsetStr);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
      out.print("Invalid input (datanodePort absent)");
      return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);
    out.print("
File: ");
    JspHelper.printPathWithLinks(HtmlQuoting.quoteHtmlChars(filename),
                                 out, namenodeInfoPort, tokenString);
    out.print("

");
    String parent = new File(filename).getParent();
    JspHelper.printGotoForm(out, namenodeInfoPort, tokenString,
                            HtmlQuoting.quoteHtmlChars(parent));
    out.print("
");
    out.print("Go back to dir listing
");
    out.print("Advanced view/download options
");
    out.print("
");

    //Determine the prev & next blocks
    long nextStartOffset = 0;
    long nextBlockSize = 0;
    String nextBlockIdStr = null;
    String nextGenStamp = null;
    String nextHost = req.getServerName();
    int nextPort = req.getServerPort();
    int nextDatanodePort = datanodePort;
    //determine data for the next link
    if (startOffset + chunkSizeToView >= blockSize) {
      //we have to go to the next block from this point onwards
      List<LocatedBlock> blocks =
        dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks();
      for (int i = 0; i < blocks.size(); i++) {
        if (blocks.get(i).getBlock().getBlockId() == blockId) {
          if (i != blocks.size() - 1) {
            LocatedBlock nextBlock = blocks.get(i+1);
            nextBlockIdStr = Long.toString(nextBlock.getBlock().getBlockId());
            nextGenStamp = Long.toString(nextBlock.getBlock().getGenerationStamp());
            nextStartOffset = 0;
            nextBlockSize = nextBlock.getBlock().getNumBytes();
            DatanodeInfo d = jspHelper.bestNode(nextBlock);
            String datanodeAddr = d.getName();
            nextDatanodePort = Integer.parseInt(
                                      datanodeAddr.substring(
                                           datanodeAddr.indexOf(':') + 1,
                                      datanodeAddr.length()));
            nextHost = InetAddress.getByName(d.getHost()).getCanonicalHostName();
            nextPort = d.getInfoPort();
          }
        }
      }
    }
    else {
      //we are in the same block
      nextBlockIdStr = blockIdStr;
      nextStartOffset = startOffset + chunkSizeToView;
      nextBlockSize = blockSize;
      nextGenStamp = blockGenStamp;
    }
    String nextUrl = null;
    if (nextBlockIdStr != null) {
      nextUrl = "http://" + nextHost + ":" +
                nextPort +
                "/browseBlock.jsp?blockId=" + nextBlockIdStr +
                "&blockSize=" + nextBlockSize + "&startOffset=" +
                nextStartOffset +
                "&genstamp=" + nextGenStamp +
                "&filename=" + URLEncoder.encode(filename, "UTF-8") +
                "&chunkSizeToView=" + chunkSizeToView +
                "&datanodePort=" + nextDatanodePort +
                "&namenodeInfoPort=" + namenodeInfoPort +
                JspHelper.getDelegationTokenUrlParam(tokenString);
      out.print("View Next chunk  ");
    }
    //determine data for the prev link
    String prevBlockIdStr = null;
    String prevGenStamp = null;
    long prevStartOffset = 0;
    long prevBlockSize = 0;
    String prevHost = req.getServerName();
    int prevPort = req.getServerPort();
    int prevDatanodePort = datanodePort;
    if (startOffset == 0) {
      List<LocatedBlock> blocks =
        dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks();
      for (int i = 0; i < blocks.size(); i++) {
        if (blocks.get(i).getBlock().getBlockId() == blockId) {
          if (i != 0) {
            LocatedBlock prevBlock = blocks.get(i-1);
            prevBlockIdStr = Long.toString(prevBlock.getBlock().getBlockId());
            prevGenStamp = Long.toString(prevBlock.getBlock().getGenerationStamp());
            prevStartOffset = prevBlock.getBlock().getNumBytes() - chunkSizeToView;
            if (prevStartOffset < 0)
              prevStartOffset = 0;
            prevBlockSize = prevBlock.getBlock().getNumBytes();
            DatanodeInfo d = jspHelper.bestNode(prevBlock);
            String datanodeAddr = d.getName();
            prevDatanodePort = Integer.parseInt(
                                      datanodeAddr.substring(
                                          datanodeAddr.indexOf(':') + 1,
                                      datanodeAddr.length()));
            prevHost = InetAddress.getByName(d.getHost()).getCanonicalHostName();
            prevPort = d.getInfoPort();
          }
        }
      }
    }
    else {
      //we are in the same block
      prevBlockIdStr = blockIdStr;
      prevStartOffset = startOffset - chunkSizeToView;
      if (prevStartOffset < 0) prevStartOffset = 0;
      prevBlockSize = blockSize;
      prevGenStamp = blockGenStamp;
    }

    String prevUrl = null;
    if (prevBlockIdStr != null) {
      prevUrl = "http://" + prevHost + ":" +
                prevPort +
                "/browseBlock.jsp?blockId=" + prevBlockIdStr +
                "&blockSize=" + prevBlockSize + "&startOffset=" +
                prevStartOffset +
                "&filename=" + URLEncoder.encode(filename, "UTF-8") +
                "&chunkSizeToView=" + chunkSizeToView +
                "&genstamp=" + prevGenStamp +
                "&datanodePort=" + prevDatanodePort +
                "&namenodeInfoPort=" + namenodeInfoPort +
                JspHelper.getDelegationTokenUrlParam(tokenString);
      out.print("View Prev chunk  ");
    }
    out.print("
");
    out.print("<textarea cols=\"100\" rows=\"25\" wrap=\"virtual\" style=\"width:100%\" READONLY>");
    try {
    jspHelper.streamBlockInAscii(
            new InetSocketAddress(req.getServerName(), datanodePort), blockId,
            accessToken, genStamp, blockSize, startOffset, chunkSizeToView,
            out, conf);
    } catch (Exception e){
        out.print(e);
    }
    out.print("</textarea>");
    dfs.close();
  }

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.Vector _jspx_dependants;

  private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write('\n');
      out.write('\n');
      out.write("\n\n\n");
JspHelper.createTitle(out, request, request.getParameter("filename"));
      out.write("\n\n\n");

   Configuration conf =
     (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
   generateFileChunks(out, request, conf);

      out.write("\n
\n");

   generateFileDetails(out, request, conf);

      out.write("\n\n
Local logs
\nLog directory\n\n");

out.println(ServletUtil.htmlFooter());

      out.write('\n');
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


text:
package org.jhotdraw.figures;

import java.awt.*;
import java.io.*;
import java.util.List;
import java.awt.image.ImageObserver;
import org.jhotdraw.framework.*;
import org.jhotdraw.standard.*;
import org.jhotdraw.util.*;

/**
 * A Figure that shows an Image.
 * Images shown by an image figure are shared by using the Iconkit.
 *
 * @see Iconkit
 *
 * @version <$CURRENT_VERSION$>
 */
public  class ImageFigure
		extends AttributeFigure implements ImageObserver {

	private String   fFileName;
	private transient Image fImage;
	private Rectangle fDisplayBox;
	/*
	 * Serialization support.
	 */
	private static final long serialVersionUID = 148012030121282439L;
	private int imageFigureSerializedDataVersion = 1;

	public ImageFigure() {
		fFileName = null;
		fImage = null;
		fDisplayBox = null;
	}

	public ImageFigure(Image image, String fileName, Point origin) {
		fFileName = fileName;
		fImage = image;
		// fix for bug-id: 593080 (ImageFigure calculates the image rectangle wrongly)
		basicDisplayBox(origin, new Point(origin.x + fImage.getWidth(this), origin.y + fImage.getHeight(this)));
	}

	public void basicDisplayBox(Point origin, Point corner) {
		fDisplayBox = new Rectangle(origin);
		fDisplayBox.add(corner);
	}

	public HandleEnumeration handles() {
		List handles = CollectionsFactory.current().createList();
		BoxHandleKit.addHandles(this, handles);
		return new HandleEnumerator(handles);
	}

	public Rectangle displayBox() {
		return new Rectangle(
			fDisplayBox.x,
			fDisplayBox.y,
			fDisplayBox.width,
			fDisplayBox.height);
	}

	protected void basicMoveBy(int x, int y) {
		fDisplayBox.translate(x,y);
	}

	public void draw(Graphics g) {
		if (fImage == null) {
			fImage = Iconkit.instance().getImage(fFileName);
		}
		if (fImage != null) {
			g.drawImage(fImage, fDisplayBox.x, fDisplayBox.y, fDisplayBox.width, fDisplayBox.height, this);
		}
		else {
			drawGhost(g);
		}
	}

	private void drawGhost(Graphics g) {
		g.setColor(Color.gray);
		g.fillRect(fDisplayBox.x, fDisplayBox.y, fDisplayBox.width, fDisplayBox.height);
	}

   /**
	* Handles asynchroneous image updates.
	*/
	public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
		if ((flags & (FRAMEBITS|ALLBITS)) != 0) {
			invalidate();
			if (listener() != null) {
				listener().figureRequestUpdate(new FigureChangeEvent(this));
			}
		}
		return (flags & (ALLBITS|ABORT)) == 0;
	}

	/**
	 * Releases a figure's resources. Release is called when
	 * a figure is removed from a drawing. Informs the listeners that
	 * the figure is removed by calling figureRemoved.
	 */
	public void release() {
		fImage.flush();
	}

   /**
	* Writes the ImageFigure to a StorableOutput. Only a reference to the
	* image, that is its pathname is saved.
	*/
	public void write(StorableOutput dw) {
		super.write(dw);
		dw.writeInt(fDisplayBox.x);
		dw.writeInt(fDisplayBox.y);
		dw.writeInt(fDisplayBox.width);
		dw.writeInt(fDisplayBox.height);
		dw.writeString(fFileName);
	}

   /**
	* Reads the ImageFigure from a StorableInput. It registers the
	* referenced figure to be loaded from the Iconkit.
	* @see Iconkit#registerImage
	*/
	public void read(StorableInput dr) throws IOException {
		super.read(dr);
		fDisplayBox = new Rectangle(
			dr.readInt(),
			dr.readInt(),
			dr.readInt(),
			dr.readInt());
		fFileName = dr.readString();
		Iconkit.instance().registerImage(fFileName);
	}

	private void readObject(ObjectInputStream s)
		throws ClassNotFoundException, IOException {

		s.defaultReadObject();
		Iconkit.instance().registerImage(fFileName);
		fImage = null;
	}
}


text:
package com.github.aleksandy.petrovich.rules.data;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Rules {

    @JsonProperty("lastname")
    private RuleSet lastName;

    @JsonProperty("firstname")
    private RuleSet firstName;

    @JsonProperty("middlename")
    private RuleSet middleName;

    public RuleSet getLastName() {
        return lastName;
    }

    public void setLastName(RuleSet lastName) {
        this.lastName = lastName;
    }

    public RuleSet getFirstName() {
        return firstName;
    }

    public void setFirstName(RuleSet firstName) {
        this.firstName = firstName;
    }

    public RuleSet getMiddleName() {
        return middleName;
    }

    public void setMiddleName(RuleSet middleName) {
        this.middleName = middleName;
    }

}


text:
package umich.ms.fileio.filetypes.mzml.jaxb;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * This element must be used to describe an Analyzer Component Type. This is a PRIDE3-specific
 * modification of the core MzML schema that does not have any impact on the base schema
 * validation.
 *
 *
 *
Java class for AnalyzerComponentType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="AnalyzerComponentType">
 *   <complexContent>
 *     <extension base="{http://psi.hupo.org/ms/mzml}ComponentType">
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AnalyzerComponentType")
public class AnalyzerComponentType
    extends ComponentType {

}


text:
/*
 * Stub for class boofcv.core.image.border.ImageBorderValue.Value_IL_F64
 * Generated by Sapphire Compiler (sc).
 */
package boofcv.core.image.border.stubs;

public final class ImageBorderValue$Value_IL_F64_Stub extends boofcv.core.image.border.ImageBorderValue.Value_IL_F64 implements sapphire.common.AppObjectStub {

    sapphire.policy.SapphirePolicy.SapphireClientPolicy $__client = null;
    boolean $__directInvocation = false;

    public ImageBorderValue$Value_IL_F64_Stub (double $param_double_1) {
        super($param_double_1);
    }

    public ImageBorderValue$Value_IL_F64_Stub (boofcv.struct.image.InterleavedF64 $param_InterleavedF64_1, double $param_double_2) {
        super($param_InterleavedF64_1, $param_double_2);
    }

    public void $__initialize(sapphire.policy.SapphirePolicy.SapphireClientPolicy client) {
        $__client = client;
    }

    public void $__initialize(boolean directInvocation) {
        $__directInvocation = directInvocation;
    }

    public Object $__clone() throws CloneNotSupportedException {
        return super.clone();
    }

    // Implementation of setOutside(int, int, double[])
    public void setOutside(int $param_int_1, int $param_int_2, double[] $param_arrayOf_double_3) {
        java.lang.Object $__result = null;
        try {
            if ($__directInvocation)
                super.setOutside( $param_int_1,  $param_int_2,  $param_arrayOf_double_3);
            else {
                java.util.ArrayList<Object> $__params = new java.util.ArrayList<Object>();
                String $__method = "public void boofcv.core.image.border.ImageBorderValue$Value_IL_F64.setOutside(int,int,double[])";
                $__params.add($param_int_1);
                $__params.add($param_int_2);
                $__params.add($param_arrayOf_double_3);
                $__result = $__client.onRPC($__method, $__params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Implementation of getOutside(int, int, double[])
    public void getOutside(int $param_int_1, int $param_int_2, double[] $param_arrayOf_double_3) {
        java.lang.Object $__result = null;
        try {
            if ($__directInvocation)
                super.getOutside( $param_int_1,  $param_int_2,  $param_arrayOf_double_3);
            else {
                java.util.ArrayList<Object> $__params = new java.util.ArrayList<Object>();
                String $__method = "public void boofcv.core.image.border.ImageBorderValue$Value_IL_F64.getOutside(int,int,double[])";
                $__params.add($param_int_1);
                $__params.add($param_int_2);
                $__params.add($param_arrayOf_double_3);
                $__result = $__client.onRPC($__method, $__params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
package org.kuali.kra.bo;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kuali.coeus.common.framework.person.attr.KcPersonExtendedAttributes;
import org.kuali.coeus.common.impl.person.attr.KcPersonExtendedAttributesMaintainableImpl;
import org.kuali.coeus.common.impl.person.attr.KcPersonExtendedAttributesMaintenanceDocumentRule;
import org.kuali.kra.maintenance.MaintenanceRuleTestBase;
import org.kuali.rice.core.api.util.RiceKeyConstants;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.krad.UserSession;
import org.kuali.rice.krad.bo.PersistableBusinessObject;
import org.kuali.rice.krad.maintenance.MaintainableImpl;
import org.kuali.rice.krad.util.ErrorMessage;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.MessageMap;

import java.util.List;
import static org.junit.Assert.*;
public class KcPersonExtendedAttributesMaintenanceDocumentRuleTest extends MaintenanceRuleTestBase {
    private KcPersonExtendedAttributesMaintenanceDocumentRule rule = null;

    @Before
    public void setUp() throws Exception {
        rule = new KcPersonExtendedAttributesMaintenanceDocumentRule();
        GlobalVariables.setUserSession(new UserSession("quickstart"));
    }

    @After
    public void tearDown() throws Exception {
        rule = null;
    }

    @Test
    public void testExists() throws Exception {
        KcPersonExtendedAttributes kcPersonEA= new KcPersonExtendedAttributes();
        kcPersonEA.setPersonId("10000000001");   // quickstart's id, should exists
        MaintenanceDocument kcPesonExtendedAttribuesDocument = newMaintDoc(kcPersonEA);
        MessageMap eMap = GlobalVariables.getMessageMap();
        assertEquals(0, eMap.getErrorCount());
        assertTrue(rule.processSaveDocument(kcPesonExtendedAttribuesDocument));
        assertEquals(0, eMap.getErrorCount());
    }

    protected MaintainableImpl getNewMaintainableImpl(PersistableBusinessObject bo) {
        if (bo == null) {
            return new KcPersonExtendedAttributesMaintainableImpl();
        } else {
            MaintainableImpl result = new KcPersonExtendedAttributesMaintainableImpl();
            result.setDataObject(bo);
            return result;
        }
    }

    @Test
    public void testNotExists() throws Exception {
        KcPersonExtendedAttributes kcPersonEA = new KcPersonExtendedAttributes();
        kcPersonEA.setPersonId("12345");   // should not exists
        MaintenanceDocument kcPesonExtendedAttribuesDocument = newMaintDoc(kcPersonEA);
        MessageMap eMap = GlobalVariables.getMessageMap();
        assertEquals(0, eMap.getErrorCount());
        assertFalse(rule.processSaveDocument(kcPesonExtendedAttribuesDocument));
        assertEquals(1, eMap.getErrorCount());
        List errors = eMap.getErrorMessagesForProperty(KRADConstants.MAINTENANCE_NEW_MAINTAINABLE + "principalId");
        ErrorMessage message = (ErrorMessage) errors.get(0);
        assertEquals(message.getErrorKey(), RiceKeyConstants.ERROR_EXISTENCE);
    }
}


text:
package com.example.helloendpoints;

/**
 * Contains the client IDs and scopes for allowed clients consuming the helloworld API.
 */
public class Constants {
  public static final String WEB_CLIENT_ID = "170501818751-7573rcg7ojuspnnosvuklkko8jgj7bfb.apps.googleusercontent.com";
  public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID";
  public static final String IOS_CLIENT_ID = "replace this with your iOS client ID";
  public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID;

  public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";

  public static final String API_EXPLORER_CLIENT_ID = com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. bot. Zbl. 49(2): 274 (1932)

#### Original name
Russula puellaris var. caucasica Singer

### Remarks
null


text:
<?php
$estados_fact=array(
    "no emitida" => "No emitida",
    "emitida" => "Emitida",
    "pdte. de envío" => "Pendiente de Envío",
    "pdte. de cobro" => "Pendiente de Cobro",
    "cobrada" => "Cobrada",
    "anulada" => "Anulada",
);

echo Form::open(array("class"=>"form-horizontal")); ?>
	<fieldset>
		<?php echo Form::input('num_fact', Input::post('num_fact', isset($factura) ? $factura->num_fact : ''), array('class' => 'col-md-4 form-control hidden')); ?>
		<?php echo Form::input('num_cuota', Input::post('num_cuota', isset($factura) ? $factura->num_cuota : ''), array('class' => 'col-md-4 form-control hidden')); ?>
		<?php echo Form::input('idsc', Input::post('idsc', isset($factura) ? $factura->idsc : ''), array('class' => 'col-md-4 form-control hidden')); ?>
		<?php echo Form::input('mes_cobro', Input::post('mes_cobro', isset($factura) ? $factura->mes_cobro : ''), array('class' => 'col-md-4 form-control hidden')); ?>
		<?php echo Form::input('anyo_cobro', Input::post('anyo_cobro', isset($factura) ? $factura->anyo_cobro : ''), array('class' => 'col-md-4 form-control hidden')); ?>

			<?php echo Form::label('Estado', 'estado', array('class'=>'control-label')); ?>
			<?php echo Form::select('estado', Input::post('estado', isset($factura) ? $factura->estado : ''),$estados_fact, array('class' => 'col-md-4 form-control', 'placeholder'=>'Estado')); ?>

			<?php echo Form::submit('submit', 'Guardar', array('class' => 'btn btn-primary')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text:
'use strict';

export const ADD_SPEC_STEP                = 'ADD_SPEC_STEP';
export const ADD_SPEC_SUBSTEP_STEP        = 'ADD_SPEC_SUBSTEP_STEP';
export const CLOSE_SPEC_SUBSTEP_STEP      = 'CLOSE_SPEC_SUBSTEP_STEP';

export const ADD_USER_ACTION              = 'ADD_USER_ACTION';
export const ADD_EXPECT_ACTION            = 'ADD_EXPECT_ACTION';

export const UPDATE_CURRENT_USER_ACTION   = 'UPDATE_CURRENT_USER_ACTION';

export const SET_RETURN_ON_ACTION         = 'SET_RETURN_ON_ACTION';

export const ADD_SPEC                     = 'ADD_SPEC';

export const PARSE_TO_CLIENT_SPEC         = 'PARSE_TO_CLIENT_SPEC';
export const ADD_TEST_HOOK_TO_TRACK       = 'ADD_TEST_HOOK_TO_TRACK';
export const ADD_INPUT_TYPE_TO_TRACK      = 'ADD_INPUT_TYPE_TO_TRACK';
export const ADD_DESCRIPTOR               = 'ADD_DESCRIPTOR';

export const ADD_TRACKABLE_EVENT          = 'ADD_TRACKABLE_EVENT';
export const REMOVE_TRACKABLE_EVENT       = 'REMOVE_TRACKABLE_EVENT';


text:
package ws.wamp.jawampa.transport;

import ws.wamp.jawampa.WampRouter;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.StringUtil;
import ws.wamp.jawampa.WampSerialization;

import java.util.List;

import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpVersion.*;

/**
 * A websocket server adapter for WAMP that integrates into a Netty pipeline.
 */
public class WampServerWebsocketHandler extends ChannelInboundHandlerAdapter {

    final String websocketPath;
    final WampRouter router;
    final List<WampSerialization> supportedSerializations;

    WampSerialization serialization = WampSerialization.Invalid;
    boolean handshakeInProgress = false;

    public WampServerWebsocketHandler(String websocketPath, WampRouter router) {
        this(websocketPath, router, WampSerialization.defaultSerializations());
    }

    public WampServerWebsocketHandler(String websocketPath, WampRouter router,
                                      List<WampSerialization> supportedSerializations) {
        this.websocketPath = websocketPath;
        this.router = router;
        this.supportedSerializations = supportedSerializations;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest request = (msg instanceof FullHttpRequest) ? (FullHttpRequest) msg : null;

        // Check for invalid http messages during handshake
        if (request != null && handshakeInProgress) {
            request.release();
            sendBadRequestAndClose(ctx, null);
            return;
        }

        // Transform this when we have an upgrade for our path,
        // otherwise pass the message
        if (request != null && isUpgradeRequest(request)) {
            try {
                tryWebsocketHandshake(ctx, (FullHttpRequest) msg);
            } finally {
                request.release();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private boolean isUpgradeRequest(FullHttpRequest request) {
        if (!request.getDecoderResult().isSuccess()) {
            return false;
        }

        String connectionHeaderValue = request.headers().get(HttpHeaders.Names.CONNECTION);
        if (connectionHeaderValue == null) {
            return false;
        }
        String[] connectionHeaderFields = StringUtil.split(connectionHeaderValue.toLowerCase(), ',');
        boolean hasUpgradeField = false;
        for (String s : connectionHeaderFields) {
            if (s.trim().equals(HttpHeaders.Values.UPGRADE.toLowerCase())) {
                hasUpgradeField = true;
                break;
            }
        }
        if (!hasUpgradeField) {
            return false;
        }

        if (!request.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)){
            return false;
        }

        return request.getUri().equals(websocketPath);
    }

    private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
        String wsLocation = getWebSocketLocation(ctx, request);
        String subProtocols = WampSerialization.makeWebsocketSubprotocolList(supportedSerializations);
        WebSocketServerHandshaker handshaker =
            new WebSocketServerHandshakerFactory(wsLocation,
                                                 subProtocols,
                                                 false,
                                                 WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE)
                                                .newHandshaker(request);

        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshakeInProgress = true;
            final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
            String actualProtocol = handshaker.selectedSubprotocol();
            serialization = WampSerialization.fromString(actualProtocol);

            // In case of unsupported websocket subprotocols we close the connection.
            // Won't help us when the client will ignore our protocol response and send
            // invalid packets anyway
            if (serialization == WampSerialization.Invalid) {
                handshakeFuture.addListener(ChannelFutureListener.CLOSE);
                return;
            }

            // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
            ChannelHandler last = ctx.pipeline().last();
            while (last != null && last != this) {
                ctx.pipeline().removeLast();
                last = ctx.pipeline().last();
            }

            if (last == null) {
                throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
            }

            // Remove the WampServerWebSocketHandler and replace it with the protocol handler
            // which processes pings and closes
            ProtocolHandler protocolHandler = new ProtocolHandler();
            ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
            final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);

            // Handle websocket fragmentation before the deserializer
            protocolHandlerCtx.pipeline().addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));

            // Install the serializer and deserializer
            protocolHandlerCtx.pipeline().addLast("wamp-serializer",
                new WampSerializationHandler(serialization));
            protocolHandlerCtx.pipeline().addLast("wamp-deserializer",
                new WampDeserializationHandler(serialization));

            // Install the router in the pipeline
            protocolHandlerCtx.pipeline().addLast(router.eventLoop(), "wamp-router", router.createRouterHandler());

            handshakeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    } else {
                        // We successfully sent out the handshake
                        // Notify the activation to everything new
                        ctx.fireChannelActive();
                    }
                }
            });
        }
    }

    private String getWebSocketLocation(ChannelHandlerContext ctx, FullHttpRequest req) {
        String location = req.headers().get(HOST) + websocketPath;
        if (ctx.pipeline().get(SslHandler.class) != null) {
            return "wss://" + location;
        } else {
            return "ws://" + location;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof WebSocketHandshakeException) {
            sendBadRequestAndClose(ctx, cause.getMessage());
        } else {
            ctx.close();
        }
    }

    private static void sendBadRequestAndClose(ChannelHandlerContext ctx, String message) {
        FullHttpResponse response;
        if (message != null) {
            response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
                                                   Unpooled.wrappedBuffer(message.getBytes()));
        } else {
            response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        }
        ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    public static class ProtocolHandler extends ChannelInboundHandlerAdapter {

        enum ReadState {
            Closed,
            Reading,
            Error
        }

        ReadState readState = ReadState.Reading;

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) {
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            ctx.fireChannelActive();
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) {
            readState = ReadState.Closed;
            ctx.fireChannelInactive();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // Discard messages when we are not reading
            if (readState != ReadState.Reading) {
                ReferenceCountUtil.release(msg);
                return;
            }

            // We might receive http requests here when the whe clients sends something after the upgrade
            // request but we have not fully sent out the response and the http codec is still installed.
            // However that would be an error.
            if (msg instanceof FullHttpRequest) {
                ((FullHttpRequest) msg).release();
                WampServerWebsocketHandler.sendBadRequestAndClose(ctx, null);
                return;
            }

            if (msg instanceof PingWebSocketFrame) {
                // Respond to Pings with Pongs
                try {
                    ctx.writeAndFlush(new PongWebSocketFrame());
                } finally {
                    ((PingWebSocketFrame) msg).release();
                }
            } else if (msg instanceof CloseWebSocketFrame) {
                // Echo the close and close the connection
                readState = ReadState.Closed;
                ctx.writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE);

            } else {
                ctx.fireChannelRead(msg);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            // Will be called either through an exception in channelRead
            // or when the websocket handshake fails
            readState = ReadState.Error;
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            ctx.fireExceptionCaught(cause);
        }
    }
}


text:
/**
 * Module for interfacing with the Kalabox container system implementation, and
 * the provider of the container system.
 *
 * NOTE: The container system and the provider are not always the same. For
 * example using docker on a Mac would use docker as the container system,
 * however it would be provided by boot2docker.
 * @module kbox.engine
 */

'use strict';

var core = require('./core.js');
var util = require('./util.js');
var helpers = util.helpers;
var _ = require('lodash');

var provider = require('./engine/provider.js');
exports.provider = provider;

var engine = null;

var makeProviderError = function(msg) {
  return new Error(
    ['Provider "' + engine.getProviderName() + '"', msg].join(' ')
  );
};

var isProviderInstalled = false;
var verifyProviderInstalled = function(callback) {
  if (isProviderInstalled) {
    callback(null);
  } else {
    provider.isInstalled(function(err, isInstalled) {
      if (err) {
        callback(err);
      } else if (!isInstalled) {
        callback(makeProviderError('is NOT installed!'));
      } else {
        isProviderInstalled = true;
        callback(null);
      }
    });
  }
};

var isProviderUp = false;
var verifyProviderUp = function(callback) {
  if (isProviderUp) {
    callback(null);
  } else {
    provider.isUp(function(err, isUp) {
      if (err) {
        callback(err);
      } else if (!isUp) {
        callback(makeProviderError('is NOT up!'));
      } else {
        isProviderUp = true;
        callback(null);
      }
    });
  }
};

var engineHasBeenInit = false;
var verifyProviderIsReady = function(callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      verifyProviderUp(function(err) {
        if (err) {
          callback(err);
        } else {
          if (!engineHasBeenInit) {
            provider.engineConfig(function(err, config) {
              if (err) {
                callback(err);
              }
              else {
                engine.init(config);
                engineHasBeenInit = true;
                callback(null);
              }
            });
          }
          else {
            callback(null);
          }
        }
      });
    }
  });
};

/**
 * Returns the name of the configured provider.
 * @returns {string} - Name of the configured provider.
 */
exports.getProviderName = function() {
  return provider.name;
};

/**
 * Retrieves the state of the engine being up.
 * @arg {function} callback
 * @arg {error} callback.error
 * @arg {boolean} callback.isUp - Boolean representing the state of the engine being up.
 * @example
 * kbox.engine.isUp(function(err, isUp) {
 *   if (err) {
 *     throw err;
 *   } else if (isUp) {
 *     console.log('It is up!');
 *   }
 * });
 */
exports.isUp = function(callback) {
  provider.isUp(callback);
};

/**
 * Initializes kalabox engine.
 * @arg {string} globalConfig - Kalabox global config to initialize with.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * kbox.engine.init(globalConfig);
 */
exports.init = function(globalConfig) {
  if (!engine) {
    engine = require('./engine/' + globalConfig.engine + '.js');
    core.deps.register('providerModule', engine.getProviderModule());
  }
};

/**
 * Gets the engine provider into the state it needs to be in to do
 * engine things.
 * @arg {int} attempts - The amount of times to try to start the engine.
 * @arg {function} callback - Callback called when the engine has started.
 * @arg {error} callback.error
 */
exports.up = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.up(attempts, callback);
      provider.up(callback);
    }
  });
};

/**
 * Turns the engine off.
 * @arg {int} attempts - The amount of times to try to stop the engine.
 * @arg {function} callback - Callback called when the engine has been stopped.
 * @arg {error} callback.error
 */
exports.down = function(attempts, callback) {
  verifyProviderInstalled(function(err) {
    if (err) {
      callback(err);
    } else {
      //provider.down(attempts, callback);
      provider.down(callback);
    }
  });
};

/**
 * Lists installed containers.
 * @arg {string} appName [optional] - App name to filter containers by.
 * @arg {function} callback - Callback called when the engine query completes.
 * @arg {error} callback.error
 * @arg {array} callback.containers - An array of container objects.
 * @example
 * kbox.engine.list(function(err, containers) {
 *   for (var i = 0; i < containers.length; ++i) {
 *     console.log(containers[i].name);
 *   }
 * });
 */
var list = exports.list = function(appName, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.list(appName, callback);
    }
  });
};

// @todo: document...
exports.exists = function(cid, callback) {
  list(function(err, containers) {
    if (err) {
      callback(err);
    } else {
      var exists = _.find(containers, function(container) {
        return container.id === cid || container.name === cid;
      });
      callback(null, exists !== undefined);
    }
  });
};

/**
 * Inspects a container and returns details.
 * @arg {string} containerId - Id of the container to inspect.
 * @arg {function} callback - Callback called when the container has been inspected.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the containers inspected data.
 */
exports.inspect = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.getEnsure(cid, 'inspect', function(err, container) {
        if (err) {
          callback(err);
        } else {
          engine.inspect(container, callback);
        }
      });
    }
  });
};

// @todo: document
exports.info = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.info(cid, callback);
    }
  });
};

/**
 * Creates a container.
 * @arg {object} startOptions [optional] - Object containing the create options for the container.
 * @arg {function} callback - Callback called when the container has been created.
 * @arg {error} callback.error
 * @arg {object} callback.data - Object containing the created containers information.
 */
// @todo: find a good way to document createOptions, and possibly not make them docker specific.
exports.create = function(createOptions, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.create(createOptions, callback);
    }
  });
};

/**
 * Starts a container.
 * @arg {string} containerId - Id of the container to start.
 * @arg {object} startOptions [optional] - Object containing the start options for the container.
 * @arg {function} callback - Callback called when the container has been started.
 * @arg {error} callback.error
 * @todo Find a good way to document startOptions, and possibly not make them docker specific.
 */
exports.start = function(cid, startOptions, callback) {
  if (typeof startOptions === 'function' && callback === undefined) {
    callback = startOptions;
    startOptions = null;
  }
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.start(cid, startOptions, function(err) {
        // @todo: This short delay is to give redis a chance to get into a good state.
        // A better check would be bounded polling of redis until it is in a good state.
        setTimeout(function() {
          callback(err);
        }, 3000);
      });
    }
  });
};

/**
 * Stops a container.
 * @arg {string} containerId - Id of the container to stop.
 * @arg {function} callback - Callback called when the container has been stopped.
 * @arg {error} callback.error
 * @example
 * kbox.engine.stop(containerId, function(err) {
 *   if (err) {
 *     throw err;
 *   }
 *   console.log('Container stopped!');
 * });
 */
exports.stop = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.stop(cid, callback);
    }
  });
};

/**
 * Removes a container from the engine.
 * @arg {string} containerId - Id of the container to remove.
 * @arg {function} callback - Callback called when the container has been removed.
 * @arg {error} callback.error
 */
exports.remove = function(cid, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.remove(cid, callback);
    }
  });
};

/**
 * Pulls or builds the image for a container.
 * @arg {object} image - Image object to pull or build.
 * @arg {function} callback - Callback called when the image has been built.
 * @arg {error} callback.error
 */
exports.build = function(image, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      var fn = (image.build) ? 'build' : 'pull';
      engine[fn](image, callback);
    }
  });
};

/**
 * TODO
 */
var run = function(image, cmd, streamo, createOptions, startOptions, callback) {
  verifyProviderIsReady(function(err) {
    if (err) {
      callback(err);
    } else {
      engine.run(image, cmd, streamo, createOptions, startOptions, callback);
    }
  });
};
exports.run = run;


text:
/* CSS using SCSS
        Created By: Don Page on 12/15/14
        Don.page.work@gmail.com
        @DonRPage
  */
@import url(../bower_components/angular-material/angular-material.css);
@import url(../bower_components/angular-material/themes/indigo-theme.css);

.shop-wrapper--outer {
    width: 100%;
    max-width: 960px;
    margin: 20px auto; }

.shop-wrapper {
    height: 500px; }


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

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="up" title="FatFs" href="../00index_e.html">
<link rel="alternate" hreflang="ja" title="Japanese" href="../ja/gets.html">
<link rel="stylesheet" href="../css_e.css" type="text/css" media="screen" title="ELM Default">
<title>FatFs - f_gets</title>

f_gets

The f_gets reads a string from the file.

TCHAR* f_gets (
  TCHAR* buff, /* [OUT] Read buffer */
  int len,     /* [IN] Size of the read buffer */
  FIL* fp      /* [IN] File object */
);

Parameters

buff

Pointer to read buffer to store the read string.

len

Size of the read buffer in unit of character.

fp

Pointer to the open file object structure.

Return Values

When the function succeeded, <tt class="arg">buff</tt> will be returuned.

Description

The read operation continues until a <tt>'\n'</tt> is stored, reached end of the file or the buffer is filled with <tt>len - 1</tt> characters. The read string is terminated with a <tt>'\0'</tt>. When no character to read or any error occured during read operation, it returns a null pointer. The status of EOF and error can be examined with <tt>f_eof</tt> and <tt>f_error</tt> function.

When FatFs is configured to Unicode API (<tt>_LFN_UNICODE == 1</tt>), data types on the srting fuctions, <tt>f_putc</tt>, <tt>f_puts</tt>, <tt>f_printf</tt> and <tt>f_gets</tt>, is also switched to Unicode. The character encoding on the file to be read/written via those functions is selected by <tt>_STRF_ENCODE</tt> option.

QuickInfo

This is a wrapper function of <tt>f_read</tt> function. Available when <tt>_USE_STRFUNC</tt> is 1 or 2. When it is set to 2, <tt>'\r'</tt>s contained in the file are stripped out.

See Also

<tt>f_open, f_read, f_putc, f_puts, f_printf, f_close, FIL</tt>

Return


text:
function FV(viewId : string) : View {
    //Use currently active?
    return null;
}

class ViewEvent {
    public view : View;
    public callback : Function;
    public cancellable : boolean;

    constructor(view : View, callback : Function, cancellable : boolean) {
        this.view = view;
        this.callback = callback;
        this.cancellable = cancellable;
    }
}

enum FragmentFlags {
    None,
    ClearTop,
}

var MAX_HISTORY_SIZE = 10;

class FragmentStackItem {
    private _fragmentClass : any = null;
    private _uriParams : any = {};
}

class FragmentRouter {
    private _url : string = "";
    private _fragment : any = null;
    private _flags : FragmentFlags = FragmentFlags.None;
}

class Application {
    public window : RootView = null;
    public root : View = null;
    public overlay : View = null;
    public rect : Rect = new Rect(0, 0, 0, 0);
    public canvas : HTMLCanvasElement = null;
    public renderer : Renderer = null;
    private _drawPending : boolean = false;
    private _layoutRequested : boolean = false;
    private _layoutPending : boolean = false;
    private _eventsPending : boolean = false;
    private _events : ViewEvent[] = [];
    private _cursor : string = "auto";
    private _hoverView : View = null;
    private _focusView : View = null;
    private _captureView : View = null; //TODO
    private _inputElement : HTMLInputElement = null;
    private _inputElementIgnores : number = 0;
    private _drawBlocks : number = 0; //Prevent requestAnimationFrame and alert() draws
    private _layoutBlocks : number = 0;
    private _layoutBroken : boolean = false;
    private _lastDrawTime : number = 0;

    private _fragmentStack : FragmentStackItem[] = [];
    private _fragmentRouters : FragmentRouter[] = [];

    constructor() {

    }

    startFragment(fragment : Fragment) {

    }

    startFragmentByName(name : string) {

    }

    $(id : string) : View {
        return this.window.findView(id);
    }

    theme() : Theme {
        return this.window.theme();
    }

    layoutRequested() : boolean {
        return this._layoutRequested;
    }

    drawPending() : boolean {
        return this._drawPending;
    }

    getFocusView() : View {
        return this._focusView;
    }

    blockLayout(block : boolean) {
        if (block) {
            this._layoutBlocks++;
        }
        else {
            this._layoutBlocks--;
        }
    }

    postEvent(event : ViewEvent) {
        this._events.push(event);

        if (!this._eventsPending) {
            this._eventsPending = true;

            setTimeout(() => {
                this._processViewEvents();
            }, 0);
        }
    }

    _processViewEvents() {
        //Note that callbacks can add new events.
        for (var i=0; i < this._events.length; ++i) {
            var event = this._events[i];
            if (!event.view.destroyed() || !event.cancellable) {
                event.callback();
            }
        }
        this._events.length = 0;
        this._eventsPending = false;
    }

    _createRootViews() {
        this.window = new RootView();
        this.window._bootstrap(this);

        this.root = new View(this.window);
        this.root.fillParent(true);
        this.root.scrollable(false);
        this.root.clickable(false);

        this.overlay = new View(this.window);
        this.overlay.fillParent(true);
        this.overlay.scrollable(false);
        this.overlay.clickable(false);
    }

    setSize(width : number, height : number) {
        if (width === this.rect.width && height === this.rect.height) {
            //Not changed.
            return;
        }

        if (Config.IS_MOBILE && width === this.rect.width) {
            //Probably a virtual keyboard change, don't do layout.
            this._drawViews();
        }
        else {
            width = Math.max(width, Config.CANVAS_MIN_WIDTH);
            height = Math.max(height, Config.CANVAS_MIN_HEIGHT);

            this.canvas.width = width;
            this.canvas.height = height;

            this.rect = new Rect(0, 0, width, height);

            //No request, do this immediately.
            this._layoutViews();
            this._drawViews();
        }
    }

    setCanvas(canvas : HTMLCanvasElement) {
        this.canvas = canvas;

        var context = canvas.getContext("2d");
        this.renderer = new Renderer(context);
        this.renderer.reset();

        this._setEventListeners(canvas);

        this._createDomInput();
        this._createRootViews();
    }

    _setEventListeners(canvas : HTMLCanvasElement) {
        if (Config.HAS_TOUCH_EVENTS) {
            canvas.addEventListener("touchstart", (event) => { this._onTouchStart(event); return false}, false);
            canvas.addEventListener("touchend", (event) => { this._onTouchEnd(event); return false}, false);
            canvas.addEventListener("touchcancel", (event) => { this._onTouchCancel(event); return false}, false);
            canvas.addEventListener("touchmove", (event) => { this._onTouchMove(event); return false}, false);
        }
        else {
            canvas.addEventListener("mousedown", (event) => { this._onMouseDown(event); return false; }, false);
            canvas.addEventListener("mouseup", (event) => { this._onMouseUp(event); return false; }, false);
            canvas.addEventListener("mousemove", (event) => { this._onMouseMove(event); return false; }, false);

            var mouseWheelListener = (event) => { this._onMouseWheel(event); return false; }
            canvas.addEventListener("mousewheel", mouseWheelListener, false);
            canvas.addEventListener("DOMMouseScroll", mouseWheelListener, false);
        }

        var keyDownListener = (event) => { this._onKeyDown(event || window.event); return false; };
        var keyUpListener = (event) => { this._onKeyUp(event || window.event); return false; };
        var keyPressListener = (event) => { this._onKeyPress(event || window.event); return false; };

        window.addEventListener("keydown", keyDownListener, false);
        window.addEventListener("keyup", keyUpListener, false);
        //window.addEventListener("keypress", keyPressListener, false);
    }

    _createDomInput() {
        var input = document.createElement("input");
        input.type = "text";
        input.value = "";
        input.style.position = "absolute";
        input.style.left = "0px";
        input.style.top = "-100px";
        input.style.width = "10px";
        input.style.height = "10px";
        input.style.zIndex = "10";

        var listener = (event) => {
            this._stopNativeEvent(event);

            var text = input.value;
            input.value = "";

            for (var i=0; i < text.length; ++i) {
                var fake = {
                    keyCode: 0,
                    ctrlKey: false,
                    metaKey: false,
                    charCode: text.charCodeAt(i)
                };
                this._onKeyPress(fake);
            }
        };
        input.onchange = listener
        input.onkeypress = () => { input.value = ""; }
        input.onpaste = () => { input.value = ""; }
        input.oninput = listener

        document.body.appendChild(input);
        this._inputElement = input;
    }

    inputElement() : HTMLInputElement {
        return this._inputElement;
    }

    inputElementText(text : string) {
        this._inputElementIgnores++;
        this._inputElement.value = text;
        this._inputElement.focus();
        this._inputElement.select();
    }

    focusInputElement(focus : boolean) {
        if (focus) {
            this._inputElement.focus();
            if (window["GuiHooks"]) {
                window["GuiHooks"].showVirtualKeyboard();
            }
        }
        else {
            this._inputElement.blur();
        }
    }

    clearInputElement() {
        this._inputElement.value = "";
    }

    setCursor(cursor : string) {
        this._cursor = cursor;
    }

    _handleViewClose(view : View) {
        if (view === this._hoverView) {
            this._setHoverView(null);
        }
        if (view === this._focusView) {
            this._setFocusView(null);
        }
        if (view === this._captureView) {
            this._stopIntercept(view);
        }
    }

    _setHoverView(view : View) {
        if (view !== this._hoverView) {
            if (this._hoverView) {
                this._hoverView.onHoverEnd();
            }
            this._hoverView = view;
            if (view) {
                view.onHoverStart();
            }
        }
    }

    _setFocusView(view : View) {
        if (view !== this._focusView) {
            if (this._focusView) {
                this._focusView.onLoseFocus();
            }
            this._focusView = view;
            if (view) {
                view.onGainFocus();
            }
        }
    }

    _startIntercept(view : View) {
        if (this._captureView === null) {
            this._captureView = view;
        }
    }

    _stopIntercept(view : View) : boolean {
        if (this._captureView === view) {
            this._captureView = null;
            return true;
        }
        return false;
    }

    _stopInterceptIfRequired(input : InputEvent) {
        if (this._captureView !== null) {
            if (input.type === InputType.MouseUp || !this._captureView.enabled()) {  //TODO OR CANCEL
                this._stopIntercept(this._captureView);
            }
        }
    }

    _convertInputEvent(event : MouseEvent, eventType : InputType) : InputEvent {
        var rect = this.canvas.getBoundingClientRect(); //TODO offsetLeft ja offsetTop ?
        var input = new InputEvent(eventType, event.clientX - rect.left, event.clientY - rect.top);
        if (eventType === InputType.MouseWheel) {
            input.scroll = Math.max(-1, Math.min(1, (event["wheelDelta"] || -event.detail)));
        }
        return input;
    }

    _convertKeyEvent(event : KeyboardEvent, eventType : InputType) : KeyEvent {
        var keyEvent = new KeyEvent(eventType);
        keyEvent.keyCode = event.keyCode;
        keyEvent.ctrlKey = event.ctrlKey;
        keyEvent.metaKey = event.metaKey;
        if (eventType === InputType.KeyPress) {
            keyEvent.charCode = event.which || event.charCode;
        }
        return keyEvent;
    }

    _createViewState(x : number, y : number, reason : WalkReason) : ViewState {
        this.renderer.resetTextAttributes();
        var state = new ViewState(this.renderer, reason);
        state.x = x;
        state.y = y;
        state.time = Date.now();
        state.bbox = this.window.rect().copy();
        return state;
    }

    _transformViews(hit : View, input : InputEvent, reason : WalkReason, callback : Function) : View {
        this.renderer.saveTransform();
        this.renderer.setIdentity();

        var parents = [];
        var parent = hit;
        while (parent !== null) {
            parents.push(parent);
            parent = parent.parent();
        }
        parents.reverse();

        var state = this._createViewState(input.x, input.y, reason);
        for (var i=0; i < parents.length; ++i) {
            parents[i]._pushViewTransform(state);
            parents[i]._pushViewTranslation(state);
        }

        var interceptor = null;

        parents.reverse();
        for (var i=0; i < parents.length; ++i) {
            this.renderer.popTransform();
            var view = parents[i];
            if (interceptor === null && view.visibility() === Visibility.Visible && view.enabled()) {
                view._updateViewState(state);
                if (callback(view, state, input)) {
                    interceptor = view;
                }
            }
            this.renderer.popTransform();
        }
        this.renderer.popTransform();

        return interceptor;
    }

    _stopNativeEvent(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        }
        if (event.preventDefault) {
            event.preventDefault();
        }
    }

    _getViewAt(input : InputEvent, startState : ViewState, viewCallback : Function, interceptCallback : Function) : View {
        return this.window._walkViewTransform(startState, null,
            (view : View, state : ViewState) => {
                var handled = false;

                if (this._captureView === null) {
                    var hitArea = view.onHitTest(state, input.x, input.y);
                    if (hitArea !== HitArea.None) {
                        var interceptor = null;
                        if (this._captureView === null) {
                            interceptor = this._transformViews(view, input, state.reason, interceptCallback);
                        }

                        if (interceptor !== null) {
                            //A view starts to intercept input events.
                            this._startIntercept(interceptor);
                            handled = true;
                        }
                        else {
                            handled = viewCallback(view, input);
                        }
                    }
                }
                return handled;
        });
    }

    _callInputEventHandler(event, eventType : InputType, checkCursor : boolean, callback : Function) {
        this._drawBlocks++;

        this._processViewEvents();

        this._cursor = "auto";

        this._stopNativeEvent(event);

        var reason = WalkReason.HitTest;
        var input = this._convertInputEvent(event, eventType);
        var startState = this._createViewState(input.x, input.y, reason);

        var interceptCallback = (view : View, state : ViewState, input : InputEvent) => {
            return view.onInterceptInputEvent(state, input);
        }

        if (this._captureView !== null) {
            //A view is currently intercepting events. Note that this
            //might call through several intercepting views. For example
            //nested flinging views will all receive the up event and stop.
            this._transformViews(this._captureView, input, reason, interceptCallback);
        }
        this._stopInterceptIfRequired(input);

        var hitView : View = null;
        if (this._captureView === null) {
            hitView = this._getViewAt(input, startState, callback, interceptCallback);
        }

        if (this._captureView !== null) {
            //TODO override hit view if intercepted or set to null?
            hitView = this._captureView;
        }

        if (hitView !== null && hitView.destroyed()) {
            //Some callback closed the view, so don't touch it.
            hitView = null;
        }

        this._setHoverView(hitView);
        if (eventType === InputType.MouseDown) {
            this._setFocusView(hitView);
        }

        if (eventType === InputType.MouseUp && hitView !== null && hitView != this._focusView) {
            //Click started on a view but was moved and released on another view.
            this._setFocusView(hitView);
        }

        this._stopInterceptIfRequired(input);

        if (eventType === InputType.MouseWheel && hitView === null && this._focusView !== null) {
            //If nobody else wanted the mouse wheel event give it to the focus view.
            var scrollCallback = (view : View, state : ViewState, input : InputEvent) => {
                if (view === this._focusView) {
                    callback(this._focusView, input);
                    return true;
                }
                return false;
            }
            this._transformViews(this._focusView, input, reason, scrollCallback);
        }

        if (checkCursor && this.canvas.style.cursor !== this._cursor) {
            this.canvas.style.cursor = this._cursor;
        }

        this._processViewEvents();

        this._drawBlocks--;
    }

    //Mouse events

    _onMouseMove(event) {
        this._callInputEventHandler(event, InputType.MouseMove, true, (view, input) => {
            return view.onInputMove(input);
        });
    }

    _onMouseUp(event) {
        this._callInputEventHandler(event, InputType.MouseUp, false, (view, input) => {
            return view.onInputUp(input);
        });
    }

    _onMouseDown(event) {
        this._callInputEventHandler(event, InputType.MouseDown, false, (view, input) => {
            return view.onInputDown(input);
        });
    }

    _onMouseWheel(event) {
        this._callInputEventHandler(event, InputType.MouseWheel, false, (view, input) => {
            return view.onInputScroll(input);
        });
    }

    //Touch events

    _convertTouchToMouseEvent(event) : any {
        this._stopNativeEvent(event);

        var result : any = {};

        var touch = event.changedTouches[0];
        result.clientX = touch.clientX;
        result.clientY = touch.clientY;

        return result;
    }

    _onTouchStart(event) {
        this._onMouseDown(this._convertTouchToMouseEvent(event));
    }

    _onTouchEnd(event) {
        this._onMouseUp(this._convertTouchToMouseEvent(event));
    }

    _onTouchCancel(event) {

    }

    _onTouchMove(event) {
        this._onMouseMove(this._convertTouchToMouseEvent(event));
    }

    //Keyboard evente

    _callKeyEventHandler(method : string, event : KeyEvent) {
        this._processViewEvents();

        //Start looking a view that handles the event up the view tree.
        //Start from the focused view. If no view has focus use the window view.
        var view = this._focusView || this.window;
        while (view !== null) {
            if (view.visibility() === Visibility.Visible && view.enabled()) {
                var handled = view[method](event);
                if (handled) {
                    break;
                }
            }
            else {
                //Views that are not visible can never get events.
                break;
            }
            view = view.parent();
        }
        this._processViewEvents();
    }

    _onKeyDown(event) {
        this._callKeyEventHandler("onKeyDown", this._convertKeyEvent(event, InputType.KeyDown));
    }

    _onKeyUp(event) {
        this._callKeyEventHandler("onKeyUp", this._convertKeyEvent(event, InputType.KeyUp));
    }

    _onKeyPress(event) {
        this._callKeyEventHandler("onKeyPress", this._convertKeyEvent(event, InputType.KeyPress));
    }

    _resetContext() {
        this.renderer.reset();
    }

    _layoutViewLoop(view : View) {
        if (this._layoutBroken) {
            return;
        }

        var start = Date.now();

        var counter = 0;
        do {
            this._layoutRequested = false;

            this._processViewEvents();

            this._resetContext();
            view.onLayout(new LayoutState());

            this._processViewEvents();

            counter++;
            if (counter > 25) {
                this._layoutBroken = true;
                var msg = "Possible layout loop, layout might be broken. Check your anchors, possibly conflicting constraints etc.";
                Log(msg);
                if (window.alert) {
                    alert(msg);
                }
                break;
            }
        }
        while (this._layoutRequested);

        var end = Date.now();
        var duration = end - start;
        Log("Layout passes: " + counter + " in " + duration + " ms ");

        //Notify that layout is ready
        view._walkViews((v : View) => {
            v.onLayoutReady();
        });
        this._processViewEvents();
    }

    _layoutViews() {
        this._processViewEvents(); //Needed for example ListView child creation without flickering.

        if (this._layoutBlocks > 0) {
            return
        }
        this.renderer.clearCache();

        this._layoutViewLoop(this.window);

        this.renderer.clearCache();
    }

    _drawViews() {
        this._processViewEvents(); //Needed for example ListView child creation without flickering.
        if (this._layoutRequested || this._drawBlocks > 0) {
            //We need to draw, but layout must be done first or we received recursive requests.
            return;
        }
        this.window._walkViews((v : View) => {
            v._onUpdate();
        });
        this._processViewEvents(); //In case update did something to the layout (animations etc.)
        if (this._layoutRequested) {
            return;
        }

        var time = Date.now();
        if (time - this._lastDrawTime > 250) {
            this._lastDrawTime = time;
            //Log("Draw at " + time);
        }

        this._resetContext();
        this.renderer.clearRect(0, 0, this.rect.width, this.rect.height);
        Counters.ViewsDrawn = 0;

        var state = this._createViewState(null, null, WalkReason.Draw);
        this.window._onDrawWalk(state);

        //Log("Views drawn: " + Counters.ViewsDrawn);
    }

    requestLayout() {
        this._layoutRequested = true;

        if (this._layoutPending) {
            return;
        }
        this._layoutPending = true;

        setTimeout(() => {
            this._layoutPending = false;

            if (this._layoutRequested) {
                this._layoutViews();
            }
            this._drawViews();
        }, 0);
    }

    requestDraw() {
        if (this._drawPending || this._layoutPending) {
            //Layout also draws, so wait for it.
            return;
        }
        this._drawPending = true;

        var callback = () => {
            this._drawPending = false;

            this._drawViews();
        }
        if (window.requestAnimationFrame) {
            window.requestAnimationFrame(callback);
        }
        else {
            setTimeout(callback, Config.DRAW_SPEED_MS);
        }
    }
}


text:
using System.ComponentModel.DataAnnotations;

namespace QIP.IODomain.Input {
    public class InUpdateUserBoard {
        [Required]
        [StringLength(128)]
        public string UserId { get; set; }

        [Required]
        [Range(0, long.MaxValue)]
        public long? BoardId { get; set; }

        [Required]
        [Range(1, 2)]
        public InBoardPermission? Permission { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 335911 $ -->
<refentry xml:id="function.wincache-ucache-info" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>wincache_ucache_info</refname>
  <refpurpose>
   Retrieves information about data stored in the user cache
  </refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>array</type><methodname>wincache_ucache_info</methodname>
   <methodparam choice="opt"><type>bool</type><parameter>summaryonly</parameter><initializer>false</initializer></methodparam>
   <methodparam choice="opt"><type>string</type><parameter>key</parameter><initializer>NULL</initializer></methodparam>
  </methodsynopsis>
  <para>
   Retrieves information about data stored in the user cache.
  </para>
 </refsect1>
 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>summaryonly</parameter></term>
     <listitem>
      <para>
       Controls whether the returned array will contain information about individual cache entries
       along with the user cache summary.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>key</parameter></term>
     <listitem>
      <para>
       The key of an entry in the user cache. If specified then the returned array will contain information
       only about that cache entry. If not specified and <parameter>summaryonly</parameter> is set to
       &false; then the returned array will contain information about all entries in the cache.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Array of meta data about user cache &return.falseforfailure;
  </para>
    <para>
   The array returned by this function contains the following elements:
   <itemizedlist spacing="compact">
    <listitem>
     <simpara>
      <literal>total_cache_uptime</literal> - total time in seconds that the user cache has been active
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      <literal>total_item_count</literal> - total number of elements that are currently in the user cache
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      <literal>is_local_cache</literal> - true is the cache metadata is for a local cache instance,
       false if the metadata is for the global cache
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      <literal>total_hit_count</literal> - number of times the data has been served from the cache
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      <literal>total_miss_count</literal> - number of times the data has not been found in the cache
     </simpara>
    </listitem>
    <listitem>
     <para>
      <literal>ucache_entries</literal> - an array that contains the information about all the cached items:
      <itemizedlist spacing="compact">
       <listitem>
        <simpara>
         <literal>key_name</literal> - name of the key which is used to store the data
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>value_type</literal> - type of value stored by the key
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>use_time</literal> - time in seconds since the file has been accessed in the opcode cache
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>last_check</literal> - time in seconds since the file has been checked for modifications
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>is_session</literal> - indicates if the data is a session variable
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>ttl_seconds</literal> - time remaining for the data to live in the cache, 0 meaning infinite
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>age_seconds</literal> - time elapsed from the time data has been added in the cache
        </simpara>
       </listitem>
       <listitem>
        <simpara>
         <literal>hitcount</literal> - number of times data has been served from the cache
        </simpara>
       </listitem>
      </itemizedlist>
     </para>
    </listitem>
   </itemizedlist>
  </para>
 </refsect1>
 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title>Using <function>wincache_ucache_info</function></title>
    <programlisting role="php">
<![CDATA[
<?php
wincache_ucache_get('green');
wincache_ucache_set('green', 2922);
wincache_ucache_get('green');
wincache_ucache_get('green');
wincache_ucache_get('green');
print_r(wincache_ucache_info());
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
Array
( ["total_cache_uptime"] => int(0)
  ["is_local_cache"] => bool(false)
  ["total_item_count"] => int(1)
  ["total_hit_count"] => int(3)
  ["total_miss_count"] => int(1)
  ["ucache_entries"] => Array(1)
    ( [1] => Array(6)
      (
        ["key_name"] => string(5) "green"
        ["value_type"] => string(4) "long"
        ["is_session"] => int(0)
        ["ttl_seconds"] => int(0)
        ["age_seconds"] => int(0)
        ["hitcount"] => int(3)
       )
    )
)
]]>
    </screen>
   </example>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>wincache_fcache_meminfo</function></member>
    <member><function>wincache_ocache_fileinfo</function></member>
    <member><function>wincache_ocache_meminfo</function></member>
    <member><function>wincache_rplist_meminfo</function></member>
    <member><function>wincache_rplist_fileinfo</function></member>
    <member><function>wincache_refresh_if_changed</function></member>
    <member><function>wincache_ucache_meminfo</function></member>
    <member><function>wincache_scache_info</function></member>
    <member><function>wincache_scache_meminfo</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
export function encorchetar(frase: string){
    return "["+frase+"]";
}