text:
from __future__ import print_function
import sys, json, os, math, gzip, shutil, argparse, hashlib

from paraview import simple
from paraview.vtk import *
import sys

if sys.version_info[0] == 3:
    buffer = memoryview

# -----------------------------------------------------------------------------

arrayTypesMapping = '  bBhHiIlLfdL' # last one is idtype

jsMapping = {
    'b': 'Int8Array',
    'B': 'Uint8Array',
    'h': 'Int16Array',
    'H': 'Uint16Array',
    'i': 'Int32Array',
    'I': 'Uint32Array',
    'l': 'Int32Array',
    'L': 'Uint32Array',
    'f': 'Float32Array',
    'd': 'Float64Array'
}

writerMapping = {}

# -----------------------------------------------------------------------------

def getRangeInfo(array, component):
  r = array.GetRange(component)
  compRange = {}
  compRange['min'] = r[0]
  compRange['max'] = r[1]
  compRange['component'] = array.GetComponentName(component)
  return compRange

# -----------------------------------------------------------------------------

def getRef(destDirectory, md5):
  ref = {}
  ref['id'] = md5
  ref['encode'] = 'BigEndian' if sys.byteorder == 'big' else 'LittleEndian'
  ref['basepath'] = destDirectory
  return ref

# -----------------------------------------------------------------------------

def dumpStringArray(datasetDir, dataDir, array, root = {}, compress = True):
  if not array:
    return None

  stringArray = []
  arraySize = array.GetNumberOfTuples()
  for i in range(arraySize):
    stringArray.append(array.GetValue(i))

  strData = json.dumps(stringArray)

  pMd5 = hashlib.md5(strData).hexdigest()
  pPath = os.path.join(dataDir, pMd5)
  with open(pPath, 'wb') as f:
    f.write(strData)

  if compress:
    with open(pPath, 'rb') as f_in, gzip.open(os.path.join(dataDir, pMd5 + '.gz'), 'wb') as f_out:
      shutil.copyfileobj(f_in, f_out)
      f_in.close()
      os.remove(pPath)

  root['ref'] = getRef(os.path.relpath(dataDir, datasetDir), pMd5)
  root['vtkClass'] = 'vtkStringArray'
  root['name'] = array.GetName()
  root['dataType'] = 'JSON'
  root['numberOfComponents'] = array.GetNumberOfComponents()
  root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()

  return root

# -----------------------------------------------------------------------------

def dumpDataArray(datasetDir, dataDir, array, root = {}, compress = True):
  if not array:
    return None

  if array.GetDataType() == 12:
    # IdType need to be converted to Uint32
    arraySize = array.GetNumberOfTuples() * array.GetNumberOfComponents()
    newArray = vtkTypeUInt32Array()
    newArray.SetNumberOfTuples(arraySize)
    for i in range(arraySize):
      newArray.SetValue(i, -1 if array.GetValue(i) < 0 else array.GetValue(i))
    pBuffer = buffer(newArray)
  else:
    pBuffer = buffer(array)

  pMd5 = hashlib.md5(pBuffer).hexdigest()
  pPath = os.path.join(dataDir, pMd5)
  with open(pPath, 'wb') as f:
    f.write(pBuffer)

  if compress:
    with open(pPath, 'rb') as f_in, gzip.open(os.path.join(dataDir, pMd5 + '.gz'), 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)
        f_in.close()
        os.remove(pPath)

  # print array
  # print array.GetName(), '=>', jsMapping[arrayTypesMapping[array.GetDataType()]]

  root['ref'] = getRef(os.path.relpath(dataDir, datasetDir), pMd5)
  root['vtkClass'] = 'vtkDataArray'
  root['name'] = array.GetName()
  root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
  root['numberOfComponents'] = array.GetNumberOfComponents()
  root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
  root['ranges'] = []
  if root['numberOfComponents'] > 1:
    for i in range(root['numberOfComponents']):
      root['ranges'].append(getRangeInfo(array, i))
    root['ranges'].append(getRangeInfo(array, -1))
  else:
    root['ranges'].append(getRangeInfo(array, 0))

  return root

# -----------------------------------------------------------------------------

def dumpAttributes(datasetDir, dataDir, dataset, root = {}, compress = True):
  # PointData
  _pointData = root['pointData'] = { "vtkClass": "vtkDataSetAttributes", "arrays": [] }
  _nbFields = dataset.GetPointData().GetNumberOfArrays()
  for i in range(_nbFields):
    array = dataset.GetPointData().GetArray(i)
    abstractArray = dataset.GetPointData().GetAbstractArray(i)
    if array:
      _array = dumpDataArray(datasetDir, dataDir, array, {}, compress)
      if _array:
        if (root['vtkClass'] == 'vtkImageData'):
          _array['ref']['registration']="setScalars"

        _pointData['arrays'].append({ "data": _array })
    elif abstractArray:
      _array = dumpStringArray(datasetDir, dataDir, abstractArray, {}, compress)
      if _array:
        _pointData['arrays'].append({ "data": _array })

  # CellData
  _cellData = root['cellData'] = { "vtkClass": "vtkDataSetAttributes", "arrays": [] }
  _nbFields = dataset.GetCellData().GetNumberOfArrays()
  for i in range(_nbFields):
    array = dataset.GetCellData().GetArray(i)
    abstractArray = dataset.GetCellData().GetAbstractArray(i)
    if array:
      _array = dumpDataArray(datasetDir, dataDir, array, {}, compress)
      if _array:
        _cellData['arrays'].append({ "data": _array })
    elif abstractArray:
      _array = dumpStringArray(datasetDir, dataDir, abstractArray, {}, compress)
      if _array:
        _cellData['arrays'].append({ "data": _array })

  # FieldData
  _fieldData = root['FieldData'] = { "vtkClass": "vtkDataSetAttributes", "arrays": [] }
  _nbFields = dataset.GetFieldData().GetNumberOfArrays()
  for i in range(_nbFields):
    array = dataset.GetFieldData().GetArray(i)
    abstractArray = dataset.GetFieldData().GetAbstractArray(i)
    if array:
      _array = dumpDataArray(datasetDir, dataDir, array, {}, compress)
      if _array:
        _fieldData['arrays'].append({ "data": _array })
    elif abstractArray:
      _array = dumpStringArray(datasetDir, dataDir, abstractArray, {}, compress)
      if _array:
        _fieldData['arrays'].append({ "data": _array })
  return root

# -----------------------------------------------------------------------------

def dumpPolyData(datasetDir, dataDir, dataset, container = {}, compress = True):
  container['vtkClass'] = 'vtkPolyData'

  # Points
  points = dumpDataArray(datasetDir, dataDir, dataset.GetPoints().GetData(), {}, compress)
  container['points'] = points
  container['points']['vtkClass'] = 'vtkPoints'
  container['points']['numberOfComponents'] = 3

  # Cells
  _cells = container

  ## Verts
  if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
    _verts = dumpDataArray(datasetDir, dataDir, dataset.GetVerts().GetData(), {}, compress)
    _verts['name'] = '_verts'
    _cells['verts'] = _verts
    _cells['verts']['vtkClass'] = 'vtkCellArray'

  ## Lines
  if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
    _lines = dumpDataArray(datasetDir, dataDir, dataset.GetLines().GetData(), {}, compress)
    _lines['name'] = '_lines'
    _cells['lines'] = _lines
    _cells['lines']['vtkClass'] = 'vtkCellArray'

  ## Polys
  if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
    _polys = dumpDataArray(datasetDir, dataDir, dataset.GetPolys().GetData(), {}, compress)
    _polys['name'] = '_polys'
    _cells['polys'] = _polys
    _cells['polys']['vtkClass'] = 'vtkCellArray'

  ## Strips
  if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
    _strips = dumpDataArray(datasetDir, dataDir, dataset.GetStrips().GetData(), {}, compress)
    _strips['name'] = '_strips'
    _cells['strips'] = _strips
    _cells['strips']['vtkClass'] = 'vtkCellArray'

  # Attributes (PointData, CellData, FieldData)
  dumpAttributes(datasetDir, dataDir, dataset, container, compress)

  return container

# -----------------------------------------------------------------------------
writerMapping['vtkPolyData'] = dumpPolyData
# -----------------------------------------------------------------------------

def dumpUnstructuredGrid(datasetDir, dataDir, dataset, container = {}, compress = True):
  container['vtkClass'] = 'vtkUnstructuredGrid'

  # Points
  points = dumpDataArray(datasetDir, dataDir, dataset.GetPoints().GetData(), {}, compress)
  points['name'] = '_points'
  container['points'] = points
  container['points']['vtkClass'] = 'vtkPoints'

  # Cells
  container['cells'] = dumpDataArray(datasetDir, dataDir, dataset.GetCells().GetData(), {}, compress)
  container['cells']['vtkClass'] = 'vtkCellArray'

  # CellTypes
  container['cellTypes'] = dumpDataArray(datasetDir, dataDir, dataset.GetCellTypesArray(), {}, compress)

  # Attributes (PointData, CellData, FieldData)
  dumpAttributes(datasetDir, dataDir, dataset, container, compress)

  return container

# -----------------------------------------------------------------------------
writerMapping['vtkUnstructuredGrid'] = dumpUnstructuredGrid
# -----------------------------------------------------------------------------

def dumpImageData(datasetDir, dataDir, dataset, container = {}, compress = True):
  container['vtkClass'] = 'vtkImageData'

  # Origin / Spacing / Dimension
  container['origin'] = tuple(dataset.GetOrigin())
  container['spacing'] = tuple(dataset.GetSpacing())
  container['extent'] = tuple(dataset.GetExtent())

  # Attributes (PointData, CellData, FieldData)
  dumpAttributes(datasetDir, dataDir, dataset, container, compress)

  return container

# -----------------------------------------------------------------------------
writerMapping['vtkImageData'] = dumpImageData
# -----------------------------------------------------------------------------

def dumpRectilinearGrid(datasetDir, dataDir, dataset, container = {}, compress = True):
  container['vtkClass'] = 'vtkRectilinearGrid'

  # Dimensions
  container['dimensions'] = tuple(dataset.GetDimensions())

  # X, Y, Z
  container['xCoordinates'] = dumpDataArray(datasetDir, dataDir, dataset.GetXCoordinates(), {}, compress)
  container['yCoordinates'] = dumpDataArray(datasetDir, dataDir, dataset.GetYCoordinates(), {}, compress)
  container['zCoordinates'] = dumpDataArray(datasetDir, dataDir, dataset.GetZCoordinates(), {}, compress)

  # Attributes (PointData, CellData, FieldData)
  dumpAttributes(datasetDir, dataDir, dataset, container, compress)

  return container

# -----------------------------------------------------------------------------
writerMapping['vtkRectilinearGrid'] = dumpRectilinearGrid
# -----------------------------------------------------------------------------

def dumpTable(datasetDir, dataDir, dataset, container = {}, compress = True):
  container['vtkClass'] = 'vtkTable'

  # Columns
  _columns = container['Columns'] = {}
  _nbFields = dataset.GetNumberOfColumns()
  for i in range(_nbFields):
    array = dumpDataArray(datasetDir, dataDir, dataset.GetColumn(i), {}, compress)
    if array:
      _columns[array['name']] = array

  return container

# -----------------------------------------------------------------------------
writerMapping['vtkTable'] = dumpTable
# -----------------------------------------------------------------------------

def dumpMultiBlock(datasetDir, dataDir, dataset, container = {}, compress = True):
  container['vtkClass'] = 'vtkMultiBlock'

  _blocks = container['Blocks'] = {}
  _nbBlocks = dataset.GetNumberOfBlocks()
  for i in range(_nbBlocks):
    name = dataset.GetMetaData(i).Get(vtkCompositeDataSet.NAME())
    blockDataset = dataset.GetBlock(i)
    if blockDataset:
      writer = writerMapping[blockDataset.GetClassName()]
      if writer:
        _blocks[name] = writer(datasetDir, dataDir, blockDataset, {}, compress)
      else:
        _blocks[name] = blockDataset.GetClassName()

  return container

# -----------------------------------------------------------------------------
writerMapping['vtkMultiBlockDataSet'] = dumpMultiBlock
# -----------------------------------------------------------------------------

def writeDataSet(filePath, dataset, outputDir, newDSName = None, compress = True):
  fileName = newDSName if newDSName else os.path.basename(filePath)
  datasetDir = os.path.join(outputDir, fileName)
  dataDir = os.path.join(datasetDir, 'data')

  if not os.path.exists(dataDir):
    os.makedirs(dataDir)

  root = {}
  root['metadata'] = {}
  root['metadata']['name'] = fileName

  writer = writerMapping[dataset.GetClassName()]
  if writer:
    writer(datasetDir, dataDir, dataset, root, compress)
  else:
    print (dataObject.GetClassName(), 'is not supported')

  with open(os.path.join(datasetDir, "index.json"), 'w') as f:
    f.write(json.dumps(root, indent=2))

# -----------------------------------------------------------------------------

def writeTimeDataSource(filePath, datasource, sourceToExport, outputDir, newDSName = None, compress = True):
  fileName = newDSName if newDSName else os.path.basename(filePath)
  datasetDir = os.path.join(outputDir, fileName)
  dataDir = os.path.join(datasetDir, 'data')

  if not os.path.exists(dataDir):
    os.makedirs(dataDir)

  root = {}
  root['metadata'] = {}
  root['metadata']['name'] = fileName
  root['type'] = 'Parametric'
  container = root['Parametric'] = {}
  _params = container['parameters'] = { 'time': [ '%02d' % idx for idx in range(len(datasource.TimestepValues))] }
  _refs = container['refs'] = { 'dataset': { 'id': '{time}/index.json', 'pattern': True, 'basepath': '', 'encode': 'JSON' } }

  for idx in range(len(datasource.TimestepValues)):
    t = datasource.TimestepValues[idx]
    sourceToExport.UpdatePipeline(t)
    ds = sourceToExport.GetClientSideObject().GetOutputDataObject(0)
    writer = writerMapping[ds.GetClassName()]
    if writer:
      dsDir = os.path.join(datasetDir, "%02d" % idx)
      dsFileName = os.path.join(dsDir, "index.json")
      if not os.path.exists(dsDir):
        os.makedirs(dsDir)
      with open(dsFileName, 'w') as f:
        f.write(json.dumps(writer(dsDir, dataDir, ds, {}, compress), indent=2))
    else:
      print (dataObject.GetClassName(), 'is not supported')

  with open(os.path.join(datasetDir, "index.json"), 'w') as f:
    f.write(json.dumps(root, indent=2))

# -----------------------------------------------------------------------------

def convert(inputFile, outputDir, merge = False, extract = False, newName = None):
  print (inputFile, outputDir)
  reader = simple.OpenDataFile(inputFile)
  activeSource = reader

  if merge:
    activeSource = simple.MergeBlocks(activeSource)

  if extract:
    activeSource = simple.ExtractSurface(activeSource)

  activeSource.UpdatePipeline()
  dataObject = activeSource.GetClientSideObject().GetOutputDataObject(0)

  if 'TimestepValues' in reader.ListProperties():
    if len(reader.TimestepValues) == 0:
      writeDataSet(inputFile, dataObject, outputDir, newName)
    else:
      writeTimeDataSource(inputFile, reader, activeSource, outputDir, newName)
  else:
    writeDataSet(inputFile, dataObject, outputDir, newName)

# -----------------------------------------------------------------------------

def sample(dataDir, outputDir):
  convert(os.path.join(dataDir, 'Data/bot2.wrl'), outputDir, True, True)
  convert(os.path.join(dataDir, 'Data/can.ex2'), outputDir)
  convert(os.path.join(dataDir, 'Data/can.ex2'), outputDir, True, True, 'can_MS.ex2')
  convert(os.path.join(dataDir, 'Data/can.ex2'), outputDir, True, False, 'can_M.ex2')
  convert(os.path.join(dataDir, 'Data/can.ex2'), outputDir, False, True, 'can_S.ex2')
  convert(os.path.join(dataDir, 'Data/disk_out_ref.ex2'), outputDir, True, False, 'disk_out_ref_M.ex2')
  convert(os.path.join(dataDir, 'Data/disk_out_ref.ex2'), outputDir)
  convert(os.path.join(dataDir, 'Data/RectGrid2.vtk'), outputDir)

  # Create image data based on the Wavelet source
  wavelet = simple.Wavelet()
  wavelet.UpdatePipeline()
  imageData = wavelet.GetClientSideObject().GetOutputDataObject(0)
  writeDataSet('Wavelet.vti', imageData, outputDir)

  # Create a table based on the disk_out_ref
  diskout = simple.ExtractSurface(simple.MergeBlocks(simple.OpenDataFile(os.path.join(dataDir, 'Data/disk_out_ref.ex2'))))
  diskout.UpdatePipeline()
  unstructuredGrid = diskout.GetClientSideObject().GetOutputDataObject(0)
  table = vtkTable()
  _nbFields = unstructuredGrid.GetPointData().GetNumberOfArrays()
  for i in range(_nbFields):
    table.AddColumn(unstructuredGrid.GetPointData().GetArray(i))
  writeDataSet('table', table, outputDir)

# =============================================================================
# Main: Parse args and start data conversion
# =============================================================================

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Data conversion")
    parser.add_argument("--input", help="path to the file to convert", dest="input")
    parser.add_argument("--output", help="path to the directory where to write the output", dest="output")
    parser.add_argument("--merge", help="Merge multiblock into single dataset", default=False, action='store_true', dest="merge")
    parser.add_argument("--extract-surface", help="Extract surface mesh", default=False, action='store_true', dest="extract")
    parser.add_argument("--sample-data", help="Generate sample data from ParaView Data", dest="sample")

    args = parser.parse_args()

    if args.sample:
      sample(args.sample, args.output)
    else:
      convert(args.input, args.output, args.merge, args.extract)


text:
using System;
using System.Collections.Generic;
using QuantConnect.Optimizer.Objectives;
using QuantConnect.Optimizer.Parameters;

namespace QuantConnect.Optimizer.Strategies
{
    /// <summary>
    /// Defines the optimization settings, direction, solution and exit, i.e. optimization strategy
    /// </summary>
    public interface IOptimizationStrategy
    {
        /// <summary>
        /// Fires when new parameter set is retrieved
        /// </summary>
        event EventHandler<ParameterSet> NewParameterSet;

        /// <summary>
        /// Best found solution, its value and parameter set
        /// </summary>
        OptimizationResult Solution { get; }

        /// <summary>
        /// Initializes the strategy using generator, extremum settings and optimization parameters
        /// </summary>
        /// <param name="target">The optimization target</param>
        /// <param name="constraints">The optimization constraints to apply on backtest results</param>
        /// <param name="parameters">optimization parameters</param>
        /// <param name="settings">optimization strategy advanced settings</param>
        void Initialize(Target target, IReadOnlyList<Constraint> constraints, HashSet<OptimizationParameter> parameters, OptimizationStrategySettings settings);

        /// <summary>
        /// Callback when lean compute job completed.
        /// </summary>
        /// <param name="result">Lean compute job result and corresponding parameter set</param>
        void PushNewResults(OptimizationResult result);

        /// <summary>
        /// Estimates amount of parameter sets that can be run
        /// </summary>
        int GetTotalBacktestEstimate();
    }
}

redpajama_set_name: RedPajamaGithub


text:
Prank v0.75 - Common Sense PHP Framework
========================================

Prank is a YAPF - Yet Another [PHP][] Framework

Prank tries to utilize the common sense approach to web application design.
It's in alpha stage, and is only fit for experimentation.

Prank is build around [PHP5.4][] (which is required) and is tested on
Apache 2.2 and MySQL 5.0.

[PHP]:    http://php.net/                        "PHP"
[PHP5.4]: http://php.net/migration54.changes.php "What has changed in PHP 5.4"

Philosophy
----------

Prank's design supports the development of web applications more advanced than
simple dynamic sites. Many of used concepts and solutions are far from being
efficient (although I try to make them as scalable as possible) – they are
meant to make the prototyping as fast as possible, and heighten programmer
enjoyment.

If you want your PHP to scale and use as few resources as possible, don't use a
framework.

Prank is also a highly opinionated software - I'm not trying to please
everybody, or even please myself in full. In all events, Prank is meant to take
the most sane and common-sense way of doing things.

Design Goals
------------

*  Code should be *nice*. This framework is not intended for anybody enjoying
   large XML files and extremely long method calls.

*  Object Oriented design as basis of functionality, functions as syntax sugar
   and helpers for common tasks. There's nothing wrong with sugar.

*  Clever use of Closures and smart static methods when applicable.

Usage
=====

This is an ongoing experiment, and it is in continuous alpha stage, so use at
your own risk. There's no use of writing a proper usage document at the moment,
as things change frequently around here. However, Most of the code is pretty
self-explanatory. Take look at the provided /app/ directory, to see how to
create your own test-apps. If you have comments or suggestions, contact me
through [brego][].

Enjoy ;)

[brego]: mailto:brego.dk@gmail.com

Credits
=======

Prank uses a modified version of the CakePHP's [Inflector class][] licensed
under The MIT License - all credit goes to it's authors and the
[Cake Software Foundation][], Inc.

Huge thanks to Larry E. Masters aka [phpnut][], Michal Tatarynowicz aka
[pies][] and the rest of the original CakePHP comunity for inspiration.

[Inflector class]:          https://github.com/cakephp/cakephp/blob/master/src/Utility/Inflector.php
[Cake Software Foundation]: http://cakefoundation.org
[phpnut]:                   https://github.com/phpnut
[pies]:                     https://github.com/pies


text:
package com.acenosekai.antplayer.models;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Acenosekai on 1/17/2016.
 * Rock On
 */
public class Folder {
    private String name;
    private String path;
    private List<Folder> childs = new ArrayList<>();
    private Folder parent;
    private boolean directory;

    public Folder getParent() {
        return parent;
    }

    public void setParent(Folder parrent) {
        this.parent = parrent;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public List<Folder> getChilds() {
        return childs;
    }

    public void setChilds(List<Folder> childs) {
        this.childs = childs;
    }

    public boolean isDirectory() {
        return directory;
    }

    public void setDirectory(boolean directory) {
        this.directory = directory;
    }
}


text:
@interface WMFNearbyPlaceholderTableViewCell : SSBaseTableCell

@property (strong, nonatomic) IBOutlet UIImageView *placeholderImageView;

@end


text:
CHECKPOINT_DISABLE ?= 1
all: debian

cuckoo:
	make validate-cuckoo
	packer build -var-file=debian-vars.jsondebian-cuckoo.json

debian:
	make validate-debian
	packer build -var-file=debian-vars.json debian.json

debug-cuckoo:
	make validate-cuckoo
	packer build -on-error=abort -var-file=debian-vars.json debian-cuckoo.json

debian-chrome:
	make validate-debian-chrome
	packer build -var-file=debian-vars.json debian-chrome.json

validate-cuckoo:
	packer validate -var-file=debian-vars.json debian-cuckoo.json

validate-debian:
	packer validate -var-file=debian-vars.json debian.json

validate-debian-chrome:
	packer validate -var-file=debian-vars.json debian-chrome.json

install:
	../bin/install.sh

clean:
	rm -rf Debian_Cuckoo_64-bit.vmwarevm
	rm -rf Debian_64-bit.vmwarevm
	rm -rf Debian_11_64-bit.vmwarevm
	rm -rf Debian_11_chrome-bit.vmwarevm

dist-clean:
	make clean
	rm -rf packer_cache


text:
package com.twitter.zipkin.common

import com.twitter.zipkin.gen
import scala.collection.JavaConversions._
import scala.collection.Map
import java.nio.ByteBuffer

/**
 * A span represents one RPC request. A trace is made up of many spans.
 *
 * A span can contain multiple annotations, some are always incuded such as
 * Client send -> Server received -> Server send -> Client receive.
 *
 * Some are created by users, describing application specific information,
 * such as cache hits/misses.
 */
object Span {

  def apply(span: Span): Span = Span(span.traceId, span.name, span.id,
    span.parentId, span.annotations, span.binaryAnnotations)

  def fromThrift(span: gen.Span): Span = {
    span.`name` match {
      case null => throw new IncompleteTraceDataException("No name set in Span")
      case _ => ()
    }

    val annotations = span.annotations match {
      case null => List[Annotation]()
      case as => as.map { annotation => Annotation.fromThrift(annotation) }.toList
    }

    val binaryAnnotations = span.binaryAnnotations match {
      case null => Seq[gen.BinaryAnnotation]()
      case b => b
    }

    new Span(span.traceId, span.name, span.id, span.parentId, annotations, binaryAnnotations)
  }

}

/**
 * @param traceId random long that identifies the trace, will be set in all spans in this trace
 * @param name name of span, can be rpc method name for example
 * @param id random long that identifies this span
 * @param parentId reference to the parent span in the trace tree
 * @param annotations annotations, containing a timestamp and some value. both user generated and
 * some fixed ones from the tracing framework
 * @param binaryAnnotations  binary annotations, can contain more detailed information such as
 * serialized objects
 */
case class Span(traceId: Long, name: String, id: Long, parentId: Option[Long],
                 annotations: List[Annotation], binaryAnnotations: Seq[gen.BinaryAnnotation]) {
  /**
   * Order annotations by timestamp.
   */
  val timestampOrdering = new Ordering[Annotation] {
      def compare(a: Annotation, b: Annotation) = {a.timestamp.compare(b.timestamp)}
  }

  def toThrift: gen.Span = {
    gen.Span(traceId, name, id, parentId, annotations.map(a => a.toThrift),
      binaryAnnotations)
  }

  def serviceNames: Set[String] = {
    annotations.flatMap(a => a.host.map(h => h.serviceName.toLowerCase)).toSet
  }

  /**
   * Tries to extract the best possible service name
   */
  def serviceName: Option[String] = {
    if (annotations.isEmpty) {
      None
    } else {
      val sName = serverSideAnnotations.flatMap(_.host).headOption.map(_.serviceName)
      val cName = clientSideAnnotations.flatMap(_.host).headOption.map(_.serviceName)
      sName match {
        case Some(s) => Some(s)
        case None => cName
      }
    }
  }

  /**
   * Iterate through list of annotations and return the one with the given value.
   */
  def getAnnotation(value: String): Option[Annotation] = {
    annotations.find {a => a.value == value}
  }

  /**
   * Take two spans with the same span id and merge all data into one of them.
   */
  def mergeSpan(mergeFrom: Span): Span = {
    if (id != mergeFrom.id) {
      throw new IllegalArgumentException("Span ids must match")
    }

    // ruby tracing can give us an empty name in one part of the span
    val selectedName = name match {
      case "" => mergeFrom.name
      case "Unknown" => mergeFrom.name
      case _ => name
    }

    new Span(traceId, selectedName, id, parentId,
      annotations ++ mergeFrom.annotations,
      binaryAnnotations ++ mergeFrom.binaryAnnotations)
  }

  /**
   * Get the first annotation by timestamp.
   */
  def firstAnnotation: Option[Annotation] = {
    try {
      Some(annotations.min(timestampOrdering))
    } catch {
      case e: UnsupportedOperationException => None
    }
  }

  /**
   * Get the last annotation by timestamp.
   */
  def lastAnnotation: Option[Annotation] = {
    try {
      Some(annotations.max(timestampOrdering))
    } catch {
      case e: UnsupportedOperationException => None
    }
  }

  /**
   * Endpoints involved in this span
   */
  def endpoints: Set[Endpoint] = {
    annotations.flatMap(a => a.host).toSet
  }

  /**
   * Assuming this is an RPC span, is it from the client side?
   */
  def isClientSide(): Boolean = {
    annotations.exists(a => {
      a.value.equals(gen.Constants.CLIENT_SEND) || a.value.equals(gen.Constants.CLIENT_RECV)
    })
  }

  /**
   * Pick out the core client side annotations
   */
  def clientSideAnnotations: Seq[Annotation] = {
    annotations.filter(a => Annotation.CoreClient.contains(a.value))
  }

  /**
   * Pick out the core server side annotations
   */
  def serverSideAnnotations: Seq[Annotation] = {
    annotations.filter(a => Annotation.CoreServer.contains(a.value))
  }

  /**
   * Duration of this span. May be None if we cannot find any annotations.
   */
  def duration: Option[Long] = {
    for (first <- firstAnnotation; last <- lastAnnotation)
      yield last.timestamp - first.timestamp
  }

  /**
   * @return true  if Span contains at most one of each core annotation
   *         false otherwise
   */
  def isValid: Boolean = {
    Annotation.CoreAnnotations.map { c =>
      annotations.filter { _.value == c }.length > 1
    }.count {b => b} == 0
  }

  /**
   * Get the annotations as a map with value to annotation bindings.
   */
  def getAnnotationsAsMap(): Map[String, Annotation] = annotations.map{ a => a.value -> a}.toMap
}


text:
<?php

ERROR_REPORTING(E_ALL);
ini_set('display_errors', 1);
include "vendor/autoload.php";

use Slim\Slim;
use Emeka\Candy\Model\BaseModel;
use Emeka\SweetEmoji\Model\User;
use Emeka\SweetEmoji\Model\Emoji;
use Emeka\SweetEmoji\Auth\Config;
use Emeka\SweetEmoji\Controller\AuthController;
use Emeka\SweetEmoji\Middleware\AuthMiddleware;
use Emeka\SweetEmoji\Controller\UserController;
use Emeka\SweetEmoji\Controller\EmojiController;

$app 				= new Slim;
$authController     = new AuthController($app);
$authMiddleware     = new AuthMiddleware($app);
$userController    	= new UserController($app);
$emojiController    = new EmojiController($app);

$authenticated = function () use ($authMiddleware){
    $authMiddleware->authenticate();
};

/*
| Welcome page
*/
$app->get('/', function () use ($emojiController){
    //echo "Welcome to SweetEmoji";
    $emojiController->all();

});

/*
| "/emojis" get all emoji from the database
*/
$app->get('/emojis', function () use ($emojiController){
    $emojiController->all();
});

/*
| "/emojis" create new emoji
*/
$app->put('/emojis', $authenticated, function () use ($emojiController){
    $emojiController->addEmoji();
});

/*
| "/emojis" update emoji
*/
$app->patch('/emojis/:id', $authenticated, function ($id) use ($emojiController){
    $emojiController->updateEmoji($id);
});

/*
| "/emojis" find an emoji by id
| POST method
*/
$app->get('/emojis/:id', function ($id) use ($emojiController){
    $emojiController->findEmoji($id);
});

/*
| "/emojis/:id" find and delete an emoji by id
| DELETE method
*/
$app->delete('/emojis/:id', function ($id) use ($emojiController){
    $emojiController->deleteEmoji($id);
});

/*
| login
*/
$app->post('/auth/login', function () use ($authController){
    $authController->login();
});

/*
| logout
*/
$app->post('/auth/logout', $authenticated, function () use ($authController){
    $authController->logout();
});

/*
| register
*/
$app->post('/auth/register', function () use ($userController){
    $userController->register();
});

$app->run();


text:
GET_FILENAME_COMPONENT( _EXTRACT_EXPORTS_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/ExtractExportsWorker.cmake" REALPATH )

# List exported symbols from static libs and put references to them in source
# file. The source file becomes target.
# Synopsis: EXTRACT_EXPORTS( <output source file name> <static lib 1> [<static lib 2> ...] )
# WARNING! this currently works only for MSVC toolchain!
FUNCTION( EXTRACT_EXPORTS OUT_REFERENCES_FILE )
	# get list of static lib files
	FOREACH( libname ${ARGN} )
		SET( LIB_FILES ${LIB_FILES} $<TARGET_FILE:${libname}> )
	ENDFOREACH()

	# extract dllexport'ed symbols from static libs
	ADD_CUSTOM_COMMAND( OUTPUT ${OUT_REFERENCES_FILE}
		COMMAND ${CMAKE_COMMAND} -D "IN_BINS:STRING=${LIB_FILES}" -D "OUT_FILE:STRING=${OUT_REFERENCES_FILE}" -P "${_EXTRACT_EXPORTS_SCRIPT}"
		DEPENDS ${ARGN} ${_EXTRACT_EXPORTS_SCRIPT}
		COMMENT "Listing exported symbols..."
		VERBATIM
	)
ENDFUNCTION()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=1024, user-scalable=no">
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <title>Bleeding Edge Web: June 2019</title>

    <link rel="stylesheet" href="../../shared/core/deck.core.css">

    <link rel="stylesheet" href="../../shared/extensions/goto/deck.goto.css">
    <link rel="stylesheet" href="../../shared/extensions/menu/deck.menu.css">
    <link rel="stylesheet" href="../../shared/extensions/navigation/deck.navigation.css">
    <link rel="stylesheet" href="../../shared/extensions/status/deck.status.css">
    <link rel="stylesheet" href="../../shared/extensions/hash/deck.hash.css">
    <link rel="stylesheet" href="../../shared/extensions/scale/deck.scale.css">

    <link rel="stylesheet" href="../../shared/themes/transition/fade.css">

    <link rel="stylesheet" href="../../shared/prism/prism-okaidia.css">

    <link rel="stylesheet" href="../../shared/themes/build/skew-dark.css">

Bleeding Edge Web

@edgeATX

edgeATX.org

Bleeding Edge Web: June 2019

News From the Bleeding Edge

— Corey Butler (@goldglovecb)

Real User Measurements and the Development Lifecycle

— Ken Harker

Housekeeping

Speakers and sponsors always wanted (edgeATX.org for details)

Don't forget your parking validation

Omni hotel bar (downstairs) after meetup

Thanks to
Our Sponsors

News from the
Bleeding Edge

Browser
Update

Browser Pop Quiz

Last check: April 18, 2019:

          74
          66
          18
          12.1

Browser Pop Quiz

As of May 16, 2019:

          74
75
          66
67
          18*
          12.1

Chrome 75

stale-while-revalidate - Removes stale assets from critical path.

Scroll Snap Stop

Firefox 67

Suspends "unused" tabs

Lowered priority of setTimeout

Block known cryptominers

Supports dynamic module imports import()

String.matchAll() support

Desktop notifications now restricted to TLS

Edge (Dev Channel)

First to use Chromium

Languages, Libraries &
Frameworks

npm

CLI 6.9.1 - no commits in 3mos (job cuts)

npm token support w/ Github (like Checksum)

Releases

HAProxy 2.0

WSL 2 (Docker for Windows): Full Linux Kernel

PIKA CDN

Node 12.4.0 (w/ JSON Module support)

In Case You
Missed It

Industry

Github/Microsoft acquires Pull Panda (Reminders, Analytics, & Assigners)

Facebook launches Libra Cryptocurrency

Mozilla Launching Paid Firefox (w/ VPN)

Entropic: Decentralized Package Registry

State of CSS 2019

.io & .sh in jeopardy?

UN Ruling May Put .io Domains at Risk

Dispute over the Chagos Archipelago (British or Mauritius)

Illegal decolonialization

Would make the registrar no longer part of the UK

Old news: but will the British accept the court ruling? Not yet.

On the
Lighter Side

<clippy>

      I've spoken to several people in Microsoft, and we all agree it is a good idea.

We looked through a number of great software projects (mostly from Microsoft) and found lots of inconsistencies in the way Clippy is presented and invoked.

...

Because users keep buying and using our products, I'm going to assume they all love Clippy as much as I do.

Google.oops

Thanks!

https://edgeATX.org/slides

Corey Butler (@goldglovecb)

    ←→

 /

    <form class="goto-form" action="." method="get">
      Go to slide:
      <input id="goto-slide" type="text" name="slidenum" list="goto-datalist">
      <datalist id="goto-datalist"></datalist>
      <input type="submit" value="Go">
    </form>
    #


text:
layout: post
date:	2006-07-07 14:22:00
title:  Our Victorian mindset...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Sorry, some amendments are in order.

I had written:

A friend of mine says that there are two "units" in a house for rent, but he and another friend (a young woman) will not be allowed to take the two units because of snoopy landlords and neighbours.

The amendment:

Actually, there is apparently no problem in their taking TWO units. The problem arises if they don't want to waste money on two units....they can't take one, that will outrage proprieties. Hypocrisy rules.

But my comments still stand:

In my ideal, everything-is-simple world:

a. If they  are not a "couple" , there can be no objection.

b. If they are, and want to live in or whatever else, that is their
...er...affair, and as long as they are paying the rent properly and are
keeping the premises well, what's the problem? How does the piece of paper
that the marriage certificate is, change anything, as far as the landlord and neighbours are
concerned? Have all those couples in the vicinity shown them their marriage certificates?

c. How do these assorted neighbours/landlords know that if  the young man  brings over
male friends, or the young woman  brings over female friends, that they are not
g/l?

d.. And if everyone was like this, how DO unmarried couples live together?
(And I can't believe that there are no unmarried couples living together in
Bangalore.) ( I *would* like an answer to this one.) Do they always pretend to be married? Is hypocrisy the order of the day?

To me, the presence or absence of a marriage certificate it has never made any difference at all to my interaction with a "couple"; it is
their relationship, and their commitment to each other. No marriage certificate can keep a crumbling marriage from falling apart, and no marriage certificate is necessary when the commitment between two people exist...and the whole thing is  nothing to do
with me.  If we can accept that with friends, why can't assorted landlords
and neighbours accept the way some unknown youngsters wish to live? I know a gay couple who have been together for more than 8 years now. I have the utmost respect for both of them and I think it is wonderful that in this cold harsh world they have found love.....

...But...I think that is the ideal world! We are still in Victorian times here, and so
proud to be that way, too....our uncles and brothers will molest young
nieces (and,sometimes, nephews)  in the privacy of their homes, but a young
man and young woman must necessarily be thinking of orgies if they want to
share the same address.....

Sad, but true. I asked Jasmeen Patheja of Blank Noise why they could not
also protest against the sexual harassment of women in private spaces as well as in public areas, but
apparently, that is out of their ambit....


text:
#include "paddle/fluid/platform/profiler/chrometracing_logger.h"

#include <cstdio>
#include <ctime>
#include <limits>
#include <regex>

#include "glog/logging.h"
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/profiler/event_node.h"
#include "paddle/fluid/platform/profiler/utils.h"

namespace paddle {
namespace platform {

static const char* kDefaultFilename = "pid_%s_time_%s.paddle_trace.json";

static std::string DefaultFileName() {
  auto pid = GetProcessId();
  return string_format(
      std::string(kDefaultFilename), pid, GetStringFormatLocalTime().c_str());
}

void ChromeTracingLogger::OpenFile() {
  output_file_stream_.open(filename_,
                           std::ofstream::out | std::ofstream::trunc);
  if (!output_file_stream_) {
    LOG(WARNING) << "Unable to open file for writing profiling data."
                 << std::endl;
  } else {
    LOG(INFO) << "writing profiling data to " << filename_ << std::endl;
  }
}

ChromeTracingLogger::ChromeTracingLogger(const std::string& filename) {
  filename_ = filename.empty() ? DefaultFileName() : filename;
  OpenFile();
  StartLog();
}

ChromeTracingLogger::ChromeTracingLogger(const char* filename_cstr) {
  std::string filename(filename_cstr);
  filename_ = filename.empty() ? DefaultFileName() : filename;
  OpenFile();
  StartLog();
}

ChromeTracingLogger::~ChromeTracingLogger() {
  EndLog();
  output_file_stream_.close();
}

void ChromeTracingLogger::LogNodeTrees(const NodeTrees& node_trees) {
  output_file_stream_ << std::string(
      R"JSON(
    "traceEvents": [
  )JSON");
  // log all nodes except root node, root node is a helper node.
  const std::map<uint64_t, std::vector<HostTraceEventNode*>>
      thread2host_event_nodes = node_trees.Traverse(true);
  // find the earliest time in current timeline
  start_time_ = std::numeric_limits<uint64_t>::max();
  for (auto it = thread2host_event_nodes.begin();
       it != thread2host_event_nodes.end();
       ++it) {
    if (it->second.begin() + 1 != it->second.end()) {
      if ((*(it->second.begin() + 1))->StartNs() < start_time_) {
        start_time_ = (*(it->second.begin() + 1))->StartNs();
      }
    } else {
      auto runtimenode =
          (*(it->second.begin()))->GetRuntimeTraceEventNodes().begin();
      if (runtimenode !=
          (*(it->second.begin()))->GetRuntimeTraceEventNodes().end()) {
        if ((*runtimenode)->StartNs() < start_time_) {
          start_time_ = (*runtimenode)->StartNs();
        }
      }
    }
  }

  for (auto it = thread2host_event_nodes.begin();
       it != thread2host_event_nodes.end();
       ++it) {
    for (auto hostnode = it->second.begin(); hostnode != it->second.end();
         ++hostnode) {
      if (hostnode != it->second.begin()) {  // skip root node
        (*hostnode)->LogMe(this);
      }
      for (auto runtimenode = (*hostnode)->GetRuntimeTraceEventNodes().begin();
           runtimenode != (*hostnode)->GetRuntimeTraceEventNodes().end();
           ++runtimenode) {
        (*runtimenode)->LogMe(this);
        for (auto devicenode =
                 (*runtimenode)->GetDeviceTraceEventNodes().begin();
             devicenode != (*runtimenode)->GetDeviceTraceEventNodes().end();
             ++devicenode) {
          (*devicenode)->LogMe(this);
        }
      }
      for (auto memnode = (*hostnode)->GetMemTraceEventNodes().begin();
           memnode != (*hostnode)->GetMemTraceEventNodes().end();
           ++memnode) {
        (*memnode)->LogMe(this);
      }
    }
  }
}

void ChromeTracingLogger::LogMemTraceEventNode(
    const MemTraceEventNode& mem_node) {
  if (!output_file_stream_) {
    return;
  }
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
    "name": "[memory]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld,
    "ph": "i", "cat": "%s",
    "args": {
      "place": "%s",
      "addr": "%llu",
      "increase_bytes": %lld,
      "current_allocated": %llu,
      "current_reserved": %llu,
      "peak_allocated": %llu,
      "peak_reserved": %llu
    }
  },
  )JSON"),
      mem_node.ProcessId(),
      mem_node.ThreadId(),
      nsToUs(mem_node.TimeStampNs()),
      StringTracerMemEventType(mem_node.Type()),
      mem_node.Place().c_str(),
      mem_node.Addr(),
      mem_node.IncreaseBytes(),
      mem_node.CurrentAllocated(),
      mem_node.CurrentReserved(),
      mem_node.PeakAllocated(),
      mem_node.PeakReserved());
  pid_tid_set_.insert({mem_node.ProcessId(), mem_node.ThreadId()});
}

void ChromeTracingLogger::LogHostTraceEventNode(
    const HostTraceEventNode& host_node) {
  if (!output_file_stream_) {
    return;
  }
  std::string dur_display;
  float dur = nsToMsFloat(host_node.Duration());
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
  std::map<std::string, std::vector<std::vector<int64_t>>> input_shapes;
  std::map<std::string, std::vector<std::string>> input_dtypes;
  std::string callstack;
  OperatorSupplementEventNode* op_supplement_node =
      host_node.GetOperatorSupplementEventNode();
  if (op_supplement_node != nullptr) {
    input_shapes = op_supplement_node->InputShapes();
    input_dtypes = op_supplement_node->Dtypes();
    callstack = op_supplement_node->CallStack();
    callstack = std::regex_replace(callstack, std::regex("\""), "\'");
    callstack = std::regex_replace(callstack, std::regex("\n"), "\\n");
  }
  switch (host_node.Type()) {
    case TracerEventType::ProfileStep:
    case TracerEventType::Forward:
    case TracerEventType::Backward:
    case TracerEventType::Dataloader:
    case TracerEventType::Optimization:
    case TracerEventType::PythonOp:
    case TracerEventType::PythonUserDefined:
      // cname value comes from tracing.js reservedColorsByName variable

      output_file_stream_ << string_format(
          std::string(
              R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(Python)",
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "thread_state_runnable",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us"
    }
  },
  )JSON"),
          host_node.Name().c_str(),
          dur_display.c_str(),
          host_node.ProcessId(),
          host_node.ThreadId(),
          nsToUs(host_node.StartNs()),
          nsToUsFloat(host_node.Duration()),
          StringTracerEventType(host_node.Type()),
          nsToUsFloat(host_node.StartNs(), start_time_),
          nsToUsFloat(host_node.EndNs(), start_time_));
      break;

    case TracerEventType::Operator:

      output_file_stream_ << string_format(
          std::string(
              R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "thread_state_runnable",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us",
      "input_shapes": %s,
      "input_dtypes": %s,
      "callstack": "%s"
    }
  },
  )JSON"),
          host_node.Name().c_str(),
          dur_display.c_str(),
          host_node.ProcessId(),
          host_node.ThreadId(),
          nsToUs(host_node.StartNs()),
          nsToUsFloat(host_node.Duration()),
          StringTracerEventType(host_node.Type()),
          nsToUsFloat(host_node.StartNs(), start_time_),
          nsToUsFloat(host_node.EndNs(), start_time_),
          json_dict(input_shapes).c_str(),
          json_dict(input_dtypes).c_str(),
          callstack.c_str());
      break;
    case TracerEventType::CudaRuntime:
    case TracerEventType::Kernel:
    case TracerEventType::Memcpy:
    case TracerEventType::Memset:
    case TracerEventType::UserDefined:
    case TracerEventType::OperatorInner:
    case TracerEventType::Communication:
    case TracerEventType::MluRuntime:
    case TracerEventType::NumTypes:
    default:
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "thread_state_runnable",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us"
    }
  },
  )JSON"),
          host_node.Name().c_str(),
          dur_display.c_str(),
          host_node.ProcessId(),
          host_node.ThreadId(),
          nsToUs(host_node.StartNs()),
          nsToUsFloat(host_node.Duration()),
          StringTracerEventType(host_node.Type()),
          nsToUsFloat(host_node.StartNs(), start_time_),
          nsToUsFloat(host_node.EndNs(), start_time_));
      break;
  }

  pid_tid_set_.insert({host_node.ProcessId(), host_node.ThreadId()});
}

void ChromeTracingLogger::LogRuntimeTraceEventNode(
    const CudaRuntimeTraceEventNode& runtime_node) {
  if (!output_file_stream_) {
    return;
  }
  float dur = nsToMsFloat(runtime_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "thread_state_running",
    "args": {
      "correlation id": %d,
      "start_time": "%.3f us",
      "end_time": "%.3f us"
    }
  },
  )JSON"),
      runtime_node.Name().c_str(),
      dur_display.c_str(),
      runtime_node.ProcessId(),
      runtime_node.ThreadId(),
      nsToUs(runtime_node.StartNs()),
      nsToUsFloat(runtime_node.Duration()),
      StringTracerEventType(runtime_node.Type()),
      runtime_node.CorrelationId(),
      nsToUsFloat(runtime_node.StartNs(), start_time_),
      nsToUsFloat(runtime_node.EndNs(), start_time_));
  pid_tid_set_.insert({runtime_node.ProcessId(), runtime_node.ThreadId()});

  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
    "name": "launch", "id": %d, "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld,
    "ph": "s", "cat": "async"
  },
  )JSON"),
      runtime_node.CorrelationId(),
      runtime_node.ProcessId(),
      runtime_node.ThreadId(),
      nsToUs((runtime_node.StartNs() + runtime_node.EndNs()) >> 1));
  pid_tid_set_.insert({runtime_node.ProcessId(), runtime_node.ThreadId()});
}

void ChromeTracingLogger::LogDeviceTraceEventNode(
    const DeviceTraceEventNode& device_node) {
  if (!output_file_stream_) {
    return;
  }

  switch (device_node.Type()) {
    case TracerEventType::Kernel:
      HandleTypeKernel(device_node);
      break;
    case TracerEventType::Memcpy:
      HandleTypeMemcpy(device_node);
      break;
    case TracerEventType::Memset:
      HandleTypeMemset(device_node);
    default:
      break;
  }
  if (nsToUs(device_node.Duration()) == 0) {
    output_file_stream_ << string_format(std::string(
                                             R"JSON(
  {
    "name": "launch", "id": %d, "pid": %lld, "tid": %lld,
    "ts": %lld,
    "ph": "f", "cat": "async"
  },
  )JSON"),
                                         device_node.CorrelationId(),
                                         device_node.DeviceId(),
                                         device_node.StreamId(),
                                         nsToUs(device_node.StartNs()));
    deviceid_streamid_set_.insert(
        {device_node.DeviceId(), device_node.StreamId()});
  } else {
    output_file_stream_ << string_format(
        std::string(
            R"JSON(
  {
    "name": "launch", "id": %d, "pid": %lld, "tid": %lld,
    "ts": %lld,
    "ph": "f", "cat": "async", "bp": "e"
  },
  )JSON"),
        device_node.CorrelationId(),
        device_node.DeviceId(),
        device_node.StreamId(),
        nsToUs((device_node.StartNs() + device_node.EndNs()) >> 1));
    deviceid_streamid_set_.insert(
        {device_node.DeviceId(), device_node.StreamId()});
  }
}

void ChromeTracingLogger::HandleTypeKernel(
    const DeviceTraceEventNode& device_node) {
  KernelEventInfo kernel_info = device_node.KernelInfo();

  float dur = nsToMsFloat(device_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": %lld,
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "cq_build_failed",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us",
      "device": %d, "context": %d,
      "stream": %d, "correlation id": %d,
      "registers per thread": %d,
      "shared memory": %d,
      "blocks per SM": %f,
      "warps per SM": %f,
      "grid": [%d, %d, %d],
      "block": [%d, %d, %d],
      "theoretical achieved occupancy %%": %.3f
    }
  },
  )JSON"),
      device_node.Name().c_str(),
      dur_display.c_str(),
      device_node.DeviceId(),
      device_node.StreamId(),
      nsToUs(device_node.StartNs()),
      nsToUsFloat(device_node.Duration()),
      StringTracerEventType(device_node.Type()),
      nsToUsFloat(device_node.StartNs(), start_time_),
      nsToUsFloat(device_node.EndNs(), start_time_),
      device_node.DeviceId(),
      device_node.ContextId(),
      device_node.StreamId(),
      device_node.CorrelationId(),
      kernel_info.registers_per_thread,
      kernel_info.static_shared_memory + kernel_info.dynamic_shared_memory,
      kernel_info.blocks_per_sm,
      kernel_info.warps_per_sm,
      kernel_info.grid_x,
      kernel_info.grid_y,
      kernel_info.grid_z,
      kernel_info.block_x,
      kernel_info.block_y,
      kernel_info.block_z,
      kernel_info.occupancy * 100);
}

void ChromeTracingLogger::HandleTypeMemcpy(
    const DeviceTraceEventNode& device_node) {
  MemcpyEventInfo memcpy_info = device_node.MemcpyInfo();
  float memory_bandwidth = 0;
  if (device_node.Duration() > 0) {
    memory_bandwidth = memcpy_info.num_bytes * 1.0 / device_node.Duration();
  }
  float dur = nsToMsFloat(device_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": %lld,
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "cq_build_failed",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us",
      "stream": %d, "correlation id": %d,
      "bytes": %d, "memory bandwidth (GB/s)": %.3f
    }
  },
  )JSON"),
      device_node.Name().c_str(),
      dur_display.c_str(),
      device_node.DeviceId(),
      device_node.StreamId(),
      nsToUs(device_node.StartNs()),
      nsToUsFloat(device_node.Duration()),
      StringTracerEventType(device_node.Type()),
      nsToUsFloat(device_node.StartNs(), start_time_),
      nsToUsFloat(device_node.EndNs(), start_time_),
      device_node.StreamId(),
      device_node.CorrelationId(),
      memcpy_info.num_bytes,
      memory_bandwidth);
}

void ChromeTracingLogger::HandleTypeMemset(
    const DeviceTraceEventNode& device_node) {
  MemsetEventInfo memset_info = device_node.MemsetInfo();
  float dur = nsToMsFloat(device_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
    "name": "%s[%s]", "pid": %lld, "tid": %lld,
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s",
    "cname": "cq_build_failed",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us",
      "device": %d, "context": %d,
      "stream": %d, "correlation id": %d,
      "bytes": %d, "value": %d
    }
  },
  )JSON"),
      device_node.Name().c_str(),
      dur_display.c_str(),
      device_node.DeviceId(),
      device_node.StreamId(),
      nsToUs(device_node.StartNs()),
      nsToUsFloat(device_node.Duration()),
      StringTracerEventType(device_node.Type()),
      nsToUsFloat(device_node.StartNs(), start_time_),
      nsToUsFloat(device_node.EndNs(), start_time_),
      device_node.DeviceId(),
      device_node.ContextId(),
      device_node.StreamId(),
      device_node.CorrelationId(),
      memset_info.num_bytes,
      memset_info.value);
}

void ChromeTracingLogger::StartLog() {
  output_file_stream_ << std::string(
      R"JSON(
  {
    "displayTimeUnit": "ms",)JSON");
}

void ChromeTracingLogger::LogMetaInfo(const std::string& version,
                                      uint32_t span_indx) {
  output_file_stream_ << string_format(std::string(
                                           R"JSON(
    "schemaVersion": "%s",
    "span_indx": "%d",)JSON"),
                                       version.c_str(),
                                       span_indx);
}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
void ChromeTracingLogger::LogDeviceProperty(
    const std::map<uint32_t, gpuDeviceProp>& device_property_map) {
  // add device property information
  output_file_stream_ << std::string(R"JSON(
    "deviceProperties": [
    )JSON");
  auto device_nums = device_property_map.size();
  if (device_nums == 0) {
    output_file_stream_ << std::string(R"JSON(
      ],
    )JSON");
  }
#if defined(PADDLE_WITH_CUDA)
  for (auto it = device_property_map.begin(); it != device_property_map.end();
       it++) {
    const gpuDeviceProp& device_property = it->second;
    if (device_nums > 1) {
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
    {
      "id": %u, "name": "%s", "totalGlobalMem": %llu,
      "computeMajor": %d, "computeMinor": %d,
      "maxThreadsPerBlock": %d, "maxThreadsPerMultiprocessor": %d,
      "regsPerBlock": %d, "regsPerMultiprocessor": %d, "warpSize": %d,
      "sharedMemPerBlock": %d, "sharedMemPerMultiprocessor": %d,
      "smCount": %d, "sharedMemPerBlockOptin": %d
    },
  )JSON"),
          it->first,
          device_property.name,
          device_property.totalGlobalMem,
          device_property.major,
          device_property.minor,
          device_property.maxThreadsPerBlock,
          device_property.maxThreadsPerMultiProcessor,
          device_property.regsPerBlock,
          device_property.regsPerMultiprocessor,
          device_property.warpSize,
          device_property.sharedMemPerBlock,
          device_property.sharedMemPerMultiprocessor,
          device_property.multiProcessorCount,
          device_property.sharedMemPerBlockOptin);
    } else {
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
      {
        "id": %u, "name": "%s", "totalGlobalMem": %llu,
        "computeMajor": %d, "computeMinor": %d,
        "maxThreadsPerBlock": %d, "maxThreadsPerMultiprocessor": %d,
        "regsPerBlock": %d, "regsPerMultiprocessor": %d, "warpSize": %d,
        "sharedMemPerBlock": %d, "sharedMemPerMultiprocessor": %d,
        "smCount": %d, "sharedMemPerBlockOptin": %d
      }],
    )JSON"),
          it->first,
          device_property.name,
          device_property.totalGlobalMem,
          device_property.major,
          device_property.minor,
          device_property.maxThreadsPerBlock,
          device_property.maxThreadsPerMultiProcessor,
          device_property.regsPerBlock,
          device_property.regsPerMultiprocessor,
          device_property.warpSize,
          device_property.sharedMemPerBlock,
          device_property.sharedMemPerMultiprocessor,
          device_property.multiProcessorCount,
          device_property.sharedMemPerBlockOptin);
    }
    device_nums -= 1;
  }
#endif
#if defined(PADDLE_WITH_HIP)
  for (auto it = device_property_map.begin(); it != device_property_map.end();
       it++) {
    const gpuDeviceProp& device_property = it->second;
    if (device_nums > 1) {
      output_file_stream_ << string_format(std::string(
                                               R"JSON(
    {
      "id": %u, "name": "%s", "totalGlobalMem": %llu,
      "computeMajor": %d, "computeMinor": %d,
      "smCount": %d
    },
  )JSON"),
                                           it->first,
                                           device_property.name,
                                           device_property.totalGlobalMem,
                                           device_property.major,
                                           device_property.minor,
                                           device_property.multiProcessorCount);
    } else {
      output_file_stream_ << string_format(std::string(
                                               R"JSON(
      {
        "id": %u, "name": "%s", "totalGlobalMem": %llu,
        "computeMajor": %d, "computeMinor": %d,
        "smCount": %d
      }],
    )JSON"),
                                           it->first,
                                           device_property.name,
                                           device_property.totalGlobalMem,
                                           device_property.major,
                                           device_property.minor,
                                           device_property.multiProcessorCount);
    }
    device_nums -= 1;
  }
#endif
}
#endif

void ChromeTracingLogger::LogExtraInfo(
    const std::unordered_map<std::string, std::string> extra_info) {
  RefineDisplayName(extra_info);
  output_file_stream_ << std::string(
      R"JSON(
  {}
  ],
  )JSON");
  output_file_stream_ << std::string(R"JSON(
  "ExtraInfo": {)JSON");
  size_t count = extra_info.size();
  for (const auto& kv : extra_info) {
    if (count > 1) {
      output_file_stream_ << string_format(std::string(R"JSON(
     "%s": "%s",
   )JSON"),
                                           kv.first.c_str(),
                                           kv.second.c_str());
    } else {
      output_file_stream_ << string_format(std::string(R"JSON(
     "%s": "%s"
   )JSON"),
                                           kv.first.c_str(),
                                           kv.second.c_str());
    }
    count--;
  }
  output_file_stream_ << std::string(R"JSON(
  })JSON");
}

void ChromeTracingLogger::RefineDisplayName(
    std::unordered_map<std::string, std::string> extra_info) {
  for (auto it = pid_tid_set_.begin(); it != pid_tid_set_.end(); ++it) {
    output_file_stream_ << string_format(
        std::string(
            R"JSON(
  {
    "name": "process_name", "pid": %lld, "tid": "%lld(Python)",
    "ph": "M",
    "args": {
      "name": "Process %lld (CPU)"
    }
  },
  {
    "name": "process_name", "pid": %lld, "tid": "%lld(C++)",
    "ph": "M",
    "args": {
      "name": "Process %lld (CPU)"
    }
  },
   {
    "name": "thread_name", "pid": %lld, "tid": "%lld(Python)",
    "ph": "M",
    "args": {
      "name": "thread %lld:%s(Python)"
    }
  },
  {
    "name": "thread_name", "pid": %lld, "tid": "%lld(C++)",
    "ph": "M",
    "args": {
      "name": "thread %lld:%s(C++)"
    }
  },
  {
    "name": "process_sort_index", "pid": %lld, "tid": %lld,
    "ph": "M",
    "args": {
      "sort_index": %lld
    }
  },
  {
    "name": "thread_sort_index", "pid": %lld, "tid": "%lld(Python)",
    "ph": "M",
    "args": {
      "sort_index": %lld
    }
  },
  {
    "name": "thread_sort_index", "pid": %lld, "tid": "%lld(C++)",
    "ph": "M",
    "args": {
      "sort_index": %lld
    }
  },
  )JSON"),
        (*it).first,
        (*it).second,
        (*it).first,
        (*it).first,
        (*it).second,
        (*it).first,
        (*it).first,
        (*it).second,
        (*it).second,
        extra_info[string_format(std::string("%lld"), (*it).second)].c_str(),
        (*it).first,
        (*it).second,
        (*it).second,
        extra_info[string_format(std::string("%lld"), (*it).second)].c_str(),
        (*it).first,
        (*it).second,
        (*it).first,
        (*it).first,
        (*it).second,
        (*it).second * 2,
        (*it).first,
        (*it).second,
        (*it).second * 2 + 1);
  }

#ifdef PADDLE_WITH_MLU
  static std::string device_type("MLU");
#else
  static std::string device_type("GPU");
#endif

  for (auto it = deviceid_streamid_set_.begin();
       it != deviceid_streamid_set_.end();
       ++it) {
    output_file_stream_ << string_format(std::string(
                                             R"JSON(
  {
    "name": "process_name", "pid": %lld, "tid": %lld,
    "ph": "M",
    "args": {
      "name": "Deivce %lld (%s)"
    }
  },
   {
    "name": "thread_name", "pid": %lld, "tid": %lld,
    "ph": "M",
    "args": {
      "name": "stream %lld"
    }
  },
  {
    "name": "process_sort_index", "pid": %lld, "tid": %lld,
    "ph": "M",
    "args": {
      "sort_index": %lld
    }
  },
  {
    "name": "thread_sort_index", "pid": %lld, "tid": %lld,
    "ph": "M",
    "args": {
      "sort_index": %lld
    }
  },
  )JSON"),
                                         (*it).first,
                                         (*it).second,
                                         (*it).first,
                                         device_type.c_str(),
                                         (*it).first,
                                         (*it).second,
                                         (*it).second,
                                         (*it).first,
                                         (*it).second,
                                         (*it).first + 0x10000000,
                                         (*it).first,
                                         (*it).second,
                                         (*it).second);
  }
}

void ChromeTracingLogger::EndLog() {
  output_file_stream_ << std::string(
      R"JSON(
  }
  )JSON");
}

}  // namespace platform
}  // namespace paddle


text:
draft: true
title: "Alexisonfire, Funeral For A Friend & More"
date: 2015-09-29
categories: tnm-encore
description: "Because we miss you too much, we decided to hit you with a bonus podcast talking about Funeral For A Friend's split and Alexisonfire's return. See you again on Friday!"
soundcloud: 226032208
---


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Windows.Controls;

namespace BtrieveWrapper.Orm.Models.Generator.Gui.Controls
{
    public class IntegerRule : ValidationRule
    {
        public long Max { get; set; }
        public long Min { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
            try {
                var target = Convert.ToInt64(value);
                return new ValidationResult(target <= this.Max && target >= this.Min, null);
            } catch {
                return new ValidationResult(false, null);
            }
        }
    }
}


text:
package marubinotto.piggydb.ui.page.partial;

import static marubinotto.util.CollectionUtils.list;
import static marubinotto.util.web.WebUtils.escapeHtml;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import marubinotto.piggydb.model.Classification;
import marubinotto.piggydb.model.Filter;
import marubinotto.piggydb.model.Fragment;
import marubinotto.piggydb.model.Tag;
import marubinotto.piggydb.model.entity.RawFilter;
import marubinotto.piggydb.model.query.FragmentsAllButTrash;
import marubinotto.piggydb.model.query.FragmentsQuery;
import marubinotto.piggydb.model.query.FragmentsSortOption;
import marubinotto.piggydb.ui.wiki.DefaultWikiParser;
import marubinotto.piggydb.util.PiggydbUtils;
import marubinotto.util.RegexUtils;
import marubinotto.util.paging.Page;
import marubinotto.util.paging.PageUtils;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

public abstract class AbstractFragments extends AbstractPartial {

	//
	// Input
	//

	public String viewId;

	public Integer scale; // 0 - 1000

	public Integer orderBy;
	public Boolean ascending;
	public Boolean shuffle;
	private FragmentsSortOption sortOption;

	public int pi = 0;

	public static final String SK_SCALE = "fragmentsViewScale";
	public static final String SK_ORDERBY = "fragmentsViewOrderBy";
	public static final String SK_ASCENDING = "fragmentsViewAscending";

	public String query;
	public String tagsToInclude;
	public Boolean tagsToIncludeAnd;
	public String tagsToExclude;

	@Override
	public void onInit() {
		super.onInit();

		// restore the session values
		if (this.scale == null) {
			this.scale = (Integer)ObjectUtils.defaultIfNull(
				getContext().getSessionAttribute(SK_SCALE),
				getWarSetting().getDefaultFragmentsViewScale());
		}
		if (this.orderBy == null) {
			this.orderBy = (Integer)getContext().getSessionAttribute(SK_ORDERBY);
		}
		if (this.ascending == null) {
			this.ascending = (Boolean)getContext().getSessionAttribute(SK_ASCENDING);
		}

		// create a sortOption
		this.sortOption = new FragmentsSortOption(this.orderBy, this.ascending);
		if (this.shuffle != null) {
			this.sortOption.shuffle = this.shuffle;
		}

		if (isNotBlank(this.query)) {
		  this.query = modifyIfGarbledByTomcat(this.query);
		}
	}

	//
	// Model
	//

	public FragmentsView view;

	public String label = "";
	public boolean hideHeader = false;

	public Page<Fragment> fragments;
	public Classification contextTags;

	public boolean firstSet = true;
	public boolean lastSet = false;

	public String keywordRegex;

	public Filter filter;

	@Override
	protected void setModels() throws Exception {
		super.setModels();

		this.view = new FragmentsView(this.viewId);
		this.view.setScale(this.scale);

		setSelectedFragments();

		checkFragmentRef();
		this.filter = createFilter();
		if (this.fragments == null) setFragmentsByFilter();
		if (this.fragments == null) setFragments();

		if (this.fragments != null) {
			this.firstSet = (this.pi == 0);
			this.lastSet = this.fragments.isLastPage();
		}

		saveStateToSession();
	}

	private void checkFragmentRef() throws Exception {
	  if (isBlank(this.query)) return;

	  // query == "#<number>"
	  if (this.query.matches(DefaultWikiParser.PS_FRAGMENT_REF)) {
	    long id = Long.parseLong(this.query.substring(1));
	    Fragment fragment = getDomain().getFragmentRepository().get(id);
	    this.fragments = fragment != null ?
	      PageUtils.getPage(list(fragment), this.view.getPageSize(), this.pi) :
	      emptyFragments();
	    this.label = this.query;
	  }
	}

	private Page<Fragment> emptyFragments() {
	  return PageUtils.<Fragment>empty(this.view.getPageSize());
	}

  protected Filter createFilter() throws Exception {
    return null;
  }

	private void setFragmentsByFilter() throws Exception {
	  if (this.filter == null) return;

	  // add tags to include
	  if (isNotBlank(this.tagsToInclude)) {
	    this.tagsToInclude = modifyIfGarbledByTomcat(this.tagsToInclude);
	    for (String tagName : StringUtils.split(this.tagsToInclude, ',')) {
	      Tag tag = getTagByName(tagName);
	      if (tag == null) {
	        this.fragments = emptyFragments();
	        continue;
	      }
	      ((RawFilter)this.filter).getIncludes().addTag(tag);
	    }
	    if (this.tagsToIncludeAnd != null) {
	      ((RawFilter)this.filter).setAnd(this.tagsToIncludeAnd);
	    }
	  }
	  this.contextTags = this.filter.getIncludes();

	  // add tag to exclude
	  if (isNotBlank(this.tagsToExclude)) {
	    this.tagsToExclude = modifyIfGarbledByTomcat(this.tagsToExclude);
	    for (String tagName : StringUtils.split(this.tagsToExclude, ',')) {
	      Tag tag = getTagByName(tagName);
	      if (tag != null) {
	        ((RawFilter)this.filter).getExcludes().addTag(tag);
	      }
	    }
	  }

	  if (this.fragments != null) return;

	  // query
	  if (this.filter.isEmpty() && isBlank(this.query)) {
	    this.label = getMessage("all");
      FragmentsQuery query = getQuery(FragmentsAllButTrash.class);
      this.fragments = getPage(query);
      if (this.fragments.getTotalSize() == 0 && isBlank(this.query)) {
        this.hideHeader = true;
      }
	  }
	  else {
	    appendFilterLabel(this.filter);
	    marubinotto.piggydb.model.query.FragmentsByFilter query =
        (marubinotto.piggydb.model.query.FragmentsByFilter)getQuery(
          marubinotto.piggydb.model.query.FragmentsByFilter.class);
      query.setFilter(this.filter);
      if (isNotBlank(this.query)) {
        query.setKeywords(this.query);
        setKeywordRegex(this.query);
        appendKeywordSearchLabel();
      }
      this.fragments = getPage(query);
	  }
	}

	private Tag getTagByName(String name) throws Exception {
	  return isNotBlank(name) ? getDomain().getTagRepository().getByName(name.trim()) : null;
	}

	protected void setKeywordRegex(String keywords) {
	  StringBuilder keywordRegex = new StringBuilder();
    for (String word : PiggydbUtils.splitToKeywords(keywords)) {
      if (keywordRegex.length() > 0) keywordRegex.append("|");
      word = StringEscapeUtils.escapeJavaScript(word);
      word = RegexUtils.escapeRegex(word);
      keywordRegex.append(word);
    }
    this.keywordRegex = "(" + keywordRegex.toString() + ")";
	}

	protected FragmentsQuery getQuery(Class<? extends FragmentsQuery> queryClass)
	throws Exception {
		FragmentsQuery query = (FragmentsQuery)
			getDomain().getFragmentRepository().getQuery(queryClass);
		query.setSortOption(this.sortOption);
		query.setEagerFetching(this.view.needsEagerFetching());
		query.setEagerFetchingMore(this.view.needsEagerFetchingMore());
		return query;
	}

	protected Page<Fragment> getPage(FragmentsQuery query) throws Exception {
		return query.getPage(this.view.getPageSize(), this.pi);
	}

	protected void setFragments() throws Exception {
	}

	private void saveStateToSession() {
		if (this.scale != null) getContext().setSessionAttribute(SK_SCALE, this.scale);
		if (this.orderBy != null) getContext().setSessionAttribute(SK_ORDERBY, this.orderBy);
		if (this.ascending != null) getContext().setSessionAttribute(SK_ASCENDING, this.ascending);
	}

	protected static String makeKeywordSearchLabel(String keywords) {
	  String label = "  ";
    for (String keyword : PiggydbUtils.splitToKeywords(keywords)) {
      label += "\"" + keyword + "\" ";
    }
    return label.trim();
	}

	protected void appendKeywordSearchLabel() {
	  if (isBlank(this.query)) return;
	  if (isNotBlank(this.label)) {
	    this.label += " + ";
	  }
	  this.label += makeKeywordSearchLabel(this.query);
	}

	private String makeTagLabel(String tagName) {
	  return "  " + escapeHtml(tagName);
	}

	protected void appendFilterLabel(Filter filter) {
	  String separator = filter.isAnd() ? " & " : " | ";
	  separator = "" + separator + "";
	  boolean first = true;
	  for (Tag tag : filter.getIncludes()) {
	    if (first) {
	      first = false;
	    }
	    else {
	      this.label += separator;
	    }
	    this.label += makeTagLabel(tag.getName());
	  }
	}
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true,
});
exports.default = Fixture;
var React = require('react');

function Fixture() {
  return React.createElement(
    'div',
    null,
    React.createElement('p', { id: 'full' }, 'Test'),
    React.createElement('p', { id: 'empty' })
  );
}
module.exports = exports['default'];


text:
// Copyright 2013 Selenium committers
// Copyright 2013 Software Freedom Conservancy
//
// 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.

/**
 * @fileoverview An example test that may be run using Mocha. To run, you must
 * have the chromedriver installed on the system PATH.
 */

var assert = require('assert'),
    fs = require('fs');

var webdriver = require('..'),
    test = require('../testing'),
    remote = require('../remote');

test.describe('Google Search', function() {
  var driver;

  test.before(function() {
    driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();
  });

  test.it('should append query to title', function() {
    driver.get('http://www.google.com');
    driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
    driver.findElement(webdriver.By.name('btnG')).click();
    driver.wait(function() {
      return driver.getTitle().then(function(title) {
        return 'webdriver - Google Search' === title;
      });
    }, 1000);
  });

  test.after(function() { driver.quit(); });
});


text:
import Marionette from 'backbone.marionette';

import {features} from 'pageflow/frontend';

import {EncodingConfirmation} from '../models/EncodingConfirmation';
import {EntryPublication} from '../models/EntryPublication';
import {editor} from '../base';

import {ConfirmEncodingView} from '../views/ConfirmEncodingView';
import {EditEntryView} from '../views/EditEntryView';
import {EditMetaDataView} from '../views/EditMetaDataView';
import {EditWidgetView} from '../views/EditWidgetView';
import {FilesView} from '../views/FilesView';
import {PublishEntryView} from '../views/PublishEntryView';

import {state} from '$state';

export const SidebarController = Marionette.Controller.extend({
  initialize: function(options) {
    this.region = options.region;
    this.entry = options.entry;
  },

  index: function(storylineId) {
    this.region.show(new EditEntryView({
      model: this.entry,
      storylineId: storylineId
    }));
  },

  files: function(collectionName, handler, payload, filterName) {
    this.region.show(new FilesView({
      model: this.entry,
      selectionHandler: handler && editor.createFileSelectionHandler(handler, payload),
      tabName: collectionName,
      filterName: filterName
    }));

    editor.setDefaultHelpEntry('pageflow.help_entries.files');
  },

  confirmableFiles: function(preselectedFileType, preselectedFileId) {
    const model = EncodingConfirmation.createWithPreselection({
      fileType: preselectedFileType,
      fileId: preselectedFileId
    });

    model.check();

    this.region.show(ConfirmEncodingView.create({
      model
    }));
  },

  metaData: function(tab) {
    this.region.show(new EditMetaDataView({
      model: this.entry,
      tab: tab,
      state: state,
      features: features,
      editor: editor
    }));
  },

  publish: function() {
    this.region.show(PublishEntryView.create({
      model: this.entry,
      entryPublication: new EntryPublication()
    }));

    editor.setDefaultHelpEntry('pageflow.help_entries.publish');
  },

  widget: function(id) {
    this.region.show(new EditWidgetView({
      model: this.entry.widgets.get(id)
    }));
  },
});


text:
package yt.javi.fithdown.app.infrastructure.repositories.inmemory;

import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import yt.javi.fithdown.core.model.article.Article;
import yt.javi.fithdown.core.model.article.ArticleFactory;
import yt.javi.fithdown.core.model.article.ArticleId;

public class ArticleRepositoryInMemoryTest {

  private static final String ARTICLE_TITLE = "test";

  private static final String ARTICLE_CONTENT = "test";

  private static final String ARTICLE_ID = "test";

  private static final String ARTICLE_LINK = "http://test.ing";

  private static final List<String> ARTICLE_CATEGORIES = emptyList();

  private ArticleRepositoryInMemory repository;

  @Mock
  private SyndFeedInput feedInput;

  @Mock
  private ArticleFactory factory;

  @Mock
  private Article article;

  @Mock
  private ArticleId articleId;

  @Mock
  private SyndFeed feed;

  @Mock
  private SyndEntry entry;

  @Mock
  private SyndContent content;

  @Before
  public void setUp() throws Exception {
    initMocks(this);

    repository = new ArticleRepositoryInMemory(feedInput, factory);
  }

  @Test
  public void itIsPossibleToSaveAArticle() {
    when(articleId.getId()).thenReturn(ARTICLE_ID);
    when(article.getArticleId()).thenReturn(articleId);

    assertThat(repository.save(article), is(article));
  }

  @Test
  public void itIsPossibleToGetAnExistingArticleByItsId() {
    when(articleId.getId()).thenReturn(ARTICLE_ID);
    when(article.getArticleId()).thenReturn(articleId);
    repository.save(article);

    assertThat(repository.findById(ARTICLE_ID).orElse(null), is(article));
  }

  @Test
  public void itIsNotPossibleToGetANonExistingArticleByItsId() {
    assertThat(repository.findById("non_existing").isPresent(), is(false));
  }

  @Test
  public void itIsPossibleToGetAllArticles() {
    when(articleId.getId()).thenReturn(ARTICLE_ID);
    when(article.getArticleId()).thenReturn(articleId);
    repository.save(article);

    assertThat(repository.findAll(), hasItem(article));
  }

  @Test
  public void itIsPossibleToRemoveAnExistingArticle() {
    when(articleId.getId()).thenReturn(ARTICLE_ID);
    when(article.getArticleId()).thenReturn(articleId);
    repository.save(article);

    assertThat(repository.remove(article), is(true));
  }

  @Test
  public void itIsNotPossibleToRemoveANonExistingArticle() {
    when(articleId.getId()).thenReturn(ARTICLE_ID);
    when(article.getArticleId()).thenReturn(articleId);

    assertThat(repository.remove(article), is(false));
  }

  @Test
  public void itFetchesArticlesFromAGivenUrl() throws FeedException, MalformedURLException {
    when(feedInput.build(any(XmlReader.class))).thenReturn(feed);
    when(feed.getEntries()).thenReturn(singletonList(entry));
    when(entry.getPublishedDate()).thenReturn(new Date());
    when(entry.getLink()).thenReturn(ARTICLE_LINK);
    when(entry.getTitle()).thenReturn(ARTICLE_TITLE);
    when(entry.getDescription()).thenReturn(content);
    when(entry.getCategories()).thenReturn(emptyList());
    when(content.getValue()).thenReturn(ARTICLE_CONTENT);
    when(factory.getArticle(anyLong(), eq(ARTICLE_LINK), eq(ARTICLE_TITLE), eq(ARTICLE_CONTENT))).thenReturn(article);
    when(article.setCategories(ARTICLE_CATEGORIES)).thenReturn(article);

    assertThat(repository.fetchFromUrl(new URL("http://github.com")), hasItem(article));
  }
}


text:
package com.pivotallabs.util;

import java.io.*;

public class Strings {
    public static boolean isEmptyOrWhitespace(String s) {
        return (s == null) || (s.trim().length() == 0);
    }

    public static String fromStream(InputStream inputStream) throws IOException {
        char[] buffer = new char[0x10000];
        StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "UTF-8");
        int read;
        while ((read = in.read(buffer, 0, buffer.length)) > 0) {
            out.append(buffer, 0, read);
        }
        return out.toString();
    }

    public static InputStream asStream(String string) {
        return new ByteArrayInputStream(string.getBytes());
    }
}


text:
<?php

namespace Flarum\Http\Middleware;

use Dflydev\FigCookies\FigResponseCookies;
use Flarum\Http\CookieFactory;
use Illuminate\Support\Str;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Zend\Stratigility\MiddlewareInterface;

class StartSession implements MiddlewareInterface
{
    /**
     * @var CookieFactory
     */
    protected $cookie;

    /**
     * Rememberer constructor.
     * @param CookieFactory $cookie
     */
    public function __construct(CookieFactory $cookie)
    {
        $this->cookie = $cookie;
    }

    /**
     * {@inheritdoc}
     */
    public function __invoke(Request $request, Response $response, callable $out = null)
    {
        $session = $this->startSession();

        $request = $request->withAttribute('session', $session);

        $response = $out ? $out($request, $response) : $response;

        $response = $this->withCsrfTokenHeader($response, $session);

        return $this->withSessionCookie($response, $session);
    }

    private function startSession()
    {
        $session = new Session;

        $session->setName('flarum_session');
        $session->start();

        if (! $session->has('csrf_token')) {
            $session->set('csrf_token', Str::random(40));
        }

        return $session;
    }

    private function withCsrfTokenHeader(Response $response, SessionInterface $session)
    {
        if ($session->has('csrf_token')) {
            $response = $response->withHeader('X-CSRF-Token', $session->get('csrf_token'));
        }

        return $response;
    }

    private function withSessionCookie(Response $response, SessionInterface $session)
    {
        return FigResponseCookies::set(
            $response,
            $this->cookie->make($session->getName(), $session->getId())
        );
    }
}


text:
mockbrowser
===========

Mocks out some elements of the JavaScript environment in browsers. Useful for testing or hacking a client-side library into a node.js project.


text:
package consulo.ide.updateSettings.impl;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.SettingsEntryPointAction;
import com.intellij.ide.plugins.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.components.BorderLayoutPanel;
import consulo.awt.TargetAWT;
import consulo.container.plugin.PluginDescriptor;
import consulo.container.plugin.PluginId;
import consulo.container.plugin.PluginIds;
import consulo.container.plugin.PluginManager;
import consulo.ide.plugins.InstalledPluginsState;
import consulo.ide.plugins.PluginActionListener;
import consulo.ide.updateSettings.UpdateSettings;
import consulo.localize.LocalizeValue;
import consulo.logging.Logger;
import consulo.platform.base.localize.IdeLocalize;
import consulo.ui.Alerts;
import consulo.ui.UIAccess;
import consulo.ui.annotation.RequiredUIAccess;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @author VISTALL
 * @since 07-Nov-16
 */
public class PlatformOrPluginDialog extends DialogWrapper {
  private static final Logger LOG = Logger.getInstance(PlatformOrPluginDialog.class);

  private class OurPluginColumnInfo extends PluginManagerColumnInfo {
    public OurPluginColumnInfo(PluginTableModel model) {
      super(PluginManagerColumnInfo.COLUMN_NAME, model);
    }

    @Override
    public TableCellRenderer getRenderer(final PluginDescriptor pluginDescriptor) {
      return new PluginsTableRenderer(pluginDescriptor, true) {
        @Override
        protected void updatePresentation(boolean isSelected, @Nonnull PluginDescriptor pluginNode, TableModel model) {
          PlatformOrPluginNode node = ContainerUtil.find(myNodes, it -> it.getPluginId().equals(pluginDescriptor.getPluginId()));
          assert node != null;

          PluginDescriptor currentDescriptor = node.getCurrentDescriptor();
          if (currentDescriptor != null) {
            myCategory.setText(currentDescriptor.getVersion() + " " + UIUtil.rightArrow() + " " + (node.getFutureDescriptor() == null ? "??" : pluginNode.getVersion()));
          }
          else {
            myCategory.setText(pluginNode.getVersion());
          }

          FileStatus status = FileStatus.MODIFIED;
          if (myGreenStrategy.test(pluginNode.getPluginId())) {
            status = FileStatus.ADDED;
          }
          if (node.getFutureDescriptor() == null) {
            status = FileStatus.UNKNOWN;
          }

          myRating.setVisible(false);
          myDownloads.setVisible(false);

          if (!isSelected) myName.setForeground(TargetAWT.to(status.getColor()));
        }
      };
    }

    @Override
    public Comparator<PluginDescriptor> getComparator() {
      return null;
    }
  }

  private class OurPluginModel extends PluginTableModel {
    private OurPluginModel() {
      setSortKey(new RowSorter.SortKey(getNameColumn(), SortOrder.ASCENDING));
      super.columns = new ColumnInfo[]{new OurPluginColumnInfo(this)};
      view = new ArrayList<>();
    }

    @Override
    public void updatePluginsList(List<PluginDescriptor> list) {
      view.clear();
      filtered.clear();
      view.addAll(list);
      fireTableDataChanged();
    }

    @Override
    public int getNameColumn() {
      return 0;
    }

    @Override
    public boolean isPluginDescriptorAccepted(PluginDescriptor descriptor) {
      return true;
    }
  }

  @Nonnull
  private JComponent myRoot;
  @Nonnull
  private List<PlatformOrPluginNode> myNodes;
  @Nullable
  private Project myProject;
  @Nullable
  private Consumer<Collection<PluginDescriptor>> myAfterCallback;
  @Nullable
  private String myPlatformVersion;
  @Nonnull
  private Predicate<PluginId> myGreenStrategy;
  @Nonnull
  private PlatformOrPluginUpdateResult.Type myType;

  public PlatformOrPluginDialog(@Nullable Project project,
                                @Nonnull PlatformOrPluginUpdateResult updateResult,
                                @Nullable Predicate<PluginId> greenStrategy,
                                @Nullable Consumer<Collection<PluginDescriptor>> afterCallback) {
    super(project);
    myProject = project;
    myAfterCallback = afterCallback;
    myType = updateResult.getType();
    setTitle(updateResult.getType() == PlatformOrPluginUpdateResult.Type.PLUGIN_INSTALL ? IdeBundle.message("plugin.install.dialog.title") : IdeBundle.message("update.available.group"));

    myNodes = updateResult.getPlugins();

    if (greenStrategy != null) {
      myGreenStrategy = greenStrategy;
    }
    else {
      myGreenStrategy = pluginId -> {
        PluginDescriptor plugin = PluginManager.findPlugin(pluginId);
        boolean platform = PlatformOrPluginUpdateChecker.isPlatform(pluginId);
        return plugin == null && !platform;
      };
    }

    Set<PluginId> brokenPlugins = new HashSet<>();
    List<PluginDescriptor> toShowPluginList = new ArrayList<>();
    for (PlatformOrPluginNode node : myNodes) {
      PluginDescriptor futureDescriptor = node.getFutureDescriptor();
      if (futureDescriptor != null) {
        toShowPluginList.add(futureDescriptor);
      }
      else {
        brokenPlugins.add(node.getPluginId());

        toShowPluginList.add(node.getCurrentDescriptor());
      }

      if (PlatformOrPluginUpdateChecker.isPlatform(node.getPluginId())) {
        assert futureDescriptor != null;

        myPlatformVersion = futureDescriptor.getVersion();
      }
    }

    ContainerUtil.sort(toShowPluginList, (o1, o2) -> o1.getName().compareTo(o2.getName()));

    ContainerUtil.weightSort(toShowPluginList, pluginDescriptor -> {
      if (PlatformOrPluginUpdateChecker.isPlatform(pluginDescriptor.getPluginId())) {
        return 100;
      }

      if (brokenPlugins.contains(pluginDescriptor.getPluginId())) {
        return 200;
      }

      return 0;
    });

    OurPluginModel model = new OurPluginModel();
    model.updatePluginsList(toShowPluginList);

    PluginTable pluginList = new PluginTable(model);

    myRoot = JBUI.Panels.simplePanel().addToCenter(ScrollPaneFactory.createScrollPane(pluginList, true));
    setResizable(false);
    init();
  }

  @Override
  @RequiredUIAccess
  public void doOKAction() {
    super.doOKAction();

    PlatformOrPluginNode brokenPlugin = myNodes.stream().filter(c -> c.getFutureDescriptor() == null).findFirst().orElse(null);
    if (brokenPlugin != null) {
      if (Messages.showOkCancelDialog(myProject, "Few plugins will be not updated. Those plugins will be disabled after update. Are you sure?", "Consulo", Messages.getErrorIcon()) != Messages.OK) {
        return;
      }
    }

    UIAccess uiAccess = UIAccess.current();

    Task.Backgroundable.queue(myProject, IdeBundle.message("progress.download.plugins"), true, PluginManagerUISettings.getInstance(), indicator -> {
      List<PluginDescriptor> installed = new ArrayList<>(myNodes.size());

      List<PluginDownloader> forInstall = new ArrayList<>(myNodes.size());
      for (PlatformOrPluginNode platformOrPluginNode : myNodes) {
        PluginDescriptor pluginDescriptor = platformOrPluginNode.getFutureDescriptor();
        // update list contains broken plugins
        if (pluginDescriptor == null) {
          continue;
        }

        try {
          PluginDownloader downloader = PluginDownloader.createDownloader(pluginDescriptor, myPlatformVersion, myType != PlatformOrPluginUpdateResult.Type.PLUGIN_INSTALL);

          forInstall.add(downloader);

          downloader.download(indicator);
        }
        catch (PluginDownloadFailedException e) {
          uiAccess.give(() -> Alerts.okError(e.getLocalizeMessage()).showAsync());
          return;
        }
      }

      indicator.setTextValue(IdeLocalize.progressInstallingPlugins());

      Application application = Application.get();
      UpdateHistory updateHistory = application.getInstance(UpdateHistory.class);

      InstalledPluginsState installedPluginsState = InstalledPluginsState.getInstance();
      for (PluginDownloader downloader : forInstall) {
        try {
          // already was installed
          if (installedPluginsState.wasUpdated(downloader.getPluginId())) {
            continue;
          }

          installedPluginsState.getUpdatedPlugins().add(downloader.getPluginId());

          downloader.install(indicator, true);

          PluginDescriptor pluginDescriptor = downloader.getPluginDescriptor();

          if (pluginDescriptor instanceof PluginNode) {
            ((PluginNode)pluginDescriptor).setStatus(PluginNode.STATUS_DOWNLOADED);

            application.getMessageBus().syncPublisher(PluginActionListener.TOPIC).pluginInstalled(pluginDescriptor.getPluginId());

            if (myType == PlatformOrPluginUpdateResult.Type.PLUGIN_INSTALL && pluginDescriptor.isExperimental()) {
              updateHistory.setShowExperimentalWarning(true);
            }
          }

          installed.add(pluginDescriptor);
        }
        catch (IOException e) {
          uiAccess.give(() -> Alerts.okError(LocalizeValue.of(e.getLocalizedMessage())).showAsync());
          return;
        }
      }

      Map<String, String> pluginHistory = new HashMap<>();
      for (PluginDescriptor descriptor : PluginManager.getPlugins()) {
        if (PluginIds.isPlatformPlugin(descriptor.getPluginId())) {
          continue;
        }

        pluginHistory.put(descriptor.getPluginId().getIdString(), StringUtil.notNullize(descriptor.getVersion()));
      }

      pluginHistory.put(PlatformOrPluginUpdateChecker.getPlatformPluginId().getIdString(), ApplicationInfo.getInstance().getBuild().toString());

      updateHistory.replaceHistory(pluginHistory);

      if (myAfterCallback != null) {
        myAfterCallback.accept(installed);
      }

      if (myType != PlatformOrPluginUpdateResult.Type.PLUGIN_INSTALL) {
        SwingUtilities.invokeLater(() -> {
          UpdateSettings updateSettings = UpdateSettings.getInstance();
          updateSettings.setLastCheckResult(PlatformOrPluginUpdateResult.Type.RESTART_REQUIRED);

          SettingsEntryPointAction.updateState(updateSettings);

          if (PluginInstallUtil.showRestartIDEADialog() == Messages.YES) {
            Application.get().restart(true);
          }
        });
      }
    });
  }

  @Nullable
  @Override
  protected String getDimensionServiceKey() {
    setScalableSize(600, 300);
    return getClass().getSimpleName();
  }

  @Nullable
  @Override
  protected Border createContentPaneBorder() {
    return null;
  }

  @Nullable
  @Override
  protected JComponent createSouthPanel() {
    JComponent southPanel = super.createSouthPanel();
    if (southPanel != null) {
      southPanel.add(new JBLabel("Following nodes will be downloaded & installed"), BorderLayout.WEST);
      southPanel.setBorder(JBUI.Borders.empty(ourDefaultBorderInsets));

      BorderLayoutPanel borderLayoutPanel = JBUI.Panels.simplePanel(southPanel);
      borderLayoutPanel.setBorder(new CustomLineBorder(JBUI.scale(1), 0, 0, 0));
      return borderLayoutPanel;
    }
    return null;
  }

  @Nullable
  @Override
  protected JComponent createCenterPanel() {
    return myRoot;
  }
}